Example usage for java.util Map getOrDefault

List of usage examples for java.util Map getOrDefault

Introduction

In this page you can find the example usage for java.util Map getOrDefault.

Prototype

default V getOrDefault(Object key, V defaultValue) 

Source Link

Document

Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

Usage

From source file:my.school.spring.rest.controllers.UseSchedulesCondition.java

@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {

    final Map<String, Object> annotationAttributes = Optional
            .ofNullable(metadata.getAnnotationAttributes(UseSchedules.class.getName())).orElse(new HashMap<>());
    Boolean isScheduledInstance = (Boolean) annotationAttributes.getOrDefault("value", false);

    Boolean allowScheduled = Optional
            .ofNullable(context.getEnvironment().getProperty("setup.versionProvider.scheduled", Boolean.class))
            .orElse(false);//from  ww  w  . j av  a2  s . com
    final boolean scheduled = Objects.equals(allowScheduled, isScheduledInstance);
    LOG.info("Application will reuse {} implementation of the VersionProvider",
            (scheduled) ? "SCHEDULED" : "NOT SCHEDULED");
    return scheduled;
}

From source file:org.obiba.mica.variable.search.EsPublishedDatasetVariableService.java

public Map<String, Long> getCountByStudyIds(List<String> studyIds) {
    Searcher.DocumentResults results = executeCountQuery(buildStudiesFilteredQuery(studyIds));
    if (results == null)
        return studyIds.stream().collect(Collectors.toMap(s -> s, s -> 0L));

    Map<String, Long> aggs = results.getAggregation(STUDY_ID_FIELD);
    return studyIds.stream().collect(Collectors.toMap(s -> s, s -> aggs.getOrDefault(s, 0L)));
}

From source file:it.larusba.neo4j.jdbc.http.driver.Neo4jResponse.java

/**
 * Construct the object directly from the HttpResponse.
 *
 * @param response Http response//from   www  .  j  a va 2s  .c o  m
 * @param mapper   Jackson object mapper
 * @throws SQLException
 */
public Neo4jResponse(HttpResponse response, ObjectMapper mapper) throws SQLException {
    // Parse response headers
    if (response.getStatusLine() != null) {

        // SAve the http code
        this.code = response.getStatusLine().getStatusCode();

        // If status code is 201, then we retrieve the Location header to keep the transaction url.
        if (this.code == HttpStatus.SC_CREATED) {
            this.location = response.getFirstHeader("Location").getValue();
        }

        // Parsing the body
        HttpEntity json = response.getEntity();
        if (json != null) {
            try (InputStream is = json.getContent()) {
                Map body = mapper.readValue(is, Map.class);

                // Error parsing
                this.errors = new ArrayList<>();
                for (Map<String, String> error : (List<Map<String, String>>) body.get("errors")) {
                    errors.add(new SQLException(error.getOrDefault("messages", ""),
                            error.getOrDefault("code", "")));
                }

                // Data parsing
                this.results = new ArrayList<>();
                for (Map map : (List<Map>) body.get("results")) {
                    results.add(new Neo4jResult(map));
                }

            } catch (Exception e) {
                throw new SQLException(e);
            }
        }

    } else {
        throw new SQLException("Receive request without status code ...");
    }
}

From source file:io.apiman.gateway.engine.vertx.polling.fetchers.HttpResourceFetcher.java

public HttpResourceFetcher(Vertx vertx, URI uri, Map<String, String> config, boolean isHttps) {
    this.vertx = vertx;
    this.uri = uri;
    this.isHttps = isHttps;
    this.config = config;

    String authString = config.getOrDefault("auth", "NONE").toUpperCase();
    Arguments.require(EnumUtils.isValidEnum(AuthType.class, authString),
            "auth must be one of: " + AuthType.all());
    authenticator = AuthType.valueOf(authString).getAuthenticator();
    authenticator.validateConfig(config);
}

From source file:org.polyfill.services.FinancialTimesPolyfillLoaderService.java

private boolean getIsTestable(Map<String, Object> meta) {
    Map<String, Object> testMap = getMap(meta, TEST_KEY);
    String testsSource = getString(meta, TESTS_SOURCE_KEY);
    return testsSource != null && !testsSource.isEmpty() && (Boolean) testMap.getOrDefault("ci", true);
}

From source file:com.ostrichemulators.jfxhacc.engine.impl.RdfDataEngine.java

/**
 * Dumps the data to the given file. If the file is null, dumps it in NTriples
 * format to stdout. If the file isn't null, the extension is used to
 * determine the format (either nt, ttl, or rdf). If the extension parsing
 * fails for whatever reason, the dump will be in NTriples format
 *
 * @param de/*from w  ww .  ja  va 2  s .c o  m*/
 * @param out
 * @throws IOException
 */
