Example usage for java.util AbstractMap.SimpleImmutableEntry AbstractMap.SimpleImmutableEntry

List of usage examples for java.util AbstractMap.SimpleImmutableEntry AbstractMap.SimpleImmutableEntry

Introduction

In this page you can find the example usage for java.util AbstractMap.SimpleImmutableEntry AbstractMap.SimpleImmutableEntry.

Prototype

public SimpleImmutableEntry(K key, V value) 

Source Link

Document

Creates an entry representing a mapping from the specified key to the specified value.

Usage

From source file:com.epam.reportportal.gateway.CompositeInfoEndpoint.java

@RequestMapping(value = "/composite/{endpoint}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody//from   w w  w  .ja  v a  2 s.c o  m
public Map<String, ?> compose(@PathVariable("endpoint") String endpoint) {
    return discoveryClient.getServices().stream()
            .map((Function<String, AbstractMap.SimpleImmutableEntry<String, Object>>) service -> {
                try {
                    List<ServiceInstance> instances = discoveryClient.getInstances(service);
                    if (instances.isEmpty()) {
                        return new AbstractMap.SimpleImmutableEntry<>(service, "DOWN");
                    }
                    ServiceInstance instance = instances.get(0);
                    String protocol = instance.isSecure() ? "https" : "http";
                    HttpHeaders headers = new HttpHeaders();
                    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
                    return new AbstractMap.SimpleImmutableEntry<>(instance.getServiceId(),
                            loadBalancedRestTemplate.exchange(protocol + "://{service}/{endpoint}",
                                    HttpMethod.GET, new HttpEntity<>(null, headers), Map.class,
                                    instance.getServiceId(), endpoint).getBody());
                } catch (Exception e) {
                    return new AbstractMap.SimpleImmutableEntry<>(service, "DOWN");
                }
            }).collect(toMap(AbstractMap.SimpleImmutableEntry::getKey,
                    AbstractMap.SimpleImmutableEntry::getValue, (value1, value2) -> value2));

}

From source file:com.epam.reportportal.gateway.CompositeInfoEndpoint.java

private Map<String, ?> composeInfo() {
    return eurekaClient.getApplications().getRegisteredApplications().stream()
            .flatMap(app -> app.getInstances().stream()).map(instanceInfo -> {
                try {
                    HttpHeaders headers = new HttpHeaders();
                    headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
                    return new AbstractMap.SimpleImmutableEntry<>(instanceInfo.getAppName(),
                            restTemplate.exchange(instanceInfo.getStatusPageUrl(), HttpMethod.GET,
                                    new HttpEntity<>(null, headers), Map.class).getBody());
                } catch (Exception e) {
                    LOGGER.error("Unable to obtain service info", e);
                    return new AbstractMap.SimpleImmutableEntry<>(instanceInfo.getAppName(), "DOWN");
                }//from   ww w. j a v a 2s.  c  om
            }).collect(toMap(AbstractMap.SimpleImmutableEntry::getKey,
                    AbstractMap.SimpleImmutableEntry::getValue, (value1, value2) -> value2));
}

From source file:reactor.js.core.JavaScriptObject.java

@NotNull
@Override//from w  w  w  . j  a  v  a  2 s  .c om
public Set<Entry<String, Object>> entrySet() {
    MutableSet<Entry<String, Object>> entries = UnifiedSet.newSet();
    entries.addAll(properties.entrySet());
    propertySuppliers.forEachKeyValue((key, supplier) -> {
        if (!properties.containsKey(key)) {
            entries.add(new AbstractMap.SimpleImmutableEntry<>(key, supplier.get()));
        }
    });
    return entries.asUnmodifiable();
}

From source file:net.www_eee.portal.channels.ProxyChannel.java

/**
 * <p>/*from  w  ww .  ja  v a2s.c o  m*/
 * Rewrite a <code>linkURI</code> associated with a <code>proxiedFileURL</code>, if required.
 * </p>
 * 
 * <p>
 * Technically, there are two types of links within a document. First, a link within a document can be to an
 * <em>external resource</em>, which is loaded automatically by the browser to augment that document (ie a link to an
 * image, style sheet, script, etc). Or, second, a link within a document can be a <em>hyperlink</em>, which, when
 * activated by the user, will cause the browser to stop displaying that document and navigate to displaying the
 * linked document instead.
 * </p>
 * 
 * <p>
 * If the portal is configured to display a website to clients through this <code>ProxyChannel</code>, it is generally
 * expected that if the client navigates a hyperlink from one document to another within the proxied site, that the
 * linked document would also be rendered within the channel ({@linkplain net.www_eee.portal.Channel.Mode#VIEW view
 * mode}), and that any external resource links will continue to resolve correctly. Link rewriting is required for
 * each of these two scenarios to work.
 * </p>
 * 
 * <p>
 * To continue rendering within {@linkplain net.www_eee.portal.Channel.Mode#VIEW view mode} while navigating between
 * website documents, any hyperlink from within a proxied document to another document within the
 * {@linkplain #getProxiedBaseURI(Page.Request) proxied site} will, by default, be rewritten to point back through
 * this channel (alternatively, hyperlinks may {@linkplain #isLinkRewritingHyperlinksToChannelDisabled(Page.Request)
 * optionally} be resolved into an {@linkplain URI#isAbsolute() absolute} link pointing directly back to their
 * {@linkplain #getProxiedBaseURI(Page.Request) origin/source location} instead).
 * </p>
 * 
 * <p>
 * If this channel were to blindly return unmodified source HTML from a proxied document for aggregation into a
 * {@link Page}, any relative link would break when it was incorrectly resolved relative to the
 * {@link net.www_eee.portal.ContentDef.Page.Key#getPageURI(UriInfo, Map, String, boolean) URL} of that page, instead
 * of relative to the {@linkplain #BASE_URI_PROP base URL} of the document providing it. To avoid this, any relative
 * link to an external resource from within a proxied document will, by default, be resolved into an
 * {@linkplain URI#isAbsolute() absolute} link pointing directly back to the
 * {@linkplain #getProxiedBaseURI(Page.Request) origin/source location} for that resource (alternatively, resource
 * links may {@linkplain #isLinkRewritingResourceLinksToChannelEnabled(Page.Request) optionally} be rewritten to point
 * back through this channel using {@linkplain net.www_eee.portal.Channel.Mode#RESOURCE resource mode} instead).
 * </p>
 * 
 * <p>
 * For link rewriting to work, the <code>ProxyChannel</code> obviously needs to know which attributes of a proxied
 * document constitute <em>links</em>. But since the implementation is generic, and doesn't actually understand any
 * particular dialect of markup language on it's own, <em>including HTML</em>, you will likely want to configure this
 * channel alongside a plugin which does, such as the
 * {@linkplain net.www_eee.portal.channelplugins.ProxyChannelHTMLSource HTML plugin}.
 * </p>
 * 
 * @param pageRequest The {@link net.www_eee.portal.Page.Request Request} currently being processed.
 * @param proxiedFileURL The {@linkplain #getProxiedFileURL(Page.Request, Channel.Mode, boolean) proxied file URL}.
 * @param linkURI The {@link URI} of the link to rewrite.
 * @param hyperlink Is the <code>linkURI</code> a hyperlink?
 * @param absoluteURLRequired Does the result need to be {@linkplain URI#isAbsolute() absolute}?
 * @return A Map.Entry containing the rewritten link value, and a Boolean specifying if the returned link points back
 * through the channel.
 * @throws WWWEEEPortal.Exception If a problem occurred while determining the result.
 * @see #isLinkRewritingHyperlinksToChannelDisabled(Page.Request)
 * @see #isLinkRewritingResourceLinksToChannelEnabled(Page.Request)
 * @see net.www_eee.portal.channelplugins.ProxyChannelHTMLSource
 */
public Map.Entry<URI, Boolean> rewriteProxiedFileLink(final Page.Request pageRequest, final URL proxiedFileURL,
        final @Nullable URI linkURI, final boolean hyperlink, final boolean absoluteURLRequired)
        throws WWWEEEPortal.Exception {

    if ((linkURI != null) && (linkURI.isOpaque())) {
        return new AbstractMap.SimpleImmutableEntry<URI, Boolean>(linkURI, Boolean.FALSE); // Leave all the opaque ones alone (stuff like "mailto" links, etc), as we can't do anything with those.
    }

    final @NonNull URL resolvedLinkURL; // First, resolve the URL for the link so we know what server+file we are actually talking about here.
    try {
        if (linkURI == null) {
            resolvedLinkURL = proxiedFileURL; // An empty (null) link is equivalent to one back to the same proxied file.
        } else if (linkURI.isAbsolute()) {
            resolvedLinkURL = linkURI.toURL();
        } else {
            resolvedLinkURL = new URL(proxiedFileURL, linkURI.toString()); // Resolve the link relative to the file it came from.
        }
    } catch (MalformedURLException mue) {
        throw new ContentManager.ContentException("Error resolving proxied link URL", mue);
    }

    if (((hyperlink) && (isLinkRewritingHyperlinksToChannelDisabled(pageRequest)))
            || ((!hyperlink) && (!isLinkRewritingResourceLinksToChannelEnabled(pageRequest)))) {
        // We are configured to not write this link back through the portal.
        return new AbstractMap.SimpleImmutableEntry<URI, Boolean>(
                rewriteProxiedFileLinkOutsideChannel(pageRequest, proxiedFileURL, linkURI, hyperlink,
                        absoluteURLRequired, resolvedLinkURL),
                Boolean.FALSE);
    }

    /*
     * At this point, in order to determine what modifications to the link might be required, we need to figure out if
     * the link points to something either within, or outside of, the channel base URI's folder?
     */

    if ((linkURI != null) && (linkURI.isAbsolute()) && (!equalHostAndPort(resolvedLinkURL, proxiedFileURL))) {
        // This is an absolute link which doesn't even point to the same server as the proxied file.
        return new AbstractMap.SimpleImmutableEntry<URI, Boolean>(
                rewriteProxiedFileLinkOutsideChannel(pageRequest, proxiedFileURL, linkURI, hyperlink,
                        absoluteURLRequired, resolvedLinkURL),
                Boolean.FALSE);
    }

    /*
     * At this point we know the link at least points to the same server as the proxied file, but is it within the
     * channel base URI's folder?
     */

    final String resolvedLinkPath = StringUtil.toString(StringUtil.mkNull(resolvedLinkURL.getPath()), "/");

    final URI baseURI = getProxiedBaseURI(pageRequest);

    final URI resolvedBaseURI;
    if (baseURI.isAbsolute()) {
        resolvedBaseURI = baseURI;
    } else {
        resolvedBaseURI = ConfigManager.getContextResourceLocalHostURI(pageRequest.getUriInfo(),
                baseURI.getPath(), NetUtil.getQueryParams(baseURI), baseURI.getFragment(), true);
    }

    final String baseURIPath = resolvedBaseURI.getPath();

    final String baseURIFolder;
    if ((baseURIPath.length() == 1) || (baseURIPath.charAt(baseURIPath.length() - 1) == '/')) {
        baseURIFolder = baseURIPath; // Path is a folder.
    } else {
        final int lastSlashIndex = baseURIPath.lastIndexOf('/');
        baseURIFolder = (lastSlashIndex > 0) ? baseURIPath.substring(0, lastSlashIndex + 1)
                : String.valueOf('/');
    }

    if (!resolvedLinkPath.startsWith(baseURIFolder)) {
        // We have determined this link is not within the channel base URI folder.
        return new AbstractMap.SimpleImmutableEntry<URI, Boolean>(
                rewriteProxiedFileLinkOutsideChannel(pageRequest, proxiedFileURL, linkURI, hyperlink,
                        absoluteURLRequired, resolvedLinkURL),
                Boolean.FALSE);
    }

    /*
     * At this point we know the link points to within the channel base URI's folder, and that we need to rewrite it to
     * point back through the channel.
     */

    final String linkChannelLocalPath = StringUtil.mkNull(resolvedLinkPath.substring(baseURIFolder.length()));

    final Mode channelMode = ((hyperlink) && (!isMaximizationDisabled(pageRequest))) ? Mode.VIEW
            : Mode.RESOURCE;

    final ContentDef.ChannelSpec<?> channelSpec = pageRequest.getChannelSpec(this);
    return new AbstractMap.SimpleImmutableEntry<URI, Boolean>(
            channelSpec.getKey().getChannelURI(pageRequest.getUriInfo(), channelMode, linkChannelLocalPath,
                    (linkURI != null) ? NetUtil.getQueryParams(linkURI) : null,
                    (linkURI != null) ? linkURI.getFragment() : null, absoluteURLRequired),
            Boolean.TRUE);
}

From source file:net.www_eee.portal.channels.ProxyChannel.java

/**
 * Combine the {@linkplain net.www_eee.portal.Page.Request#getChannelLocalPath(Channel) channel local path} (or the
 * {@linkplain #getProxiedFilePathDefault(Page.Request) default path} if that's <code>null</code>) and
 * {@linkplain UriInfo#getQueryParameters() query parameters} from the client <code>pageRequest</code>, to construct a
 * URI containing a <em>relative</em> path and query params, which can later be resolved against the
 * {@linkplain #getProxiedBaseURI(Page.Request) base URI} to create the
 * {@linkplain #getProxiedFileURL(Page.Request, Channel.Mode, boolean) proxied file URL}. This method can also
 * <code>validate</code> the request against any {@linkplain #isParentFoldersRestrictionDisabled(Page.Request) parent
 * folder} or {@linkplain #isDefaultPathRestrictionEnabled(Page.Request) default path} restrictions.
 * /*from   www.  ja v  a  2  s .c om*/
 * @param pageRequest The {@link net.www_eee.portal.Page.Request Request} currently being processed.
 * @param mode The {@link net.www_eee.portal.Channel.Mode Mode} of the request.
 * @param validate Should any {@linkplain #isParentFoldersRestrictionDisabled(Page.Request) parent folder} or
 * {@linkplain #isDefaultPathRestrictionEnabled(Page.Request) default path} restrictions be evaluated?
 * @return The proxied file "local {@link URI}".
 * @throws WWWEEEPortal.Exception If a problem occurred while determining the result.
 * @throws WebApplicationException If a problem occurred while determining the result.
 * @see #getProxiedFileURL(Page.Request, Channel.Mode, boolean)
 * @see #PROXIED_FILE_LOCAL_URI_HOOK
 */
protected @Nullable URI getProxiedFileLocalURI(final Page.Request pageRequest, final Mode mode,
        final boolean validate) throws WWWEEEPortal.Exception, WebApplicationException {
    final URI channelLocalPath = pageRequest.getChannelLocalPath(this);
    final Object[] context = new Object[] { channelLocalPath, mode };
    URI proxiedFileLocalURI = PROXIED_FILE_LOCAL_URI_HOOK.value(plugins, context, pageRequest);
    if (proxiedFileLocalURI == null) {

        final URI proxiedFilePath;

        if (channelLocalPath != null) {
            if ((validate) && (isDefaultPathRestrictionEnabled(pageRequest))) { // The default path restriction applies to both view-mode and resource-mode requests.
                final URI proxiedFilePathDefault = getProxiedFilePathDefault(pageRequest);
                if (!channelLocalPath.equals(proxiedFilePathDefault)) {
                    throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN)
                            .entity("Request outside default path").type("text/plain").build());
                }
            }
            if ((validate) && (!isParentFoldersRestrictionDisabled(pageRequest))) {
                if (!isRelativeSubPath(channelLocalPath.getPath())) {
                    throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN)
                            .entity("Request outside base URL folder").type("text/plain").build());
                }
            }
            proxiedFilePath = channelLocalPath;
        } else if (Mode.VIEW.equals(mode)) {
            proxiedFilePath = getProxiedFilePathDefault(pageRequest);
        } else {
            proxiedFilePath = null; // The default path only applies to the view, and isn't used for resource requests.
        }

        final Map<String, List<String>> reqParameters = (pageRequest.isMaximized(this))
                ? pageRequest.getUriInfo().getQueryParameters()
                : null;
        if ((validate) && (isDefaultPathRestrictionEnabled(pageRequest)) && (reqParameters != null)
                && (!reqParameters.isEmpty())) {
            throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN)
                    .entity("Request outside default path").type("text/plain").build());
        }

        if ((proxiedFilePath == null) && ((reqParameters == null) || (reqParameters.isEmpty())))
            return null;

        final StringBuffer proxiedFileLocalURIBuffer = (proxiedFilePath != null)
                ? new StringBuffer(proxiedFilePath.toString())
                : new StringBuffer();
        if ((reqParameters != null) && (!reqParameters.isEmpty()))
            proxiedFileLocalURIBuffer.append(reqParameters.entrySet().stream()
                    .flatMap((entry) -> entry.getValue().stream().<Map.Entry<String, String>>map(
                            (i) -> new AbstractMap.SimpleImmutableEntry<String, String>(entry.getKey(), i)))
                    .map((entry) -> NetUtil.urlEncode(entry.getKey()) + '='
                            + NetUtil.urlEncode(entry.getValue()))
                    .collect(Collectors.joining("&", "?", ""))); //TODO proxied parameter blacklist

        try {
            proxiedFileLocalURI = new URI(proxiedFileLocalURIBuffer.toString());
        } catch (URISyntaxException urise) {
            throw new WWWEEEPortal.SoftwareException(urise);
        }

    }
    proxiedFileLocalURI = PROXIED_FILE_LOCAL_URI_HOOK.filter(plugins, context, pageRequest,
            proxiedFileLocalURI);
    return proxiedFileLocalURI;
}

From source file:org.janusgraph.util.datastructures.RangeInterval.java

private Map.Entry<T, Boolean> comparePoints(T one, boolean oneIncl, T two, boolean twoIncl,
        boolean chooseBigger) {
    if (one == null)
        return new AbstractMap.SimpleImmutableEntry(two, twoIncl);
    if (two == null)
        return new AbstractMap.SimpleImmutableEntry(one, oneIncl);
    int c = ((Comparable) one).compareTo(two);
    if (c == 0) {
        return new AbstractMap.SimpleImmutableEntry(one, oneIncl & twoIncl);
    } else if ((c > 0 && chooseBigger) || (c < 0 && !chooseBigger)) {
        return new AbstractMap.SimpleImmutableEntry(one, oneIncl);
    } else {/*www .j a  v  a2s  .c o m*/
        return new AbstractMap.SimpleImmutableEntry(two, twoIncl);
    }
}

From source file:org.languagetool.language.LanguageIdentifier.java

/**
 * @return language or {@code null} if language could not be identified
 * @param noopLangsTmp list of codes that are detected but will lead to the NoopLanguage that has no rules
 * @since 4.4 (new parameter noopLangs, changed return type to DetectedLanguage)
 *//*from  w w w  . j a  v a  2 s  .c  o m*/
@Nullable
public DetectedLanguage detectLanguage(String text, List<String> noopLangsTmp, List<String> preferredLangsTmp) {
    Objects.requireNonNull(noopLangsTmp);
    Objects.requireNonNull(preferredLangsTmp);
    // Chrome sends 'nn' (Nynorsk) or 'nb' (Bokmal), but fasttext detects 'no', so we have to map, and 
    // Bokmal seems to be the standard variant:
    List<String> noopLangs = noopLangsTmp.stream().map(k -> k.equals("nb") ? "no" : k)
            .collect(Collectors.toList());
    List<String> preferredLangs = preferredLangsTmp.stream().map(k -> k.equals("nb") ? "no" : k)
            .collect(Collectors.toList());
    if (preferredLangs.stream().anyMatch(k -> k.contains("-"))) {
        throw new IllegalArgumentException(
                "preferredLanguages may only contain language codes without variants (e.g. 'en', but not 'en-US'): "
                        + preferredLangs + ". Use 'preferredVariants' to specify variants");
    }
    String shortText = text.length() > maxLength ? text.substring(0, maxLength) : text;
    shortText = textObjectFactory.forText(shortText).toString();
    shortText = shortText.replaceAll("\uFEFF+", " "); // used by the browser add-on to filter HTML etc. (_ignoreText() in validator.js)
    Map.Entry<String, Double> result = null;
    if (fasttextEnabled) {
        try {
            Map<String, Double> scores = runFasttext(shortText, noopLangs);
            result = getHighestScoringResult(scores);
            if (result.getValue().floatValue() < THRESHOLD) {
                //System.out.println(text + " ->" + result.getValue().floatValue() + " " + result.getKey());
                CommonWords commonWords = new CommonWords();
                Map<Language, Integer> lang2Count = commonWords.getKnownWordsPerLanguage(text);
                //System.out.println("-> "+ lang2Count);
                for (Map.Entry<Language, Integer> entry : lang2Count.entrySet()) {
                    String langCode = entry.getKey().getShortCode();
                    if (scores.containsKey(langCode)) {
                        // this looks arbitrary, but gave best results with evaluation (LanguageDetectionMinLengthEval):
                        scores.put(langCode, scores.get(langCode) + Double.valueOf(entry.getValue()));
                    } else {
                        scores.put(langCode, Double.valueOf(entry.getValue()));
                    }
                }
                result = getHighestScoringResult(scores);
            }
            if (text.length() < CONSIDER_ONLY_PREFERRED_THRESHOLD && preferredLangs.size() > 0) {
                //System.out.println("remove? " + preferredLangs + " <-> " + scores);
                scores.keySet().removeIf(k -> !preferredLangs.contains(k));
                //System.out.println("-> " + b + " ==> " + scores);
                result = getHighestScoringResult(scores);
            }
            // Calculate a trivial confidence value because fasttext's confidence is often
            // wrong for short text (e.g. 0.99 for a test that's misclassified). Don't
            // use 1.0 because we can never be totally sure...
            double newScore = 0.99 / (30.0 / Math.min(text.length(), 30));
            //System.out.println("fasttext  : " + result);
            //System.out.println("newScore  : " + newScore);
            result = new AbstractMap.SimpleImmutableEntry<>(result.getKey(), newScore);
        } catch (Exception e) {
            fasttextEnabled = false;
            RuleLoggerMessage msg = new RuleErrorNotification(this.getClass().getSimpleName(), "-", String
                    .format("Fasttext disabled, failed on '%s': %s", text, ExceptionUtils.getStackTrace(e)));
            RuleLoggerManager.getInstance().log(msg, Level.WARNING);
            fasttextProcess.destroy();
        }
    }
    if (!fasttextEnabled) { // no else, value can change in if clause
        result = detectLanguageCode(shortText);
        if (noopLangs.size() > 0) {
            logger.warn("Cannot consider noopLanguages because not in fastText mode: " + noopLangs);
        }
    }
    if (result != null && result.getKey() != null && canLanguageBeDetected(result.getKey(), noopLangs)) {
        return new DetectedLanguage(null, Languages.getLanguageForShortCode(result.getKey(), noopLangs),
                result.getValue().floatValue());
    } else {
        return null;
    }
}

From source file:org.languagetool.language.LanguageIdentifier.java

private Map.Entry<String, Double> getHighestScoringResult(Map<String, Double> probs) {
    String result = null;/*w ww. j av  a 2s. co  m*/
    double max = -1;
    for (Map.Entry<String, Double> entry : probs.entrySet()) {
        if (entry.getValue() > max) {
            max = entry.getValue();
            result = entry.getKey();
        }
    }
    return new AbstractMap.SimpleImmutableEntry<>(result, max);
}

From source file:org.languagetool.language.LanguageIdentifier.java

/**
 * @return language or {@code null} if language could not be identified
 *///from   w w w  .  ja  va 2  s. c o  m
@Nullable
private Map.Entry<String, Double> detectLanguageCode(String text) {
    List<com.optimaize.langdetect.DetectedLanguage> lang = languageDetector.getProbabilities(text);
    // comment in for debugging:
    //System.out.println(languageDetector.getProbabilities(textObject));
    if (lang.size() > 0) {
        String code = lang.get(0).getLocale().getLanguage();
        double prob = lang.get(0).getProbability();
        return new AbstractMap.SimpleImmutableEntry<>(code, prob);
    } else {
        return null;
    }
}

From source file:org.rakam.client.builder.document.SlateDocumentGenerator.java

private Map<OperationIdentifier, Map<String, String>> generateExampleUsages() throws IOException {
    Map<OperationIdentifier, Map<String, String>> templates = Maps.newHashMap();

    Map<String, Entry<CodegenConfig, DefaultGenerator>> languages = new HashMap<>();

    for (CodegenConfigurator configurator : configurators) {
        ClientOptInput clientOptInput = configurator.toClientOptInput();
        clientOptInput.getConfig().processOpts();

        DefaultGenerator defaultGenerator = new DefaultGenerator();
        defaultGenerator.opts(clientOptInput);

        if (!supportedLanguages.contains(configurator.getLang())) {
            throw new IllegalArgumentException(
                    format("Language %s is not supported at the moment.", configurator.getLang()));
        }//from w  ww .  j  a  va 2s .  c  o m

        languages.put(configurator.getLang(),
                new AbstractMap.SimpleImmutableEntry<>(clientOptInput.getConfig(), defaultGenerator));

        if (swagger == null) {
            swagger = clientOptInput.getSwagger();
        }
    }

    for (Entry<String, Entry<CodegenConfig, DefaultGenerator>> entry : languages.entrySet()) {
        String language = entry.getKey();
        Entry<CodegenConfig, DefaultGenerator> value = entry.getValue();

        Map<String, List<CodegenOperation>> operations = value.getValue().processPaths(swagger.getPaths());
        for (String parentTag : operations.keySet()) {
            List<CodegenOperation> ops = operations.get(parentTag);
            for (CodegenOperation op : ops) {
                Map<String, Object> operation = value.getValue().processOperations(value.getKey(), parentTag,
                        ImmutableList.of(op));

                operation.put("modelPackage", value.getKey().modelPackage());
                operation.put("classname", value.getKey().toApiName(parentTag));
                operation.put("hostname", swagger.getHost());

                for (String templateName : value.getKey().apiTemplateFiles().keySet()) {
                    String filename = value.getKey().apiFilename(templateName, parentTag);
                    if (!value.getKey().shouldOverwrite(filename) && new File(filename).exists()) {
                        continue;
                    }

                    String template;
                    URL resource = this.getClass().getClassLoader()
                            .getResource("templates/" + language + "_api_example.mustache");

                    template = Resources.toString(resource, StandardCharsets.UTF_8);

                    Template tmpl = Mustache.compiler()
                            .withLoader(name -> value.getValue().getTemplateReader(
                                    value.getKey().templateDir() + File.separator + name + ".mustache"))
                            .defaultValue("").compile(template);

                    templates.computeIfAbsent(new OperationIdentifier(op.path, op.httpMethod),
                            key -> Maps.newHashMap()).put(language, tmpl.execute(operation));
                }
            }
        }
    }

    return templates;
}