List of usage examples for java.util Map getOrDefault
default V getOrDefault(Object key, V defaultValue)
From source file:org.obiba.mica.core.notification.PublicationFlowMailNotification.java
protected void sendNotification(RevisionStatus status, Map<String, String> ctx, String subject, String template, List<SubjectAcl> acls) { List<SubjectAcl> allAcls = Lists.newArrayList( SubjectAcl.newBuilder(Roles.MICA_REVIEWER, SubjectAcl.Type.GROUP) .action(PermissionsUtils.getReviewerActions()).build(), SubjectAcl.newBuilder(Roles.MICA_EDITOR, SubjectAcl.Type.GROUP) .action(PermissionsUtils.getEditorActions()).build()); allAcls.addAll(acls);/*from w ww. j a v a 2 s .c o m*/ Map<RevisionStatus, String> requiredActions = new HashMap<RevisionStatus, String>() { { put(RevisionStatus.DRAFT, "EDIT"); put(RevisionStatus.UNDER_REVIEW, "PUBLISH"); put(RevisionStatus.DELETED, "DELETE"); } }; Map<SubjectAcl.Type, List<String>> recipients = allAcls.stream() .filter(a -> a.getActions().contains(requiredActions.get(status))) .map(a -> Pair.create(a.getPrincipal(), a.getType())) .collect(groupingBy(Pair::getSecond, mapping(Pair::getFirst, toList()))); if (recipients.isEmpty()) return; mailService.sendEmailToGroupsAndUsers(subject, template, ctx, recipients.getOrDefault(SubjectAcl.Type.GROUP, Lists.newArrayList()), recipients.getOrDefault(SubjectAcl.Type.USER, Lists.newArrayList())); }
From source file:com.mweagle.tereus.commands.CreateCommand.java
@edu.umd.cs.findbugs.annotations.SuppressFBWarnings({ "DM_EXIT", "OBL_UNSATISFIED_OBLIGATION" }) @SuppressWarnings("unchecked") @Override/*from www.j a v a 2 s . c o m*/ public void run() { int exitCode = 0; try { final String argumentJSON = (null != this.jsonParamAndTagsPath) ? new String(Files.readAllBytes(Paths.get(this.jsonParamAndTagsPath)), Charsets.UTF_8) : null; Map<String, Object> jsonJavaRootObject = (null != argumentJSON) ? new Gson().fromJson(argumentJSON, Map.class) : Collections.emptyMap(); Map<String, Object> parameters = (Map<String, Object>) jsonJavaRootObject .getOrDefault(CONSTANTS.ARGUMENT_JSON_KEYNAMES.PARAMETERS, new HashMap<>()); final String jsonS3BucketName = ((String) parameters .getOrDefault(CONSTANTS.PARAMETER_NAMES.S3_BUCKET_NAME, "")).trim(); final String cliS3BucketName = (null == this.s3BucketName) ? "" : this.s3BucketName.trim(); if (!jsonS3BucketName.isEmpty() && !cliS3BucketName.isEmpty()) { final String msg = String.format("S3 bucketname defined in both %s and via command line argument", this.jsonParamAndTagsPath); throw new IllegalArgumentException(msg); } else if (!cliS3BucketName.isEmpty()) { parameters.put(CONSTANTS.PARAMETER_NAMES.S3_BUCKET_NAME, cliS3BucketName); } Map<String, Object> tags = (Map<String, Object>) jsonJavaRootObject .getOrDefault(CONSTANTS.ARGUMENT_JSON_KEYNAMES.TAGS, Collections.emptyMap()); TereusInput tereusInput = new TereusInput(this.stackTemplatePath, this.region, parameters, tags, this.dryRun); Optional<OutputStream> osSink = Optional.empty(); try { if (null != this.outputFilePath) { final Path outputPath = Paths.get(this.outputFilePath); osSink = Optional.of(new FileOutputStream(outputPath.toFile())); } this.create(tereusInput, osSink); } catch (Exception ex) { LogManager.getLogger().error(ex.getCause()); exitCode = 2; } finally { if (osSink.isPresent()) { try { osSink.get().close(); } catch (Exception e) { // NOP } } } } catch (Exception ex) { LogManager.getLogger().error(ex); Help.help(this.helpOption.commandMetadata); exitCode = 1; } System.exit(exitCode); }
From source file:edu.usc.irds.sparkler.solr.schema.FieldMapper.java
/** * Creates a field name mapper by reading config from the argument conf stream * @param jConfStream JSON config stream * @throws IOException/* w ww . jav a 2 s. c o m*/ * @throws ParseException when the config is invalid */ public FieldMapper(InputStream jConfStream) throws IOException, ParseException { try (InputStreamReader reader = new InputStreamReader(jConfStream)) { Yaml yaml = new Yaml(); Map jConf = (Map) yaml.load(reader); //Map jConf = (JSONObject) new JSONParser().parse(reader); if (jConf.containsKey(KEY_OVERRIDES)) { ((Map) jConf.get(KEY_OVERRIDES)).forEach((k, v) -> overrides.put(k.toString(), v.toString())); } if (jConf.containsKey(KEY_MULTI_VAL_SUFFIX)) { this.multiValSuffix = jConf.getOrDefault(KEY_MULTI_VAL_SUFFIX, DEFAULT_MULTI_VAL_SUFFIX).toString(); } if (jConf.containsKey(KEY_TYPE_SUFFIX)) { ((Map) jConf.get(KEY_TYPE_SUFFIX)).forEach((k, v) -> { try { typeSuffix.put(Class.forName(k.toString()), v.toString()); } catch (ClassNotFoundException e) { throw new RuntimeException("Class " + k.toString() + " is invalid or unknown"); } }); } } }
From source file:ddf.catalog.metacard.validation.MetacardValidityMarkerPlugin.java
private <T> List<T> validateList(List<T> requestItems, Function<T, Metacard> itemToMetacard) { Map<String, Integer> counter = new HashMap<>(); List<T> validated = requestItems.stream().map(item -> validate(item, itemToMetacard, counter)) .filter(didNotFailEnforcedValidator).collect(Collectors.toList()); INGEST_LOGGER.info("Validation results: {} had warnings and {} had errors.", counter.getOrDefault(Validation.VALIDATION_WARNINGS, 0), counter.getOrDefault(Validation.VALIDATION_ERRORS, 0)); return validated; }
From source file:org.jboss.as.test.integration.management.extension.customcontext.testbase.CustomManagementContextTestBase.java
private void test(final ManagementClient managementClient) throws IOException { //if (true) return; final String urlBase = "http://" + managementClient.getMgmtAddress() + ":9990/"; final String remapUrl = urlBase + "remap/foo"; final String badRemapUrl = urlBase + "remap/bad"; final String staticUrl = urlBase + "static/hello.txt"; final String staticUrlDirectory = urlBase + "static/"; final String badStaticUrl = urlBase + "static/bad.txt"; // Sanity check try (CloseableHttpClient client = HttpClients.createDefault()) { HttpResponse resp = client.execute(new HttpGet(remapUrl)); assertEquals(404, resp.getStatusLine().getStatusCode()); resp = client.execute(new HttpGet(staticUrl)); assertEquals(404, resp.getStatusLine().getStatusCode()); }/* ww w.ja va2 s . c o m*/ // Add extension and subsystem executeOp(Util.createAddOperation(getExtensionAddress()), managementClient); executeOp(Util.createAddOperation(getSubsystemAddress()), managementClient); // Unauthenticated check try (CloseableHttpClient client = HttpClients.createDefault()) { HttpResponse resp = client.execute(new HttpGet(remapUrl)); assertEquals(401, resp.getStatusLine().getStatusCode()); resp = client.execute(new HttpGet(staticUrl)); assertEquals(200, resp.getStatusLine().getStatusCode()); } try (CloseableHttpClient client = createAuthenticatingClient(managementClient)) { // Authenticated check HttpResponse resp = client.execute(new HttpGet(remapUrl)); assertEquals(200, resp.getStatusLine().getStatusCode()); ModelNode respNode = ModelNode.fromJSONString(EntityUtils.toString(resp.getEntity())); assertEquals(respNode.toString(), CustomContextExtension.EXTENSION_NAME, respNode.get("module").asString()); assertTrue(respNode.toString(), respNode.hasDefined("subsystem")); assertTrue(respNode.toString(), respNode.get("subsystem").has(CustomContextExtension.SUBSYSTEM_NAME)); resp = client.execute(new HttpGet(staticUrl)); assertEquals(200, resp.getStatusLine().getStatusCode()); String text = EntityUtils.toString(resp.getEntity()); assertTrue(text, text.startsWith("Hello")); // the response should contain headers: // X-Frame-Options: SAMEORIGIN // Cache-Control: public, max-age=2678400 final Map<String, String> headersMap = Arrays.stream(resp.getAllHeaders()) .collect(Collectors.toMap(Header::getName, Header::getValue)); Assert.assertTrue("'X-Frame-Options: SAMEORIGIN' header is expected", headersMap.getOrDefault("X-Frame-Options", "").contains("SAMEORIGIN")); Assert.assertTrue("Cache-Control header with max-age=2678400 is expected,", headersMap.getOrDefault("Cache-Control", "").contains("max-age=2678400")); // directory listing is not allowed resp = client.execute(new HttpGet(staticUrlDirectory)); assertEquals(404, resp.getStatusLine().getStatusCode()); // POST check resp = client.execute(new HttpPost(remapUrl)); assertEquals(405, resp.getStatusLine().getStatusCode()); resp = client.execute(new HttpPost(staticUrl)); assertEquals(200, resp.getStatusLine().getStatusCode()); // Bad URL check resp = client.execute(new HttpGet(badRemapUrl)); assertEquals(404, resp.getStatusLine().getStatusCode()); resp = client.execute(new HttpGet(badStaticUrl)); assertEquals(404, resp.getStatusLine().getStatusCode()); // Remove subsystem executeOp(Util.createRemoveOperation(getSubsystemAddress()), managementClient); // Requests fail resp = client.execute(new HttpGet(remapUrl)); assertEquals(404, resp.getStatusLine().getStatusCode()); resp = client.execute(new HttpGet(staticUrl)); assertEquals(404, resp.getStatusLine().getStatusCode()); } }
From source file:org.apache.bookkeeper.mledger.offload.jcloud.impl.BlobStoreManagedLedgerOffloader.java
String getReadRegion(Map<String, String> offloadDriverMetadata) { return offloadDriverMetadata.getOrDefault(METADATA_FIELD_REGION, writeRegion); }
From source file:org.apache.bookkeeper.mledger.offload.jcloud.impl.BlobStoreManagedLedgerOffloader.java
String getReadBucket(Map<String, String> offloadDriverMetadata) { return offloadDriverMetadata.getOrDefault(METADATA_FIELD_BUCKET, writeBucket); }
From source file:org.apache.bookkeeper.mledger.offload.jcloud.impl.BlobStoreManagedLedgerOffloader.java
String getReadEndpoint(Map<String, String> offloadDriverMetadata) { return offloadDriverMetadata.getOrDefault(METADATA_FIELD_ENDPOINT, writeEndpoint); }
From source file:com.srotya.sidewinder.cluster.storage.ClusteredMemStorageEngine.java
@Override public void configure(Map<String, String> conf) throws IOException { this.local = new MemStorageEngine(); this.local.configure(conf); this.clusterSize = Integer.parseInt(conf.getOrDefault("cluster.size", "1")); conf.put(Topology.WORKER_DATA_PORT, "9927"); conf.put("linea.zk.root", "/sidewinder"); this.columbus = new Columbus(conf); }
From source file:org.apache.solr.security.GenericHadoopAuthPlugin.java
@SuppressWarnings("unchecked") protected FilterConfig getInitFilterConfig(Map<String, Object> pluginConfig) { Map<String, String> params = new HashMap<>(); String type = (String) Objects.requireNonNull(pluginConfig.get(HADOOP_AUTH_TYPE)); params.put(HADOOP_AUTH_TYPE, type);//from ww w. ja va2s .c om String sysPropPrefix = (String) pluginConfig.getOrDefault(SYSPROP_PREFIX_PROPERTY, "solr."); Collection<String> authConfigNames = (Collection<String>) pluginConfig .getOrDefault(AUTH_CONFIG_NAMES_PROPERTY, Collections.emptyList()); Map<String, String> authConfigDefaults = (Map<String, String>) pluginConfig .getOrDefault(DEFAULT_AUTH_CONFIGS_PROPERTY, Collections.emptyMap()); Map<String, String> proxyUserConfigs = (Map<String, String>) pluginConfig.getOrDefault(PROXY_USER_CONFIGS, Collections.emptyMap()); for (String configName : authConfigNames) { String systemProperty = sysPropPrefix + configName; String defaultConfigVal = authConfigDefaults.get(configName); String configVal = System.getProperty(systemProperty, defaultConfigVal); if (configVal != null) { params.put(configName, configVal); } } // Configure proxy user settings. params.putAll(proxyUserConfigs); final ServletContext servletContext = new AttributeOnlyServletContext(); log.info("Params: " + params); ZkController controller = coreContainer.getZkController(); if (controller != null) { servletContext.setAttribute(DELEGATION_TOKEN_ZK_CLIENT, controller.getZkClient()); } FilterConfig conf = new FilterConfig() { @Override public ServletContext getServletContext() { return servletContext; } @Override public Enumeration<String> getInitParameterNames() { return new IteratorEnumeration(params.keySet().iterator()); } @Override public String getInitParameter(String param) { return params.get(param); } @Override public String getFilterName() { return "HadoopAuthFilter"; } }; return conf; }