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:com.github.thesmartenergy.sparql.generate.api.Fetch.java

@GET
public Response doFetch(@Context Request r, @Context HttpServletRequest request,
        @DefaultValue("http://localhost:8080/sparql-generate/example/example1") @QueryParam("uri") String uri,
        @DefaultValue("*/*") @QueryParam("useaccept") String useaccept,
        @DefaultValue("") @QueryParam("accept") String accept) throws IOException {

    HttpURLConnection con;// ww  w  .j a v a2  s .  c  om
    String message = null;
    URL obj;
    try {
        obj = new URL(uri);
        con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        con.setRequestProperty("Accept", useaccept);
        con.setInstanceFollowRedirects(true);
        System.out.println("GET to " + uri + " returned " + con.getResponseCode());
        InputStream in = con.getInputStream();
        message = IOUtils.toString(in);
    } catch (IOException e) {
        return Response.status(Response.Status.BAD_REQUEST)
                .entity("Error while trying to access message at URI <" + uri + ">: " + e.getMessage()).build();
    }

    Map<String, List<String>> headers = con.getHeaderFields();
    if (!headers.containsKey("Link")) {
        return Response.status(Response.Status.BAD_REQUEST).entity(
                "Error while processing message at URI <" + uri + ">: there should be a Link header field")
                .build();
    }
    String var = null;
    URL qobj = null;
    for (String linkstr : headers.get("Link")) {
        Link link = Link.valueOf(linkstr);
        if (link.getRels().contains("https://w3id.org/sparql-generate/voc#spargl-query")
                || link.getRels().contains("spargl-query")) {
            Map<String, String> params = link.getParams();
            // check the context
            // check syntax for variable ?
            var = params.getOrDefault("var", "message");
            // ok for relative and absolute URIs ?
            try {
                qobj = obj.toURI().resolve(link.getUri()).toURL();
                System.out.println("found link " + qobj + " and var " + var);
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
            break;
        }
        // what if multiple suitable links ? 
    }

    if (var == null || qobj == null) {
        return Response.status(Response.Status.BAD_REQUEST).entity("Error while processing message at URI <"
                + uri
                + ">: did not find a suitable link with relation spargl-query, or https://w3id.org/sparql-generate/voc#spargl-query")
                .build();
    }

    HttpURLConnection qcon;
    String query;
    try {
        qcon = (HttpURLConnection) qobj.openConnection();
        qcon.setRequestMethod("GET");
        qcon.setRequestProperty("Accept", "application/sparql-generate");
        qcon.setInstanceFollowRedirects(true);
        System.out.println("GET to " + qobj + " returned " + qcon.getResponseCode());
        InputStream in = qcon.getInputStream();
        query = IOUtils.toString(in);
    } catch (IOException e) {
        return Response.status(Response.Status.BAD_REQUEST)
                .entity("Error while trying to access query at URI <" + qobj + ">: " + e.getMessage()).build();
    }

    System.out.println("got query " + query);

    // parse the SPARQL-Generate query and create plan
    PlanFactory factory = new PlanFactory();

    Syntax syntax = SPARQLGenerate.SYNTAX;
    SPARQLGenerateQuery q = (SPARQLGenerateQuery) QueryFactory.create(query, syntax);
    if (q.getBaseURI() == null) {
        q.setBaseURI("http://example.org/");
    }
    RootPlan plan = factory.create(q);

    // create the initial model
    Model model = ModelFactory.createDefaultModel();

    // if content encoding is not text-based, then use base64 encoding
    // use con.getContentEncoding() for this

    String dturi = "http://www.w3.org/2001/XMLSchema#string";
    String ct = con.getContentType();
    if (ct != null) {
        dturi = "urn:iana:mime:" + ct;
    }

    QuerySolutionMap initialBinding = new QuerySolutionMap();
    TypeMapper typeMapper = TypeMapper.getInstance();
    RDFDatatype dt = typeMapper.getSafeTypeByName(dturi);
    Node arqLiteral = NodeFactory.createLiteral(message, dt);
    RDFNode jenaLiteral = model.asRDFNode(arqLiteral);
    initialBinding.add(var, jenaLiteral);

    // execute the plan
    plan.exec(initialBinding, model);

    System.out.println(accept);
    if (!accept.equals("text/turtle") && !accept.equals("application/rdf+xml")) {
        List<Variant> vs = Variant
                .mediaTypes(new MediaType("application", "rdf+xml"), new MediaType("text", "turtle")).build();
        Variant v = r.selectVariant(vs);
        accept = v.getMediaType().toString();
    }

    System.out.println(accept);
    StringWriter sw = new StringWriter();
    Response.ResponseBuilder res;
    if (accept.equals("application/rdf+xml")) {
        model.write(sw, "RDF/XML", "http://example.org/");
        res = Response.ok(sw.toString(), "application/rdf+xml");
        res.header("Content-Disposition", "filename= message.rdf;");
        return res.build();
    } else {
        model.write(sw, "TTL", "http://example.org/");
        res = Response.ok(sw.toString(), "text/turtle");
        res.header("Content-Disposition", "filename= message.ttl;");
        return res.build();
    }
}

From source file:org.apache.storm.daemon.supervisor.AdvancedFSOps.java

protected AdvancedFSOps(Map<String, Object> conf) {
    _symlinksDisabled = (boolean) conf.getOrDefault(Config.DISABLE_SYMLINKS, false);
}

From source file:com.netflix.spinnaker.clouddriver.kubernetes.v2.op.handler.KubernetesStatefulSetHandler.java

@Override
public void addRelationships(Map<KubernetesKind, List<KubernetesManifest>> allResources,
        Map<KubernetesManifest, List<KubernetesManifest>> relationshipMap) {
    BiFunction<String, String, String> manifestName = (namespace, name) -> namespace + ":" + name;

    Map<String, KubernetesManifest> services = allResources.getOrDefault(SERVICE, new ArrayList<>()).stream()
            .collect(Collectors.toMap((m) -> manifestName.apply(m.getNamespace(), m.getName()), (m) -> m));

    for (KubernetesManifest manifest : allResources.getOrDefault(STATEFUL_SET, new ArrayList<>())) {
        String serviceName = KubernetesStatefulSetHandler.serviceName(manifest);
        if (StringUtils.isEmpty(serviceName)) {
            continue;
        }/*w  w w  .j av a2s  . co  m*/

        String key = manifestName.apply(manifest.getNamespace(), serviceName);

        if (!services.containsKey(key)) {
            continue;
        }

        KubernetesManifest service = services.get(key);
        relationshipMap.put(manifest, Collections.singletonList(service));
    }
}

From source file:com.robertsmieja.test.utils.junit.GenericObjectFactory.java

protected Object getValueFromMapOrDefaultMap(Class<?> fieldClass, Map<Class<?>, Object> valueMap) {
    Class<?> nonPrimitiveClass = convertPrimitiveToWrapperOrReturn(fieldClass);
    Map<Class<?>, Object> defaultValueMap = getCorrectDefaultValueMapFromClassMap(valueMap);
    return valueMap.getOrDefault(nonPrimitiveClass, defaultValueMap.get(nonPrimitiveClass));
}

From source file:org.apache.metron.enrichment.adapters.geo.GeoLiteDatabase.java

public synchronized void updateIfNecessary(Map<String, Object> globalConfig) {
    // Reload database if necessary (file changes on HDFS)
    LOG.trace("[Metron] Determining if GeoIpDatabase update required");
    String hdfsFile = GEO_HDFS_FILE_DEFAULT;
    if (globalConfig != null) {
        hdfsFile = (String) globalConfig.getOrDefault(GEO_HDFS_FILE, GEO_HDFS_FILE_DEFAULT);
    }//ww  w.  j a v a  2  s . c  o  m

    // Always update if we don't have a DatabaseReader
    if (reader == null || !hdfsLoc.equals(hdfsFile)) {
        // Update
        hdfsLoc = hdfsFile;
        update(hdfsFile);
    } else {
        LOG.trace("[Metron] Update to GeoIpDatabase unnecessary");
    }
}

From source file:org.matsim.contrib.drt.optimizer.rebalancing.mincostflow.MinCostFlowRebalancingStrategy.java

private List<Relocation> calculateMinCostRelocations(double time,
        Map<String, List<Vehicle>> rebalancableVehiclesPerZone,
        Map<String, List<Vehicle>> soonIdleVehiclesPerZone) {
    List<Pair<String, Integer>> supply = new ArrayList<>();
    List<Pair<String, Integer>> demand = new ArrayList<>();

    for (String z : zonalSystem.getZones().keySet()) {
        int rebalancable = rebalancableVehiclesPerZone.getOrDefault(z, Collections.emptyList()).size();
        int soonIdle = soonIdleVehiclesPerZone.getOrDefault(z, Collections.emptyList()).size();
        int target = rebalancingTargetCalculator.estimate(z, time);

        int delta = Math.min(rebalancable + soonIdle - target, rebalancable);
        if (delta < 0) {
            demand.add(Pair.of(z, -delta));
        } else if (delta > 0) {
            supply.add(Pair.of(z, delta));
        }/*from www  . j  a v a2  s.  co m*/
    }

    return minCostRelocationCalculator.calcRelocations(supply, demand, rebalancableVehiclesPerZone);
}

From source file:io.stallion.users.OAuthEndpoints.java

@GET
@Path("/auth")
@Produces("text/html")
@MinRole(Role.CONTACT)//from   w  w  w .  ja v a  2s  . c o m
public Object authScreen(@QueryParam("client_id") String clientFullId,
        @QueryParam("scopes") String scopesString) {
    String[] scopes = StringUtils.split(scopesString, ",");
    String description = "";
    Map<String, String> descriptionMap = Settings.instance().getoAuth().getScopeDescriptions();
    for (int x = 0; x < scopes.length; x++) {
        String scope = scopes[x];
        String s = or(descriptionMap.getOrDefault(scope, scope), scope);
        if (scopes.length == 1) {
            description = s;
        } else if (scopes.length == 2) {
            if (x == 0) {
                description += s;
            } else {
                description += " and " + s;
            }
        } else if (x + 1 == scopes.length) {
            description += " and " + s;
        } else {
            description += "," + s;
        }
    }
    Map<String, Object> ctx = map(val("clientId", clientFullId));
    ctx.put("client", OAuthClientController.instance().clientForFullId(clientFullId));
    ctx.put("scopesDescription", description);
    ctx.put("scopes", set(scopes));
    String html = TemplateRenderer.instance().renderTemplate("stallion:public/oauth.jinja");
    return html;
}

From source file:controllers.config.Config.java

/**
 * Overlays the host configuration.//from   www . j  ava  2  s. c  om
 *
 * @param hostname the hostname
 * @return a host configuration yaml response
 */
public F.Promise<Result> host(final String hostname) {
    LOGGER.info(String.format("Request for host; host=%s", hostname));
    return _configClient.getHostData(hostname).map(hostOutput -> {
        // Find the host
        final Host host = Host.getByName(hostname);
        if (host == null) {
            return ok(YAML_MAPPER.writeValueAsString(hostOutput));
        }
        final String rawHostclass = hostOutput.getHostclass();
        hostOutput.setHostclass(rawHostclass + "::" + host.getHostclass().getName());
        final Map<String, Object> params = hostOutput.getParams();
        final List<HostRedirect> lockMappings = Lists.newArrayList();
        if (params.containsKey("hosts_redirect")) {
            @SuppressWarnings("unchecked")
            final List<Map<String, Object>> hostsRedirect = (List<Map<String, Object>>) params
                    .get("hosts_redirect");
            for (final Map<String, Object> map : hostsRedirect) {
                final HostRedirect redirect = new HostRedirect((String) map.get("src_host"),
                        Optional.ofNullable((Integer) map.getOrDefault("src_port", null)),
                        (String) map.get("dst_host"),
                        Optional.ofNullable((Integer) map.getOrDefault("dst_port", null)));
                lockMappings.add(redirect);
            }
        }
        params.put("hosts_redirect", lockMappings);

        final List<Configuration> configList = Configuration.root().getConfigList("package.lock.replacements");

        for (final Configuration configuration : configList) {
            final Map<String, Object> map = configuration.asMap();
            final HostRedirect redirect = new HostRedirect((String) map.get("src_host"),
                    Optional.ofNullable((Integer) map.getOrDefault("src_port", null)),
                    (String) map.get("dst_host"),
                    Optional.ofNullable((Integer) map.getOrDefault("dst_port", null)));

            if (lockMappings.stream().filter((k) -> redirect._sourceHost.equals(k._sourceHost)
                    && redirect._sourcePort.equals(k._sourcePort)).count() == 0) {
                lockMappings.add(redirect);
            }
        }

        return ok(YAML_MAPPER.writeValueAsString(hostOutput));
    });
}

From source file:org.ow2.proactive.addons.ldap_query.LDAPClient.java

public LDAPClient(Map<String, Serializable> actualTaskVariables, Map<String, Serializable> credentials) {
    ImmutableList<String> taskVariablesList = ImmutableList.of(ARG_URL, ARG_DN_BASE, ARG_USERNAME, ARG_PASSWORD,
            ARG_SEARCH_BASE, ARG_SEARCH_FILTER, ARG_SELECTED_ATTRIBUTES);

    for (String variableName : taskVariablesList) {
        Serializable value = credentials.getOrDefault(variableName, actualTaskVariables.get(variableName));
        allLDAPClientParameters.put(variableName,
                (String) Optional.ofNullable(value).orElseThrow(() -> new IllegalArgumentException(
                        "The missed argument for LDAPClient, variable name: " + variableName)));
    }/*from  w w  w .  j av a2s. c  om*/
}

From source file:ddf.catalog.resource.download.DownloadInfo.java

private void parse(Map<String, String> downloadStatus) {
    notNull(downloadStatus, "Download status map cannot be null");

    downloadId = downloadStatus.get(DownloadStatus.DOWNLOAD_ID_KEY);
    fileName = downloadStatus.get(DownloadStatus.FILE_NAME_KEY);
    status = downloadStatus.get(DownloadStatus.STATUS_KEY);

    try {/*from w w  w  .  j a v a  2s  .  com*/
        bytesDownloaded = Long.parseLong(downloadStatus.getOrDefault(DownloadStatus.BYTES_DOWNLOADED_KEY, "0"));
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException("Bytes downloaded must be a number");
    }

    percentDownloaded = downloadStatus.getOrDefault(DownloadStatus.PERCENT_KEY, "0");

    if (downloadStatus.containsKey(DownloadStatus.USER_KEY)) {
        users.add(downloadStatus.get(DownloadStatus.USER_KEY));
    }

    notBlank(this.downloadId, "Download ID cannot be null");
    notBlank(this.fileName, "File name cannot be null");
    notBlank(this.status, "Status cannot be null");
}