public void dump(File out) throws RepositoryException, IOException {
    String ext = (null == out ? "nt" : FilenameUtils.getExtension(out.getName()).toLowerCase());
    Map<String, RDFFormat> map = new HashMap<>();
    map.put("ttl", RDFFormat.TURTLE);
    map.put("rdf", RDFFormat.RDFXML);

    RDFFormat fmt = map.getOrDefault(ext, NTRIPLES);
    try (Writer w = (null == out ? new PrintWriter(System.out) : new FileWriter(out))) {
        RDFHandler handler = null;
        if (RDFFormat.RDFXML == fmt) {
            handler = new RDFXMLWriter(w);
        } else if (RDFFormat.TURTLE == fmt) {
            handler = new TurtleWriter(w);
        } else {
            handler = new NTriplesWriter(w);
        }

        try {
            rc.export(handler);
        } catch (RDFHandlerException re) {
            log.error(re, re);
        }
    }
}

From source file:org.apache.metron.parsers.syslog.Syslog5424Parser.java

@Override
public void configure(Map<String, Object> config) {
    // Default to OMIT policy for nil fields
    // this means they will not be in the returned field set
    String nilPolicyStr = (String) config.getOrDefault(NIL_POLICY_CONFIG, NilPolicy.OMIT.name());
    NilPolicy nilPolicy = NilPolicy.valueOf(nilPolicyStr);
    syslogParser = new SyslogParserBuilder().withNilPolicy(nilPolicy)
            .withDeviations(EnumSet.of(AllowableDeviations.PRIORITY, AllowableDeviations.VERSION)).build();
}

From source file:io.stallion.plugins.flatBlog.contacts.NotificationEmailer.java

private void build() {
    int totalCount = 0;

    String siteName = Settings.instance().getSiteName();
    if (siteName.length() > 25) {
        try {//ww  w.  j  a va  2s  . co  m
            siteName = new URL(Settings.instance().getSiteUrl()).getHost();
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    Map<String, Integer> counts = map();
    Map<String, String> singleToPlural = map();

    for (NotificationCallbackResult result : results) {
        counts.put(result.getThing(), counts.getOrDefault(result.getThing(), 0) + 1);
        singleToPlural.put(result.getThing(), result.getThingPlural());
    }

    StringBuffer subjectBuilder = new StringBuffer();
    if (results.size() > 1) {
        subjectBuilder.append(results.size() + " updates from \"" + siteName + "\": ");
    } else {
        subjectBuilder.append("Update from \"" + siteName + "\": ");
    }
    for (Map.Entry<String, Integer> entry : counts.entrySet()) {
        if (entry.getValue() > 1) {
            subjectBuilder.append(entry.getValue() + " " + singleToPlural.get(entry.getKey()));
        } else {
            subjectBuilder.append("1 " + entry.getKey());
        }
        subjectBuilder.append(", ");
    }
    subject = subjectBuilder.toString();
    subject = StringUtils.strip(StringUtils.strip(subject, " "), ",");
}

From source file:io.stallion.services.DynamicSettings.java

public String get(String group, String name) {
    group = GeneralUtils.slugify(group);
    checkLoadUpdated();//w ww .ja v a2  s  .  c o m
    if (!settingsMap.containsKey(group)) {
        return null;
    }
    Map<String, Object> groupMap = settingsMap.get(group);
    Object val = groupMap.getOrDefault(name, null);
    if (val != null) {
        if (val instanceof String) {
            return (String) val;
        } else {
            return val.toString();
        }
    } else {
        return null;
    }
}

From source file:org.cryptomator.frontend.webdav.mount.WindowsWebDavMounter.java

@Override
public WebDavMount mount(URI uri, Map<MountParam, Optional<String>> mountParams) throws CommandFailedException {
    final String driveLetter = mountParams.getOrDefault(MountParam.WIN_DRIVE_LETTER, Optional.empty())
            .orElse(AUTO_ASSIGN_DRIVE_LETTER);
    if (driveLetters.getOccupiedDriveLetters().contains(CharUtils.toChar(driveLetter))) {
        throw new CommandFailedException("Drive letter occupied.");
    }//from  w  w  w  . j a v  a  2s. c o  m

    final String hostname = mountParams.getOrDefault(MountParam.HOSTNAME, Optional.empty()).orElse(LOCALHOST);
    try {
        final URI adjustedUri = new URI(uri.getScheme(), uri.getUserInfo(), hostname, uri.getPort(),
                uri.getPath(), uri.getQuery(), uri.getFragment());
        CommandResult mountResult = mount(adjustedUri, driveLetter);
        return new WindowsWebDavMount(
                AUTO_ASSIGN_DRIVE_LETTER.equals(driveLetter) ? getDriveLetter(mountResult.getStdOut())
                        : driveLetter);
    } catch (URISyntaxException e) {
        throw new IllegalArgumentException("Invalid host: " + hostname);
    }
}