List of usage examples for java.util Collections EMPTY_MAP
Map EMPTY_MAP
To view the source code for java.util Collections EMPTY_MAP.
Click Source Link
From source file:io.jenkins.blueocean.service.embedded.rest.UserImplPermissionTest.java
@Before public void setup() throws IOException { testOrganization = new TestOrganization("org", "orgDisplayName"); user = mock(User.class); when(user.getId()).thenReturn("some_user"); authentication = new Authentication() { public String getName() { return "some_user"; }// w ww .ja v a 2 s.c o m public GrantedAuthority[] getAuthorities() { return null; } public Object getCredentials() { return null; } public Object getDetails() { return null; } public Object getPrincipal() { return null; } public boolean isAuthenticated() { return false; } public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException { } }; jenkins = mock(Jenkins.class); when(jenkins.getACL()).thenReturn(new ACL() { public boolean hasPermission(Authentication a, Permission permission) { return false; } }); mockStatic(Jenkins.class); when(Jenkins.getAuthentication()).thenReturn(authentication); when(Jenkins.getInstance()).thenReturn(jenkins); try { // After Jenkins 2.77 hasPermission is no longer in Node.class and is not final so we need to mock it // prior to it is called as being final and mocking it will fail for the same reason. // TODO remove after core base line is >= 2.77 Node.class.getDeclaredMethod("hasPermission", Permission.class); } catch (NoSuchMethodException e) { when(jenkins.hasPermission(Mockito.any())).thenAnswer(new Answer<Boolean>() { public Boolean answer(InvocationOnMock invocation) { Permission permission = invocation.getArgumentAt(0, Permission.class); Jenkins j = (Jenkins) invocation.getMock(); return j.getACL().hasPermission(permission); } }); } mockStatic(User.class); when(User.get("some_user", false, Collections.EMPTY_MAP)).thenReturn(user); }
From source file:org.eclipse.smarthome.model.core.internal.ModelRepositoryImpl.java
@Override public boolean addOrRefreshModel(String name, final InputStream originalInputStream) { Resource resource = null;//from w w w . ja va2 s .c om try { InputStream inputStream = null; if (originalInputStream != null) { byte[] bytes = IOUtils.toByteArray(originalInputStream); String validationResult = validateModel(name, new ByteArrayInputStream(bytes)); if (validationResult != null) { logger.warn("Configuration model '{}' has errors, therefore ignoring it: {}", name, validationResult); removeModel(name); return false; } inputStream = new ByteArrayInputStream(bytes); } resource = getResource(name); if (resource == null) { synchronized (resourceSet) { // try again to retrieve the resource as it might have been created by now resource = getResource(name); if (resource == null) { // seems to be a new file // don't use XMI as a default Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().remove("*"); resource = resourceSet.createResource(URI.createURI(name)); if (resource != null) { logger.info("Loading model '{}'", name); Map<String, String> options = new HashMap<String, String>(); options.put(XtextResource.OPTION_ENCODING, "UTF-8"); if (inputStream == null) { logger.warn( "Resource '{}' not found. You have to pass an inputStream to create the resource.", name); return false; } resource.load(inputStream, options); notifyListeners(name, EventType.ADDED); return true; } else { logger.warn("Ignoring file '{}' as we do not have a parser for it.", name); } } } } else { synchronized (resourceSet) { resource.unload(); logger.info("Refreshing model '{}'", name); if (inputStream != null) { resource.load(inputStream, Collections.EMPTY_MAP); } else { resource.load(Collections.EMPTY_MAP); } notifyListeners(name, EventType.MODIFIED); return true; } } } catch (IOException e) { logger.warn("Configuration model '{}' cannot be parsed correctly!", name, e); if (resource != null) { resourceSet.getResources().remove(resource); } } return false; }
From source file:com.adobe.ags.curly.test.ErrorBehaviorTest.java
@Test public void testActionRequireFailure2() throws IOException, ParseException { ApplicationState.getInstance().errorBehaviorProperty().set(ErrorBehavior.HALT); Action fail1 = successAction(); Action fail2 = failureAction(); fail1.setErrorBehavior(ErrorBehavior.SKIP_IF_SUCCESSFUL); fail2.setErrorBehavior(ErrorBehavior.SKIP_IF_SUCCESSFUL); List<Action> actions = Arrays.asList(fail1, fail2); ActionGroupRunner runner = new ActionGroupRunner("Action Require Failure Test", ignore -> client, actions, Collections.EMPTY_MAP, Collections.EMPTY_SET); runner.run();/*from ww w . j a v a2 s. c o m*/ assertResults(runner.getResult(), false, false); }
From source file:com.creactiviti.piper.core.Coordinator.java
private void validate(MapObject aCreateJobParams, Pipeline aPipeline) { // validate inputs Map<String, Object> inputs = aCreateJobParams.getMap(DSL.INPUTS, Collections.EMPTY_MAP); List<Accessor> input = aPipeline.getInputs(); for (Accessor in : input) { if (in.getBoolean(DSL.REQUIRED, false)) { Assert.isTrue(inputs.containsKey(in.get(DSL.NAME)), "Missing required param: " + in.get("name")); }//from w w w. j a v a 2s .c om } // validate webhooks List<Accessor> webhooks = aCreateJobParams.getList(WEBHOOKS, MapObject.class, Collections.EMPTY_LIST); for (Accessor webhook : webhooks) { Assert.notNull(webhook.getString(DSL.TYPE), "must define 'type' on webhook"); Assert.notNull(webhook.getString(DSL.URL), "must define 'url' on webhook"); } }
From source file:com.gemstone.gemfire.management.internal.cli.commands.ConfigCommandsDUnitTest.java
public void testDescribeConfig() throws ClassNotFoundException, IOException { createDefaultSetup(null);//from www . ja va 2 s.c om final String controllerName = "Member2"; /*** * Create properties for the controller VM */ final Properties localProps = new Properties(); localProps.setProperty(DistributionConfig.MCAST_PORT_NAME, "0"); localProps.setProperty(DistributionConfig.LOG_LEVEL_NAME, "info"); localProps.setProperty(DistributionConfig.STATISTIC_SAMPLING_ENABLED_NAME, "true"); localProps.setProperty(DistributionConfig.ENABLE_TIME_STATISTICS_NAME, "true"); localProps.setProperty(DistributionConfig.NAME_NAME, controllerName); localProps.setProperty(DistributionConfig.GROUPS_NAME, "G1"); getSystem(localProps); Cache cache = getCache(); int ports[] = AvailablePortHelper.getRandomAvailableTCPPorts(1); CacheServer cs = getCache().addCacheServer(); cs.setPort(ports[0]); cs.setMaxThreads(10); cs.setMaxConnections(9); cs.start(); RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); List<String> jvmArgs = runtimeBean.getInputArguments(); getLogWriter().info("#SB Actual JVM Args : "); for (String jvmArg : jvmArgs) { getLogWriter().info("#SB JVM " + jvmArg); } InternalDistributedSystem system = (InternalDistributedSystem) cache.getDistributedSystem(); DistributionConfig config = system.getConfig(); config.setArchiveFileSizeLimit(1000); String command = CliStrings.DESCRIBE_CONFIG + " --member=" + controllerName; CommandProcessor cmdProcessor = new CommandProcessor(); cmdProcessor.createCommandStatement(command, Collections.EMPTY_MAP).process(); CommandResult cmdResult = executeCommand(command); String resultStr = commandResultToString(cmdResult); getLogWriter().info("#SB Hiding the defaults\n" + resultStr); assertEquals(true, cmdResult.getStatus().equals(Status.OK)); assertEquals(true, resultStr.contains("G1")); assertEquals(true, resultStr.contains(controllerName)); assertEquals(true, resultStr.contains("archive-file-size-limit")); assertEquals(true, !resultStr.contains("copy-on-read")); cmdResult = executeCommand(command + " --" + CliStrings.DESCRIBE_CONFIG__HIDE__DEFAULTS + "=false"); resultStr = commandResultToString(cmdResult); getLogWriter().info("#SB No hiding of defaults\n" + resultStr); assertEquals(true, cmdResult.getStatus().equals(Status.OK)); assertEquals(true, resultStr.contains("is-server")); assertEquals(true, resultStr.contains(controllerName)); assertEquals(true, resultStr.contains("copy-on-read")); cs.stop(); }
From source file:org.eurekastreams.server.action.execution.notification.notifier.EmailNotifier.java
/** * {@inheritDoc}// w ww .j a v a 2 s.c o m */ @Override public Collection<UserActionRequest> notify(final NotificationType inType, final Collection<Long> inRecipients, final Map<String, Object> inProperties, final Map<Long, PersonModelView> inRecipientIndex) throws Exception { EmailNotificationTemplate template = templates.get(inType); if (template == null) { // Not an error - this is an easy way to disable a given notification. return null; } // prepare recipient lists // determine which recipients get individual emails with reply tokens and which get a mass general email List<String> addresses = new ArrayList<String>(inRecipients.size()); Map<String, String> addressesWithTokens = Collections.EMPTY_MAP; if (template.getReplyAddressType() == ReplyAction.COMMENT) { Object obj = inProperties.get("activity"); if (obj == null || !(obj instanceof ActivityDTO)) { throw new ExecutionException("Notification requires activity property for building token."); } ActivityDTO activity = (ActivityDTO) obj; addressesWithTokens = new HashMap<String, String>(inRecipients.size()); String tokenData = tokenContentFormatter.buildForActivity(activity.getId()); // ok to use relaxed mode here: the translators wouldn't include recipients who do not have access to the // activity boolean generallyAllowed = activityAuthorizer.authorize(activity, ActivityInteractionType.COMMENT, false); for (long recipientId : inRecipients) { String address = inRecipientIndex.get(recipientId).getEmail(); if (StringUtils.isNotBlank(address)) { // Note: checking on a per-user basis is very inefficient. That's why the generallyAllowed // optimization was put in to omit the per-user check for streams that allow commenting. Both the // generallyAllowed and the per-user call could be replaced with an authorizer that takes a list of // users to check and returns a list of only those which are allowed (i.e. an authorization filter). // If the scenario arises where there are streams which do not allow commenting with many email // subscribers, then a bulk authorizer could be used to significantly improve performance. if (generallyAllowed || activityAuthorizer.authorize(recipientId, activity, ActivityInteractionType.COMMENT)) { String replyAddress = tokenAddressBuilder.build(tokenData, recipientId); addressesWithTokens.put(address, replyAddress); } else { addresses.add(address); } } } } else { for (long recipientId : inRecipients) { String address = inRecipientIndex.get(recipientId).getEmail(); if (StringUtils.isNotBlank(address)) { addresses.add(address); } } } int emailCount = addressesWithTokens.size() + (addresses.isEmpty() ? 0 : 1); if (emailCount == 0) { return null; } List<UserActionRequest> requests = new ArrayList<UserActionRequest>(emailCount); // -- prepare the email -- NotificationEmailDTO email = new NotificationEmailDTO(); // Note: The doubly-nested context is to prevent the code here and Velocity templates from updating // inProperties. The inner context uses inProperties as its backing store, so anything added to the context -- // such as the values added here and any SET calls in templates -- would be added to inProperties, which we // don't want. Context velocityContext = new VelocityContext(new VelocityContext(inProperties, velocityGlobalContext)); velocityContext.put("context", velocityContext); velocityContext.put("type", inType); if (addressesWithTokens.size() + addresses.size() == 1) { velocityContext.put("recipient", inRecipientIndex.get(inRecipients.iterator().next())); } // build the subject StringWriter writer = new StringWriter(); velocityEngine.evaluate(velocityContext, writer, "EmailSubject-" + inType, template.getSubjectTemplate()); email.setSubject(subjectPrefix + writer.toString()); // set the priority email.setHighPriority(Boolean.TRUE.equals(inProperties.get(NotificationPropertyKeys.HIGH_PRIORITY))); // render the body String noReplyTextBody = null; String replyTextBody = null; String noReplyHtmlBody = null; String replyHtmlBody = null; // build the text body Template vt = velocityEngine.getTemplate(template.getTextBodyTemplateResourcePath()); if (!addresses.isEmpty()) { velocityContext.put("hasReplyAddress", false); writer.getBuffer().setLength(0); vt.merge(velocityContext, writer); noReplyTextBody = writer.toString(); } if (!addressesWithTokens.isEmpty()) { velocityContext.put("hasReplyAddress", true); writer.getBuffer().setLength(0); vt.merge(velocityContext, writer); replyTextBody = writer.toString(); } // build the HTML body if (sendHtml) { final String htmlBodyTemplateResourcePath = template.getHtmlBodyTemplateResourcePath(); if (htmlBodyTemplateResourcePath != null) { vt = velocityEngine.getTemplate(htmlBodyTemplateResourcePath); // HTML-escape all content inserted EventCartridge ec = new EventCartridge(); ec.addEventHandler(new EscapeHtmlReference()); ec.attachToContext(velocityContext); if (!addresses.isEmpty()) { velocityContext.put("hasReplyAddress", false); writer.getBuffer().setLength(0); vt.merge(velocityContext, writer); noReplyHtmlBody = writer.toString(); } if (!addressesWithTokens.isEmpty()) { velocityContext.put("hasReplyAddress", true); writer.getBuffer().setLength(0); vt.merge(velocityContext, writer); replyHtmlBody = writer.toString(); } } } // -- create requests to send emails -- if (!addressesWithTokens.isEmpty()) { email.setTextBody(replyTextBody); if (replyHtmlBody != null) { email.setHtmlBody(replyHtmlBody); } for (Entry<String, String> entry : addressesWithTokens.entrySet()) { NotificationEmailDTO userEmail = email.clone(); userEmail.setReplyTo(entry.getValue()); String address = entry.getKey(); userEmail.setToRecipient(address); // set the description (for logging / debugging) userEmail.setDescription(inType + " with token to " + address); requests.add(new UserActionRequest("sendEmailNotificationAction", null, userEmail)); } } if (!addresses.isEmpty()) { email.setTextBody(noReplyTextBody); if (noReplyHtmlBody != null) { email.setHtmlBody(noReplyHtmlBody); } if (addresses.size() == 1) { final String address = addresses.get(0); email.setToRecipient(address); // set the description (for logging / debugging) email.setDescription(inType + " to " + address); } else { email.setBccRecipients(StringUtils.join(addresses, ',')); // set the description (for logging / debugging) email.setDescription(inType + " to " + inRecipients.size() + " recipients"); } // set the reply-to to the actor (so replies to emails go to the actor, not the system) if (template.getReplyAddressType() == ReplyAction.ACTOR) { Object obj = inProperties.get(NotificationPropertyKeys.ACTOR); if (obj instanceof HasEmail) { HasEmail actor = (HasEmail) obj; String actorEmail = actor.getEmail(); if (StringUtils.isNotBlank(actorEmail)) { email.setReplyTo(actorEmail); } } } requests.add(new UserActionRequest("sendEmailNotificationAction", null, email)); } return requests; }
From source file:org.apache.openjpa.persistence.EntityManagerFactoryImpl.java
/** * Creates and configures a entity manager with the given properties. * //from ww w . j a v a 2 s.c om * The property keys in the given map can be either qualified or not. * * @return list of exceptions raised or empty list. */ public OpenJPAEntityManagerSPI createEntityManager(Map props) { if (props == null) props = Collections.EMPTY_MAP; else if (!props.isEmpty()) props = new HashMap(props); OpenJPAConfiguration conf = getConfiguration(); Log log = conf.getLog(OpenJPAConfiguration.LOG_RUNTIME); String user = (String) Configurations.removeProperty("ConnectionUserName", props); if (user == null) user = conf.getConnectionUserName(); String pass = (String) Configurations.removeProperty("ConnectionPassword", props); if (pass == null) pass = conf.getConnectionPassword(); String str = (String) Configurations.removeProperty("TransactionMode", props); boolean managed; if (str == null) managed = conf.isTransactionModeManaged(); else { Value val = conf.getValue("TransactionMode"); managed = Boolean.parseBoolean(val.unalias(str)); } Object obj = Configurations.removeProperty("ConnectionRetainMode", props); int retainMode; if (obj instanceof Number) { retainMode = ((Number) obj).intValue(); } else if (obj == null) { retainMode = conf.getConnectionRetainModeConstant(); } else { Value val = conf.getValue("ConnectionRetainMode"); try { retainMode = Integer.parseInt(val.unalias((String) obj)); } catch (Exception e) { throw new ArgumentException(_loc.get("bad-em-prop", "openjpa.ConnectionRetainMode", obj), new Throwable[] { e }, obj, true); } } // javax.persistence.jtaDataSource and openjpa.ConnectionFactory name are equivalent. // prefer javax.persistence for now. String cfName = (String) Configurations.removeProperty("jtaDataSource", props); if (cfName == null) { cfName = (String) Configurations.removeProperty("ConnectionFactoryName", props); } String cf2Name = (String) Configurations.removeProperty("nonJtaDataSource", props); if (cf2Name == null) { cf2Name = (String) Configurations.removeProperty("ConnectionFactory2Name", props); } if (log != null && log.isTraceEnabled()) { if (StringUtils.isNotEmpty(cfName)) { log.trace("Found ConnectionFactoryName from props: " + cfName); } if (StringUtils.isNotEmpty(cf2Name)) { log.trace("Found ConnectionFactory2Name from props: " + cf2Name); } } validateCfNameProps(conf, cfName, cf2Name); Broker broker = _factory.newBroker(user, pass, managed, retainMode, false, cfName, cf2Name); // add autodetach for close and rollback conditions to the configuration broker.setAutoDetach(AutoDetach.DETACH_CLOSE, true); broker.setAutoDetach(AutoDetach.DETACH_ROLLBACK, true); broker.setDetachedNew(false); OpenJPAEntityManagerSPI em = newEntityManagerImpl(broker); // allow setting of other bean properties of EM Set<Map.Entry> entrySet = props.entrySet(); for (Map.Entry entry : entrySet) { em.setProperty(entry.getKey().toString(), entry.getValue()); } if (log != null && log.isTraceEnabled()) { log.trace(this + " created EntityManager " + em + "."); } return em; }
From source file:marshalsec.Jackson.java
@Override @Args(minArgs = 0, args = {}, noTest = true) // random port only public Object makeUnicastRemoteObject(UtilFactory uf, String... args) throws Exception { return writeObject("java.rmi.server.UnicastRemoteObject", Collections.EMPTY_MAP); }
From source file:com.firstproj.testtwo.web.Test.java
public static void testFlickr() throws Exception { Flickr f = new Flickr("df1e5e194de94bb405b2ce898db83b90", "ed6088a596f20afd", new REST()); Auth auth = new Auth(); User user = new User(); user.setId("jwlee208"); auth.setUser(user);/*from w w w . j a v a 2 s.co m*/ f.setAuth(auth); GroupsInterface groups = f.getGroupsInterface(); // search group Collection<Group> searchedGroups = groups.search("jwlee208", 10, 10); if (!searchedGroups.isEmpty()) { System.out.println("SearchGroups > "); for (Group group : searchedGroups) { System.out.println(group.getName()); } } System.out.println(groups.search("[jQuery] window.onload ready()", 1, 1)); PhotosInterface photos = f.getPhotosInterface(); SearchParameters params = new SearchParameters(); params.setUserId("jwlee208"); params.setSafeSearch(Flickr.SAFETYLEVEL_SAFE); // params.setText("jquery"); PhotoList<Photo> photoList = photos.search(params, 100, 1); Collection<Photocount> photoCount = photos.getCounts(null, null); System.out.println(photoCount.size()); // photos.getContactsPhotos(10, true, true, true); if (!photoList.isEmpty()) { for (Photo photo : photoList) { System.out.println("photo.getTitle() : " + photo.getTitle() + "\nphoto.getLargeUrl() : " + photo.getLargeUrl() + "\nphoto.getLicense() : " + photo.getLicense() + "\nphoto.getUrls() : " + photo.getUrls() + "\nphoto.getTags() : " + photo.getTags() + "\n photo.getPhotoUrl() : " + photo.getPhotoUrl() + "\nphoto.getPermissions() : " + photo.getPermissions() + "\nphoto.getThumbnailUrl() : " + photo.getThumbnailUrl()); System.out.println("\n----------------------------------"); } } TestInterface testInterface = f.getTestInterface(); Collection results = testInterface.echo(Collections.EMPTY_MAP); System.out.println(results); List<Gallery> list = new ArrayList<Gallery>(); System.out.println(list.size()); if (list.size() > 0) { for (Gallery gallery : list) { System.out.println(gallery.getTitle()); } } }
From source file:org.archive.nutchwax.scoring.PageRankScoringFilter.java
/** * Utility function to read a list of page-rank records from a file * specified in the configuration./*from w w w .jav a2s . co m*/ */ public static Map<String, Integer> getPageRanks(Configuration conf) { String pageranksPath = conf.get("nutchwax.scoringfilter.pagerank.ranks"); if (pageranksPath == null || pageranksPath.trim().length() == 0) { LOG.warn("No pagerank file set for property: \"nutchwax.scoringfilter.pagerank.ranks\""); return Collections.EMPTY_MAP; } LOG.warn("Using pageranks: " + pageranksPath); Map<String, Integer> pageranks = new HashMap<String, Integer>(); BufferedReader reader = null; try { Path p = new Path(pageranksPath.trim()); FileSystem fs = FileSystem.get(conf); if (fs.exists(p)) { InputStream is = p.getFileSystem(conf).open(p); reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line; while ((line = reader.readLine()) != null) { String fields[] = line.split("\\s+"); if (fields.length < 2) { LOG.warn("Malformed pagerank, not enough fields (" + fields.length + "): " + line); continue; } try { int rank = Integer.parseInt(fields[0]); String url = fields[1]; if (rank < 0) { LOG.warn("Malformed pagerank, rank less than 0: " + line); } pageranks.put(url, rank); } catch (NumberFormatException nfe) { LOG.warn("Malformed pagerank, rank not an integer: " + line); continue; } } } else { LOG.warn("Pagerank file doesn't exist: " + pageranksPath); } } catch (IOException e) { // Umm, what to do? throw new RuntimeException(e); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { // Ignore it. } } return pageranks; }