Java Examples for org.apache.commons.collections.map.MultiValueMap
The following java examples will help you to understand the usage of org.apache.commons.collections.map.MultiValueMap. These source code samples are taken from different open source projects.
Example 1
| Project: Minecraft-ID-Resolver-master File: WindowMain.java View source code |
public void actionPerformed(ActionEvent e) {
btnBrowse.setEnabled(false);
btnSearch.setEnabled(false);
btnSearch.setText("Searching...please wait");
ConfigHelper.populateMaps(txtFieldPath.getText());
MultiValueMap blocks = ConfigHelper.getBlockIDs();
if (blocks.isEmpty() != true) {
for (Object key : blocks.keySet()) {
Integer ID = Integer.valueOf(key.toString());
if (ConflictHelper.isConflicting(ConfigHelper.getBlockIDs(), ID, "BLOCK") == true) {
listModelBlocks.addElement(getColoredString("Block ID: " + ID + " | " + ConflictHelper.getConflictString(ConfigHelper.getBlockIDs(), ID) + " " + ConflictHelper.getConfigConflictString(ConfigHelper.getBlockIDs(), ID)));
conflicts++;
} else {
listModelBlocks.addElement("Block ID: " + ID + " | " + "Block name: " + ConflictHelper.getName(ConfigHelper.getBlockIDs(), ID));
}
}
}
MultiValueMap items = ConfigHelper.getItemIDs();
if (items.isEmpty() != true) {
for (Object key : items.keySet()) {
Integer ID = Integer.valueOf(key.toString());
if (ConflictHelper.isConflicting(ConfigHelper.getItemIDs(), ID, "ITEM") == true) {
listModelItems.addElement(getColoredString("Item ID: " + ID + " | " + ConflictHelper.getConflictString(ConfigHelper.getItemIDs(), ID) + " " + ConflictHelper.getConfigConflictString(ConfigHelper.getItemIDs(), ID)));
conflicts++;
} else {
listModelItems.addElement("Item ID: " + ID + " | " + "Item name: " + ConflictHelper.getName(ConfigHelper.getItemIDs(), ID));
}
}
}
MultiValueMap unknown = ConfigHelper.getUnknownIDs();
if (unknown.isEmpty() != true) {
for (Object key : unknown.keySet()) {
Integer ID = Integer.valueOf(key.toString());
if (ConflictHelper.isConflicting(ConfigHelper.getUnknownIDs(), ID, "UNKNOWN") == true) {
listModelUnknown.addElement(getColoredString("ID: " + ID + " | " + ConflictHelper.getConflictString(ConfigHelper.getUnknownIDs(), ID) + " " + ConflictHelper.getConfigConflictString(ConfigHelper.getUnknownIDs(), ID)));
conflicts++;
} else {
listModelUnknown.addElement("ID: " + ID + " | " + "Name: " + ConflictHelper.getName(ConfigHelper.getUnknownIDs(), ID));
}
}
}
SortingHelper.sortListModel(listModelBlocks);
SortingHelper.sortListModel(listModelItems);
SortingHelper.sortListModel(listModelUnknown);
btnSearch.setText("Done!");
if (conflicts == 0) {
JOptionPane.showMessageDialog(null, "No conflicts were found! Hooray!", "Information", JOptionPane.INFORMATION_MESSAGE);
frmMain.dispose();
} else if (conflicts == 1) {
JOptionPane.showMessageDialog(null, conflicts.toString() + " conflict was found!", "Information", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, conflicts.toString() + " conflicts were found!", "Information", JOptionPane.INFORMATION_MESSAGE);
}
tabbedPaneIDs.setEnabled(true);
tabbedPaneIDs.requestFocus();
btnBrowse2.setEnabled(true);
}Example 2
| Project: ehour-master File: JoinTables.java View source code |
@SuppressWarnings("unchecked")
public List<String> getTarget(String joinTableName, String source) {
String joinTableNameLower = joinTableName.toLowerCase();
if (joinTables.containsKey(joinTableNameLower)) {
MultiValueMap multiValueMap = joinTables.get(joinTableNameLower);
return (List<String>) multiValueMap.get(source);
} else {
return Lists.newArrayList();
}
}Example 3
| Project: useful-java-links-master File: ApacheMultiValueMapTreeTest.java View source code |
// Task: parser string with text and show all indexes of all words
public static void main(String[] args) {
String INPUT_TEXT = "Hello World! Hello All! Hi World!";
// Parse text to words and index
List<String> words = Arrays.asList(INPUT_TEXT.split(" "));
// Create Multimap
MultiMap<String, Integer> multiMap = MultiValueMap.multiValueMap(new TreeMap<String, Set>(), TreeSet.class);
// Fill Multimap
int i = 0;
for (String word : words) {
multiMap.put(word, i);
i++;
}
// Print all words
// print {All!=[3], Hello=[0, 2], Hi=[4], World!=[1, 5]} -in natural order
System.out.println(multiMap);
// Print all unique words
// print [All!, Hello, Hi, World!] in natural order
System.out.println(multiMap.keySet());
// Print all indexes
// print [0, 2]
System.out.println("Hello = " + multiMap.get("Hello"));
// print [1, 5]
System.out.println("World = " + multiMap.get("World!"));
// print [3]
System.out.println("All = " + multiMap.get("All!"));
// print [4]
System.out.println("Hi = " + multiMap.get("Hi"));
// print null
System.out.println("Empty = " + multiMap.get("Empty"));
// Print count unique words
//print 4
System.out.println(multiMap.keySet().size());
}Example 4
| Project: hibernate-tools-master File: OverrideBinder.java View source code |
private static List<String> bindColumns(List<?> columns, Table table, OverrideRepository repository) {
Iterator<?> iterator = columns.iterator();
List<String> columnNames = new ArrayList<String>();
while (iterator.hasNext()) {
Element element = (Element) iterator.next();
Column column = new Column();
column.setName(element.attributeValue("name"));
String attributeValue = element.attributeValue("jdbc-type");
if (StringHelper.isNotEmpty(attributeValue)) {
column.setSqlTypeCode(new Integer(JDBCToHibernateTypeHelper.getJDBCType(attributeValue)));
}
TableIdentifier tableIdentifier = TableIdentifier.create(table);
if (table.getColumn(column) != null) {
throw new MappingException("Column " + column.getName() + " already exists in table " + tableIdentifier);
}
MultiMap map = MetaAttributeBinder.loadAndMergeMetaMap(element, new MultiValueMap());
if (map != null && !map.isEmpty()) {
repository.addMetaAttributeInfo(tableIdentifier, column.getName(), map);
}
table.addColumn(column);
columnNames.add(column.getName());
repository.setTypeNameForColumn(tableIdentifier, column.getName(), element.attributeValue("type"));
repository.setPropertyNameForColumn(tableIdentifier, column.getName(), element.attributeValue("property"));
boolean excluded = booleanValue(element.attributeValue("exclude"));
if (excluded) {
repository.setExcludedColumn(tableIdentifier, column.getName());
}
String foreignTableName = element.attributeValue("foreign-table");
if (foreignTableName != null) {
List<Column> localColumns = new ArrayList<Column>();
localColumns.add(column);
List<Column> foreignColumns = new ArrayList<Column>();
Table foreignTable = new Table();
foreignTable.setName(foreignTableName);
foreignTable.setCatalog(getValue(element.attributeValue("foreign-catalog"), table.getCatalog()));
foreignTable.setSchema(getValue(element.attributeValue("foreign-schema"), table.getSchema()));
String foreignColumnName = element.attributeValue("foreign-column");
if (foreignColumnName != null) {
Column foreignColumn = new Column();
foreignColumn.setName(foreignColumnName);
foreignColumns.add(foreignColumn);
} else {
throw new MappingException("foreign-column is required when foreign-table is specified on " + column);
}
ForeignKey key = table.createForeignKey(null, localColumns, foreignTableName, null, foreignColumns);
// only possible if foreignColumns is explicitly specified (workaround on aligncolumns)
key.setReferencedTable(foreignTable);
}
}
return columnNames;
}Example 5
| Project: jboss-migration-master File: AbstractMigrator.java View source code |
//</editor-fold>
/**
* Default implementation of examineConfigProperty();
* Simply puts it in a MultiValueMap if the module prefix belongs to the implementation.
*/
@Override
public //public int examineConfigProperty(String moduleName, String propName, String value) {
int examineConfigProperty(Configuration.ModuleSpecificProperty prop) {
if (!this.getConfigPropertyModuleName().equals(prop.getModuleId()))
return 0;
switch(prop.getPropName()) {
case Configuration.IfExists.PARAM_NAME:
this.ifExists = Configuration.IfExists.valueOf_Custom(prop.getValue());
break;
default:
if (this.config == null)
this.config = new MultiValueMap();
this.config.put(prop.getPropName(), prop.getValue());
break;
}
return 1;
}Example 6
| Project: openmrs-core-master File: PropertiesFileValidator.java View source code |
private MultiMap getAsPropertiesKeyValueMultiMap(List<String> fileLines) {
MultiMap multiMap = new MultiValueMap();
for (String line : fileLines) {
if (isCorectKeyValueLine(line)) {
Map.Entry<String, String> tuple = extractKeyValue(line);
multiMap.put(tuple.getKey(), tuple.getValue());
}
}
return multiMap;
}Example 7
| Project: ambari-master File: StackRoleCommandOrder.java View source code |
/**
* merge StackRoleCommandOrder content with parent
*
* @param parent parent StackRoleCommandOrder instance
*/
public void merge(StackRoleCommandOrder parent, boolean mergeProperties) {
HashMap<String, Object> mergedRoleCommandOrders = new HashMap<>();
HashMap<String, Object> parentData = parent.getContent();
List<String> keys = Arrays.asList(GENERAL_DEPS_KEY, GLUSTERFS_DEPS_KEY, NO_GLUSTERFS_DEPS_KEY, NAMENODE_HA_DEPS_KEY, RESOURCEMANAGER_HA_DEPS_KEY, HOST_ORDERED_UPGRADES_DEPS_KEY);
for (String key : keys) {
if (parentData.containsKey(key) && content.containsKey(key)) {
Map<String, Object> result = new HashMap<>();
Map<String, Object> parentProperties = (Map<String, Object>) parentData.get(key);
Map<String, Object> childProperties = (Map<String, Object>) content.get(key);
MultiValueMap childAndParentProperties = null;
childAndParentProperties = new MultiValueMap();
childAndParentProperties.putAll(childProperties);
childAndParentProperties.putAll(parentProperties);
for (Object property : childAndParentProperties.keySet()) {
List propertyValues = (List) childAndParentProperties.get(property);
Object values = propertyValues.get(0);
if (mergeProperties) {
List<String> valueList = new ArrayList<>();
for (Object value : propertyValues) {
if (value instanceof List) {
valueList.addAll((List<String>) value);
} else {
valueList.add(value.toString());
}
}
values = valueList;
}
result.put((String) property, values);
}
mergedRoleCommandOrders.put(key, result);
} else if (content.containsKey(key)) {
mergedRoleCommandOrders.put(key, content.get(key));
} else if (parentData.containsKey(key)) {
mergedRoleCommandOrders.put(key, parentData.get(key));
}
}
content = mergedRoleCommandOrders;
}Example 8
| Project: jadler-master File: JadlerMockerTest.java View source code |
/*
* Tests that defaults (status, headers, encoding) are used correctly when creating a stubbing instance.
*/
@Test
public void onRequestWithDefaults() {
final StubHttpServer server = mock(StubHttpServer.class);
final StubbingFactory sf = mock(StubbingFactory.class);
final JadlerMocker mocker = new JadlerMocker(server, sf);
mocker.setDefaultStatus(DEFAULT_STATUS);
mocker.addDefaultHeader(HEADER_NAME1, HEADER_VALUE1);
mocker.addDefaultHeader(HEADER_NAME2, HEADER_VALUE2);
mocker.setDefaultEncoding(DEFAULT_ENCODING);
mocker.onRequest();
//verify the Stubbing instance was created with the given defaults
final MultiMap defaultHeaders = new MultiValueMap();
defaultHeaders.put(HEADER_NAME1, HEADER_VALUE1);
defaultHeaders.put(HEADER_NAME2, HEADER_VALUE2);
verify(sf, times(1)).createStubbing(eq(DEFAULT_ENCODING), eq(DEFAULT_STATUS), eq(defaultHeaders));
}Example 9
| Project: msInspect-master File: MS2Correct.java View source code |
public static void correct(MSRun run, Feature[] ms2Features, Feature[] ms1Features, PrintWriter out) {
Map assignMap = new MultiValueMap();
Tree2D ms2Tree = new Tree2D();
for (int i = 1; i < ms2Features.length; i++) {
Feature feature = ms2Features[i];
ms2Tree.add(feature.scan, feature.mz, feature);
}
Arrays.sort(ms1Features, new Feature.IntensityDescComparator());
for (Feature feature : ms1Features) {
int minScanIndex = run.getIndexForScanNum(feature.getScanFirst());
if (minScanIndex > 0)
minScanIndex--;
int maxScanIndex = run.getIndexForScanNum(feature.getScanLast());
if (maxScanIndex < run.getScanCount() - 1)
maxScanIndex++;
int minScan = run.getScan(minScanIndex).getNum();
int maxScan = run.getScan(maxScanIndex).getNum() + 1;
double minMz = feature.mz - .25 / (feature.charge == 0 ? 1 : feature.charge);
double maxMz = feature.mz + (feature.peaks + .25) / (feature.charge == 0 ? 1 : feature.charge);
List<Feature> list = ms2Tree.getPoints(minScan, (float) minMz, maxScan, (float) maxMz);
if (null != list)
for (Feature ms2Feature : list) {
assignMap.put(ms2Feature, feature);
}
}
out.println("scan\tmz\tcharge\tintensity\tpeaks\tkl\tmatch");
//Write them out in the same order they came in...
for (Feature ms2Feature : ms2Features) {
Collection<Feature> col = (Collection) assignMap.get(ms2Feature);
if (null != col && col.size() > 0) {
int match = 0;
for (Feature feature : col) {
out.println(ms2Feature.scan + "\t" + feature.mz + "\t" + +feature.charge + "\t" + feature.intensity + "\t" + feature.peaks + "\t" + feature.kl + "\t" + match);
match++;
}
}
}
}Example 10
| Project: SEEP-master File: PolicyRulesEvaluator.java View source code |
/**
* Initializes the data structure that allows for the mapping of metric readings
* to the correct evaluators given the operator identifier in the reading and
* the operator(s) referenced by each scaling rule.
*/
protected void initializeEvaluators() {
logger.info("Initialising evaluators for scaling policy rules...");
this.evaluators = new MultiValueMap<Integer, PolicyRuleEvaluator>();
this.allEvaluators = new ArrayList<PolicyRuleEvaluator>();
// Rules that reference concrete operators are processed first
PolicyRules rules = getEvalSubject();
if (rules != null) {
for (PolicyRule rule : rules) {
Operator op = rule.getOperator();
if (op instanceof OneOperator) {
Integer operatorId = Integer.valueOf(((OneOperator) op).getId());
logger.debug("Creating evaluator for operator [" + operatorId + "]");
logger.debug("Binding to rule " + rule.toString());
evaluators.put(operatorId, new PolicyRuleEvaluator(rule, getEvalAdaptor(), new SystemTimeReference()));
}
}
// Now process wildcard rules that apply to all operators
for (PolicyRule rule : rules) {
Operator op = rule.getOperator();
if (op instanceof AllOperators) {
logger.debug("Creating evaluator for all operators");
logger.debug("Binding to rule " + rule.toString());
allEvaluators.add(new PolicyRuleEvaluator(rule, getEvalAdaptor(), new SystemTimeReference()));
}
}
// facilitates the routing to the correct evaluators for a metric reading
for (Integer operatorId : evaluators.keySet()) {
for (PolicyRuleEvaluator allEvaluator : allEvaluators) {
evaluators.put(operatorId, allEvaluator);
}
}
}
logger.info("Done initialising evaluators for scaling policy rules");
}Example 11
| Project: sqlpower-library-master File: VariablesPanel.java View source code |
@SuppressWarnings("unchecked")
private void showVarsPicker() {
final MultiValueMap namespaces = this.variableHelper.getNamespaces();
List<String> sortedNames = new ArrayList<String>(namespaces.keySet().size());
sortedNames.addAll(namespaces.keySet());
Collections.sort(sortedNames, new Comparator<String>() {
public int compare(String o1, String o2) {
if (o1 == null) {
return -1;
}
if (o2 == null) {
return 1;
}
return o1.compareTo(o2);
}
;
});
final JPopupMenu menu = new JPopupMenu();
for (final String name : sortedNames) {
final JMenu subMenu = new JMenu(name);
menu.add(subMenu);
subMenu.addMenuListener(new MenuListener() {
private Timer timer;
public void menuSelected(MenuEvent e) {
subMenu.removeAll();
subMenu.add(new PleaseWaitAction());
ActionListener menuPopulator = new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (subMenu.isPopupMenuVisible()) {
subMenu.removeAll();
for (Object namespaceO : namespaces.getCollection(name)) {
String namespace = (String) namespaceO;
logger.debug("Resolving variables for namespace ".concat(namespace));
int nbItems = 0;
for (String key : variableHelper.keySet(namespace)) {
subMenu.add(new InsertVariableAction(SPVariableHelper.getKey((String) key), (String) key));
nbItems++;
}
if (nbItems == 0) {
subMenu.add(new DummyAction());
logger.debug("No variables found.");
}
}
subMenu.revalidate();
subMenu.getPopupMenu().pack();
}
}
};
timer = new Timer(700, menuPopulator);
timer.setRepeats(false);
timer.start();
}
public void menuDeselected(MenuEvent e) {
timer.stop();
}
public void menuCanceled(MenuEvent e) {
timer.stop();
}
});
}
menu.show(varNameText, 0, varNameText.getHeight());
}Example 12
| Project: wikitext-master File: LanguageConfigGenerator.java View source code |
public static WikiConfig generateWikiConfig(String siteName, String siteUrl, String languagePrefix, String apiUrlNamespacealiases, String apiUrlNamespaces, String apiUrlInterwikimap, String apiUrlMagicwords) throws IOException, ParserConfigurationException, SAXException {
WikiConfigImpl wikiConfig = new WikiConfigImpl();
wikiConfig.setSiteName(siteName);
wikiConfig.setWikiUrl(siteUrl);
wikiConfig.setContentLang(languagePrefix);
wikiConfig.setIwPrefix(languagePrefix);
DefaultConfigEnWp config = new DefaultConfigEnWp();
config.configureEngine(wikiConfig);
MultiValueMap namespaceAliases = getNamespaceAliases(apiUrlNamespacealiases);
addNamespaces(wikiConfig, apiUrlNamespaces, namespaceAliases);
addInterwikis(wikiConfig, apiUrlInterwikimap);
addi18NAliases(wikiConfig, apiUrlMagicwords);
config.addParserFunctions(wikiConfig);
config.addTagExtensions(wikiConfig);
return wikiConfig;
}Example 13
| Project: spring-modules-master File: AjaxInterceptor.java View source code |
/**
* Set mappings configured in the given {@link java.util.Properties} object.<br>
* Each mapping associates an ANT based URL path with a comma separated list of {@link AjaxHandler}s configured in the Spring Application Context.<br>
* Mappings are ordered in a sorted map, following the longest path order (from the longest path to the shorter).<br>
* Please note that multiple mappings to the same URL are supported thanks to a {@link org.apache.commons.collections.map.MultiValueMap}.
*
* @param mappings A {@link java.util.Properties} containing handler mappings.
*/
public void setHandlerMappings(Properties mappings) {
this.handlerMappings = MultiValueMap.decorate(new TreeMap<String, String>(new Comparator() {
public int compare(Object o1, Object o2) {
if (!(o1 instanceof String) || !(o2 instanceof String)) {
throw new ClassCastException("You have to map an URL to a comma separated list of handler names.");
}
if (o1.equals(o2)) {
return 0;
} else if (o1.toString().length() > o2.toString().length()) {
return -1;
} else {
return 1;
}
}
}));
for (Map.Entry entry : mappings.entrySet()) {
String[] handlers = ((String) entry.getValue()).split(",");
for (String handler : handlers) {
String url = (String) entry.getKey();
if (!url.startsWith("/")) {
url = "/" + url;
}
this.handlerMappings.put(url.trim(), handler.trim());
}
}
}Example 14
| Project: exist-master File: LuceneIndexConfig.java View source code |
private void parse(Element root, Map<String, String> namespaces) throws DatabaseConfigurationException {
Node child = root.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
final String localName = child.getLocalName();
if (null != localName) {
Element configElement = (Element) child;
switch(localName) {
case IGNORE_ELEMENT:
{
String qnameAttr = configElement.getAttribute(QNAME_ATTR);
if (StringUtils.isEmpty(qnameAttr)) {
throw new DatabaseConfigurationException("Lucene configuration element 'ignore' needs an attribute 'qname'");
}
if (specialNodes == null) {
specialNodes = new TreeMap<>();
}
specialNodes.put(parseQName(qnameAttr, namespaces), N_IGNORE);
break;
}
case INLINE_ELEMENT:
{
String qnameAttr = configElement.getAttribute(QNAME_ATTR);
if (StringUtils.isEmpty(qnameAttr)) {
throw new DatabaseConfigurationException("Lucene configuration element 'inline' needs an attribute 'qname'");
}
if (specialNodes == null) {
specialNodes = new TreeMap<>();
}
specialNodes.put(parseQName(qnameAttr, namespaces), N_INLINE);
break;
}
case MATCH_SIBLING_ATTR_ELEMENT:
case HAS_SIBLING_ATTR_ELEMENT:
case HAS_ATTR_ELEMENT:
case MATCH_ATTR_ELEMENT:
{
final boolean doMatch = localName.equals(MATCH_ATTR_ELEMENT) || localName.equals(MATCH_SIBLING_ATTR_ELEMENT);
final boolean onSibling = localName.equals(HAS_SIBLING_ATTR_ELEMENT) || localName.equals(MATCH_SIBLING_ATTR_ELEMENT);
if (onSibling && !isAttributeNode()) {
throw new DatabaseConfigurationException("Lucene module: " + localName + " can only be used on attribute");
} else if (!onSibling && isAttributeNode()) {
throw new DatabaseConfigurationException("Lucene module: " + localName + " can not be used on attribute");
}
final String qname = configElement.getAttribute("qname");
if (StringUtils.isEmpty(qname)) {
throw new DatabaseConfigurationException("Lucene configuration element '" + localName + " needs an attribute 'qname'");
}
float boost;
final String boostStr = configElement.getAttribute("boost");
try {
boost = Float.parseFloat(boostStr);
} catch (NumberFormatException e) {
throw new DatabaseConfigurationException("Invalid value for attribute 'boost'. " + "Expected float, got: " + boostStr);
}
String value = null;
if (doMatch) {
value = configElement.getAttribute("value");
if (StringUtils.isEmpty(value)) {
throw new DatabaseConfigurationException("Lucene configuration element '" + localName + " needs an attribute 'value'");
}
}
if (matchAttrs == null)
matchAttrs = new MultiValueMap();
matchAttrs.put(qname, new MatchAttrData(qname, value, boost, onSibling));
break;
}
}
}
}
child = child.getNextSibling();
}
}Example 15
| Project: openiot-master File: MenuFactory.java View source code |
/**
* Groups the navigation properties in a Linked Hashmap where Key = the navigation group name
* e.g. Request Presentation Values = a Hashmap with the group fields e.g. Url, Title, Active
* Monitoring
*
* @return
*/
private HashMap<String, HashMap<String, String>> createPropertyMap() {
HashMap<String, HashMap<String, String>> itemMap = null;
HashMap<String, String> navigationMap = resources.getNavigationMap();
MultiValueMap groupMap = new MultiValueMap();
for (String key : navigationMap.keySet()) {
String newKey = key.split(IDE_CORE_GROUP)[1];
Scanner sc = new Scanner(newKey).useDelimiter("\\.");
String group = sc.next();
groupMap.put(group, sc.next());
sc.close();
}
itemMap = new LinkedHashMap<>();
for (Object parentKey : groupMap.keySet()) {
HashMap<String, String> childMap = new HashMap<>();
for (Object childKey : groupMap.getCollection(parentKey)) {
String fullKey = IDE_CORE_GROUP + parentKey + "." + childKey;
childMap.put((String) childKey, navigationMap.get(fullKey));
}
itemMap.put((String) parentKey, childMap);
}
System.out.println("ItemMap size: " + itemMap.size());
return itemMap;
}Example 16
| Project: type-mapper-for-uima-master File: TypeMapperTest.java View source code |
@Test(expected = AnalysisEngineProcessException.class)
public void testBeginAndEndDoNotMatch() throws ResourceInitializationException, AnalysisEngineProcessException {
Annotation sentenceAnnotation = (Annotation) cas.createAnnotation(sentenceType, 6, 4);
sentenceAnnotation.addToIndexes();
AnalysisEngine analysisEngine = AnalysisEngineFactory.createEngine(TypeMapper.class, TypeMapper.CONFIG_FILE_NAME, "src/test/resources/com/radialpoint/uima/typemapper/NormalWorkflowConfig.xml");
SimplePipeline.runPipeline(cas, analysisEngine);
MultiValueMap featureValues = new MultiValueMap();
featureValues.put("begin", sentenceAnnotation.getBegin());
featureValues.put("end", sentenceAnnotation.getEnd());
verifyMappedAnnotation(sentenceType, 1, featureValues);
}Example 17
| Project: XSLT-master File: LuceneIndexConfig.java View source code |
private void parse(Element root, Map<String, String> namespaces) throws DatabaseConfigurationException {
Node child = root.getFirstChild();
while (child != null) {
if (child.getNodeType() == Node.ELEMENT_NODE) {
final String localName = child.getLocalName();
if (null != localName) {
Element configElement = (Element) child;
switch(localName) {
case IGNORE_ELEMENT:
{
String qnameAttr = configElement.getAttribute(QNAME_ATTR);
if (StringUtils.isEmpty(qnameAttr)) {
throw new DatabaseConfigurationException("Lucene configuration element 'ignore' needs an attribute 'qname'");
}
if (specialNodes == null) {
specialNodes = new TreeMap<>();
}
specialNodes.put(parseQName(qnameAttr, namespaces), N_IGNORE);
break;
}
case INLINE_ELEMENT:
{
String qnameAttr = configElement.getAttribute(QNAME_ATTR);
if (StringUtils.isEmpty(qnameAttr)) {
throw new DatabaseConfigurationException("Lucene configuration element 'inline' needs an attribute 'qname'");
}
if (specialNodes == null) {
specialNodes = new TreeMap<>();
}
specialNodes.put(parseQName(qnameAttr, namespaces), N_INLINE);
break;
}
case MATCH_SIBLING_ATTR_ELEMENT:
case HAS_SIBLING_ATTR_ELEMENT:
case HAS_ATTR_ELEMENT:
case MATCH_ATTR_ELEMENT:
{
final boolean doMatch = localName.equals(MATCH_ATTR_ELEMENT) || localName.equals(MATCH_SIBLING_ATTR_ELEMENT);
final boolean onSibling = localName.equals(HAS_SIBLING_ATTR_ELEMENT) || localName.equals(MATCH_SIBLING_ATTR_ELEMENT);
if (onSibling && !isAttributeNode()) {
throw new DatabaseConfigurationException("Lucene module: " + localName + " can only be used on attribute");
} else if (!onSibling && isAttributeNode()) {
throw new DatabaseConfigurationException("Lucene module: " + localName + " can not be used on attribute");
}
final String qname = configElement.getAttribute("qname");
if (StringUtils.isEmpty(qname)) {
throw new DatabaseConfigurationException("Lucene configuration element '" + localName + " needs an attribute 'qname'");
}
float boost;
final String boostStr = configElement.getAttribute("boost");
try {
boost = Float.parseFloat(boostStr);
} catch (NumberFormatException e) {
throw new DatabaseConfigurationException("Invalid value for attribute 'boost'. " + "Expected float, got: " + boostStr);
}
String value = null;
if (doMatch) {
value = configElement.getAttribute("value");
if (StringUtils.isEmpty(value)) {
throw new DatabaseConfigurationException("Lucene configuration element '" + localName + " needs an attribute 'value'");
}
}
if (matchAttrs == null)
matchAttrs = new MultiValueMap();
matchAttrs.put(qname, new MatchAttrData(qname, value, boost, onSibling));
break;
}
}
}
}
child = child.getNextSibling();
}
}Example 18
| Project: directory-studio-master File: SchemaViewContentProvider.java View source code |
/**
* {@inheritDoc}
*/
public Object[] getChildren(Object parentElement) {
List<TreeNode> children = new ArrayList<TreeNode>();
int presentation = store.getInt(PluginConstants.PREFS_SCHEMA_VIEW_SCHEMA_PRESENTATION);
int group = store.getInt(PluginConstants.PREFS_SCHEMA_VIEW_GROUPING);
int sortBy = store.getInt(PluginConstants.PREFS_SCHEMA_VIEW_SORTING_BY);
int sortOrder = store.getInt(PluginConstants.PREFS_SCHEMA_VIEW_SORTING_ORDER);
if (parentElement instanceof SchemaViewRoot) {
root = (SchemaViewRoot) parentElement;
if (presentation == PluginConstants.PREFS_SCHEMA_VIEW_SCHEMA_PRESENTATION_FLAT) {
if (root.getChildren().isEmpty()) {
elementsToWrappersMap = new MultiValueMap();
SchemaHandler schemaHandler = Activator.getDefault().getSchemaHandler();
if (schemaHandler != null) {
List<Schema> schemas = schemaHandler.getSchemas();
for (Schema schema : schemas) {
addSchemaFlatPresentation(schema);
}
}
}
children = root.getChildren();
Collections.sort(children, schemaSorter);
} else if (presentation == PluginConstants.PREFS_SCHEMA_VIEW_SCHEMA_PRESENTATION_HIERARCHICAL) {
if (root.getChildren().isEmpty()) {
elementsToWrappersMap = new MultiValueMap();
hierarchyManager = new HierarchyManager();
if (group == PluginConstants.PREFS_SCHEMA_VIEW_GROUPING_FOLDERS) {
Folder atFolder = new Folder(FolderType.ATTRIBUTE_TYPE, root);
Folder ocFolder = new Folder(FolderType.OBJECT_CLASS, root);
root.addChild(atFolder);
root.addChild(ocFolder);
List<Object> rootChildren = hierarchyManager.getChildren(hierarchyManager.getRootObject());
if ((rootChildren != null) && (rootChildren.size() > 0)) {
for (Object rootChild : rootChildren) {
TreeNode childNode = null;
// Creating the wrapper
if (rootChild instanceof AttributeType) {
AttributeType at = (AttributeType) rootChild;
childNode = new AttributeTypeWrapper(at, atFolder);
atFolder.addChild(childNode);
} else if (rootChild instanceof ObjectClass) {
MutableObjectClass oc = (MutableObjectClass) rootChild;
childNode = new ObjectClassWrapper(oc, ocFolder);
ocFolder.addChild(childNode);
}
// Filling the 'Elements To Wrappers' Map
elementsToWrappersMap.put(rootChild, childNode);
// Recursively creating the hierarchy for all children
// of the root element.
addHierarchyChildren(childNode, hierarchyManager.getChildren(rootChild));
}
}
} else if (group == PluginConstants.PREFS_SCHEMA_VIEW_GROUPING_MIXED) {
addHierarchyChildren(root, hierarchyManager.getChildren(hierarchyManager.getRootObject()));
}
}
children = root.getChildren();
if (group == PluginConstants.PREFS_SCHEMA_VIEW_GROUPING_MIXED) {
// Sort by
if (sortBy == PluginConstants.PREFS_SCHEMA_VIEW_SORTING_BY_FIRSTNAME) {
Collections.sort(children, firstNameSorter);
} else if (sortBy == PluginConstants.PREFS_SCHEMA_VIEW_SORTING_BY_OID) {
Collections.sort(children, oidSorter);
}
// Sort Order
if (sortOrder == PluginConstants.PREFS_SCHEMA_VIEW_SORTING_ORDER_DESCENDING) {
Collections.reverse(children);
}
}
}
} else if (parentElement instanceof Folder) {
children = ((TreeNode) parentElement).getChildren();
// Sort by
if (sortBy == PluginConstants.PREFS_SCHEMA_VIEW_SORTING_BY_FIRSTNAME) {
Collections.sort(children, firstNameSorter);
} else if (sortBy == PluginConstants.PREFS_SCHEMA_VIEW_SORTING_BY_OID) {
Collections.sort(children, oidSorter);
}
// Sort Order
if (sortOrder == PluginConstants.PREFS_SCHEMA_VIEW_SORTING_ORDER_DESCENDING) {
Collections.reverse(children);
}
} else if ((parentElement instanceof AttributeTypeWrapper) || (parentElement instanceof ObjectClassWrapper)) {
children = ((TreeNode) parentElement).getChildren();
// Sort by
if (sortBy == PluginConstants.PREFS_SCHEMA_VIEW_SORTING_BY_FIRSTNAME) {
Collections.sort(children, firstNameSorter);
} else if (sortBy == PluginConstants.PREFS_SCHEMA_VIEW_SORTING_BY_OID) {
Collections.sort(children, oidSorter);
}
// Sort Order
if (sortOrder == PluginConstants.PREFS_SCHEMA_VIEW_SORTING_ORDER_DESCENDING) {
Collections.reverse(children);
}
} else if (parentElement instanceof SchemaWrapper) {
children = ((TreeNode) parentElement).getChildren();
if (group == PluginConstants.PREFS_SCHEMA_VIEW_GROUPING_MIXED) {
// Sort by
if (sortBy == PluginConstants.PREFS_SCHEMA_VIEW_SORTING_BY_FIRSTNAME) {
Collections.sort(children, firstNameSorter);
} else if (sortBy == PluginConstants.PREFS_SCHEMA_VIEW_SORTING_BY_OID) {
Collections.sort(children, oidSorter);
}
// Sort Order
if (sortOrder == PluginConstants.PREFS_SCHEMA_VIEW_SORTING_ORDER_DESCENDING) {
Collections.reverse(children);
}
}
}
return children.toArray();
}Example 19
| Project: flume-master File: ReplayHandler.java View source code |
/**
* Replay logic from Flume1.2 which can be activated if the v2 logic
* is failing on ol logs for some reason.
*/
@Deprecated
void replayLogv1(List<File> logs) throws Exception {
int total = 0;
int count = 0;
MultiMap transactionMap = new MultiValueMap();
//Read inflight puts to see if they were committed
SetMultimap<Long, Long> inflightPuts = queue.deserializeInflightPuts();
for (Long txnID : inflightPuts.keySet()) {
Set<Long> eventPointers = inflightPuts.get(txnID);
for (Long eventPointer : eventPointers) {
transactionMap.put(txnID, FlumeEventPointer.fromLong(eventPointer));
}
}
SetMultimap<Long, Long> inflightTakes = queue.deserializeInflightTakes();
LOG.info("Starting replay of " + logs);
for (File log : logs) {
LOG.info("Replaying " + log);
LogFile.SequentialReader reader = null;
try {
reader = LogFileFactory.getSequentialReader(log, encryptionKeyProvider, fsyncPerTransaction);
reader.skipToLastCheckpointPosition(queue.getLogWriteOrderID());
LogRecord entry;
FlumeEventPointer ptr;
// for puts the fileId is the fileID of the file they exist in
// for takes the fileId and offset are pointers to a put
int fileId = reader.getLogFileID();
while ((entry = reader.next()) != null) {
int offset = entry.getOffset();
TransactionEventRecord record = entry.getEvent();
short type = record.getRecordType();
long trans = record.getTransactionID();
readCount++;
if (record.getLogWriteOrderID() > lastCheckpoint) {
if (type == TransactionEventRecord.Type.PUT.get()) {
putCount++;
ptr = new FlumeEventPointer(fileId, offset);
transactionMap.put(trans, ptr);
} else if (type == TransactionEventRecord.Type.TAKE.get()) {
takeCount++;
Take take = (Take) record;
ptr = new FlumeEventPointer(take.getFileID(), take.getOffset());
transactionMap.put(trans, ptr);
} else if (type == TransactionEventRecord.Type.ROLLBACK.get()) {
rollbackCount++;
transactionMap.remove(trans);
} else if (type == TransactionEventRecord.Type.COMMIT.get()) {
commitCount++;
@SuppressWarnings("unchecked") Collection<FlumeEventPointer> pointers = (Collection<FlumeEventPointer>) transactionMap.remove(trans);
if (((Commit) record).getType() == TransactionEventRecord.Type.TAKE.get()) {
if (inflightTakes.containsKey(trans)) {
if (pointers == null) {
pointers = Sets.newHashSet();
}
Set<Long> takes = inflightTakes.removeAll(trans);
Iterator<Long> it = takes.iterator();
while (it.hasNext()) {
Long take = it.next();
pointers.add(FlumeEventPointer.fromLong(take));
}
}
}
if (pointers != null && pointers.size() > 0) {
processCommit(((Commit) record).getType(), pointers);
count += pointers.size();
}
} else {
Preconditions.checkArgument(false, "Unknown record type: " + Integer.toHexString(type));
}
} else {
skipCount++;
}
}
LOG.info("Replayed " + count + " from " + log);
if (LOG.isDebugEnabled()) {
LOG.debug("read: " + readCount + ", put: " + putCount + ", take: " + takeCount + ", rollback: " + rollbackCount + ", commit: " + commitCount + ", skipp: " + skipCount);
}
} catch (EOFException e) {
LOG.warn("Hit EOF on " + log);
} finally {
total += count;
count = 0;
if (reader != null) {
reader.close();
}
}
}
//re-insert the events in the take map,
//since the takes were not committed.
int uncommittedTakes = 0;
for (Long inflightTxnId : inflightTakes.keySet()) {
Set<Long> inflightUncommittedTakes = inflightTakes.get(inflightTxnId);
for (Long inflightUncommittedTake : inflightUncommittedTakes) {
queue.addHead(FlumeEventPointer.fromLong(inflightUncommittedTake));
uncommittedTakes++;
}
}
inflightTakes.clear();
count += uncommittedTakes;
int pendingTakesSize = pendingTakes.size();
if (pendingTakesSize > 0) {
String msg = "Pending takes " + pendingTakesSize + " exist after the end of replay";
if (LOG.isDebugEnabled()) {
for (Long pointer : pendingTakes) {
LOG.debug("Pending take " + FlumeEventPointer.fromLong(pointer));
}
} else {
LOG.error(msg + ". Duplicate messages will exist in destination.");
}
}
LOG.info("Replayed " + total);
}Example 20
| Project: mt-flume-master File: ReplayHandler.java View source code |
/**
* Replay logic from Flume1.2 which can be activated if the v2 logic
* is failing on ol logs for some reason.
*/
@Deprecated
void replayLogv1(List<File> logs) throws Exception {
int total = 0;
int count = 0;
MultiMap transactionMap = new MultiValueMap();
//Read inflight puts to see if they were committed
SetMultimap<Long, Long> inflightPuts = queue.deserializeInflightPuts();
for (Long txnID : inflightPuts.keySet()) {
Set<Long> eventPointers = inflightPuts.get(txnID);
for (Long eventPointer : eventPointers) {
transactionMap.put(txnID, FlumeEventPointer.fromLong(eventPointer));
}
}
SetMultimap<Long, Long> inflightTakes = queue.deserializeInflightTakes();
LOG.info("Starting replay of " + logs);
for (File log : logs) {
LOG.info("Replaying " + log);
LogFile.SequentialReader reader = null;
try {
reader = LogFileFactory.getSequentialReader(log, encryptionKeyProvider);
reader.skipToLastCheckpointPosition(queue.getLogWriteOrderID());
LogRecord entry;
FlumeEventPointer ptr;
// for puts the fileId is the fileID of the file they exist in
// for takes the fileId and offset are pointers to a put
int fileId = reader.getLogFileID();
while ((entry = reader.next()) != null) {
int offset = entry.getOffset();
TransactionEventRecord record = entry.getEvent();
short type = record.getRecordType();
long trans = record.getTransactionID();
readCount++;
if (record.getLogWriteOrderID() > lastCheckpoint) {
if (type == TransactionEventRecord.Type.PUT.get()) {
putCount++;
ptr = new FlumeEventPointer(fileId, offset);
transactionMap.put(trans, ptr);
} else if (type == TransactionEventRecord.Type.TAKE.get()) {
takeCount++;
Take take = (Take) record;
ptr = new FlumeEventPointer(take.getFileID(), take.getOffset());
transactionMap.put(trans, ptr);
} else if (type == TransactionEventRecord.Type.ROLLBACK.get()) {
rollbackCount++;
transactionMap.remove(trans);
} else if (type == TransactionEventRecord.Type.COMMIT.get()) {
commitCount++;
@SuppressWarnings("unchecked") Collection<FlumeEventPointer> pointers = (Collection<FlumeEventPointer>) transactionMap.remove(trans);
if (((Commit) record).getType() == TransactionEventRecord.Type.TAKE.get()) {
if (inflightTakes.containsKey(trans)) {
if (pointers == null) {
pointers = Sets.newHashSet();
}
Set<Long> takes = inflightTakes.removeAll(trans);
Iterator<Long> it = takes.iterator();
while (it.hasNext()) {
Long take = it.next();
pointers.add(FlumeEventPointer.fromLong(take));
}
}
}
if (pointers != null && pointers.size() > 0) {
processCommit(((Commit) record).getType(), pointers);
count += pointers.size();
}
} else {
Preconditions.checkArgument(false, "Unknown record type: " + Integer.toHexString(type));
}
} else {
skipCount++;
}
}
LOG.info("Replayed " + count + " from " + log);
if (LOG.isDebugEnabled()) {
LOG.debug("read: " + readCount + ", put: " + putCount + ", take: " + takeCount + ", rollback: " + rollbackCount + ", commit: " + commitCount + ", skipp: " + skipCount);
}
} catch (EOFException e) {
LOG.warn("Hit EOF on " + log);
} finally {
total += count;
count = 0;
if (reader != null) {
reader.close();
}
}
}
//re-insert the events in the take map,
//since the takes were not committed.
int uncommittedTakes = 0;
for (Long inflightTxnId : inflightTakes.keySet()) {
Set<Long> inflightUncommittedTakes = inflightTakes.get(inflightTxnId);
for (Long inflightUncommittedTake : inflightUncommittedTakes) {
queue.addHead(FlumeEventPointer.fromLong(inflightUncommittedTake));
uncommittedTakes++;
}
}
inflightTakes.clear();
count += uncommittedTakes;
int pendingTakesSize = pendingTakes.size();
if (pendingTakesSize > 0) {
String msg = "Pending takes " + pendingTakesSize + " exist after the end of replay";
if (LOG.isDebugEnabled()) {
for (Long pointer : pendingTakes) {
LOG.debug("Pending take " + FlumeEventPointer.fromLong(pointer));
}
} else {
LOG.error(msg + ". Duplicate messages will exist in destination.");
}
}
LOG.info("Replayed " + total);
}Example 21
| Project: screensaver-master File: CherryPickRequestPlateMapFilesBuilder.java View source code |
@SuppressWarnings("unchecked")
private /**
* Normally, we create 1 file per assay plate. However, in the case where an
* assay plate is comprised of wells from library copy plates that have
* different plate types, we need to generate a separate file for each source
* plate type (i.e., the assay plate will be defined over multiple files).
* @return a MultiMap that partitions the cherry picks by file,
* ordering both the file names and cherry picks for each file.
*/
MultiMap buildCherryPickFiles(/*<String,SortedSet<CherryPick>>*/
CherryPickRequest cherryPickRequest, Set<CherryPickAssayPlate> forPlates) {
MultiMap assayPlate2SourcePlateTypes = getSourcePlateTypesForEachAssayPlate(cherryPickRequest);
MultiMap result = MultiValueMap.decorate(new TreeMap<String, SortedSet<LabCherryPick>>(), new Factory() {
public Object create() {
return new TreeSet<LabCherryPick>(PlateMappingCherryPickComparator.getInstance());
}
});
// HACK: transform set of CPAP into a set of IDs, for purpose of checking
// set membership; we can't rely upon CPAP.equals(), since we're comparing
// non-managed entities with managed entities, and therefore we do not have
// the guarantee of instance equality for entities with the same ID
Set<Serializable> forPlateIds = new HashSet<Serializable>(forPlates.size());
for (CherryPickAssayPlate cpap : forPlates) {
if (cpap.getEntityId() == null) {
throw new IllegalArgumentException("all members of 'forPlates' must already be persisted and have a database identifier");
}
forPlateIds.add(cpap.getEntityId());
}
for (LabCherryPick cherryPick : cherryPickRequest.getLabCherryPicks()) {
if (cherryPick.isAllocated()) {
CherryPickAssayPlate assayPlate = cherryPick.getAssayPlate();
if (forPlates == null || (assayPlate != null && forPlateIds.contains(assayPlate.getEntityId()))) {
Set<PlateType> sourcePlateTypes = (Set<PlateType>) assayPlate2SourcePlateTypes.get(assayPlate.getName());
String fileName = makeFilename(cherryPick, sourcePlateTypes.size());
result.put(fileName, cherryPick);
}
}
}
return result;
}Example 22
| Project: nifi-master File: TestThreadPoolRequestReplicator.java View source code |
@Test
public void testMutableRequestRequiresAllNodesConnected() throws URISyntaxException {
final ClusterCoordinator coordinator = createClusterCoordinator();
// build a map of connection state to node ids
final Map<NodeConnectionState, List<NodeIdentifier>> nodeMap = new HashMap<>();
final List<NodeIdentifier> connectedNodes = new ArrayList<>();
connectedNodes.add(new NodeIdentifier("1", "localhost", 8100, "localhost", 8101, "localhost", 8102, 8103, false));
connectedNodes.add(new NodeIdentifier("2", "localhost", 8200, "localhost", 8201, "localhost", 8202, 8203, false));
nodeMap.put(NodeConnectionState.CONNECTED, connectedNodes);
final List<NodeIdentifier> otherState = new ArrayList<>();
otherState.add(new NodeIdentifier("3", "localhost", 8300, "localhost", 8301, "localhost", 8302, 8303, false));
nodeMap.put(NodeConnectionState.CONNECTING, otherState);
Mockito.when(coordinator.getConnectionStates()).thenReturn(nodeMap);
final ThreadPoolRequestReplicator replicator = new ThreadPoolRequestReplicator(2, new Client(), coordinator, "1 sec", "1 sec", null, null, NiFiProperties.createBasicNiFiProperties(null, null)) {
@Override
public AsyncClusterResponse replicate(Set<NodeIdentifier> nodeIds, String method, URI uri, Object entity, Map<String, String> headers, boolean indicateReplicated, boolean verify) {
return null;
}
};
try {
// set the user
final Authentication authentication = new NiFiAuthenticationToken(new NiFiUserDetails(StandardNiFiUser.ANONYMOUS));
SecurityContextHolder.getContext().setAuthentication(authentication);
try {
replicator.replicate(HttpMethod.POST, new URI("http://localhost:80/processors/1"), new ProcessorEntity(), new HashMap<>());
Assert.fail("Expected ConnectingNodeMutableRequestException");
} catch (final ConnectingNodeMutableRequestException e) {
}
nodeMap.remove(NodeConnectionState.CONNECTING);
nodeMap.put(NodeConnectionState.DISCONNECTED, otherState);
try {
replicator.replicate(HttpMethod.POST, new URI("http://localhost:80/processors/1"), new ProcessorEntity(), new HashMap<>());
Assert.fail("Expected DisconnectedNodeMutableRequestException");
} catch (final DisconnectedNodeMutableRequestException e) {
}
nodeMap.remove(NodeConnectionState.DISCONNECTED);
nodeMap.put(NodeConnectionState.DISCONNECTING, otherState);
try {
replicator.replicate(HttpMethod.POST, new URI("http://localhost:80/processors/1"), new ProcessorEntity(), new HashMap<>());
Assert.fail("Expected DisconnectedNodeMutableRequestException");
} catch (final DisconnectedNodeMutableRequestException e) {
}
// should not throw an Exception because it's a GET
replicator.replicate(HttpMethod.GET, new URI("http://localhost:80/processors/1"), new MultiValueMap<>(), new HashMap<>());
// should not throw an Exception because all nodes are now connected
nodeMap.remove(NodeConnectionState.DISCONNECTING);
replicator.replicate(HttpMethod.POST, new URI("http://localhost:80/processors/1"), new ProcessorEntity(), new HashMap<>());
} finally {
replicator.shutdown();
}
}Example 23
| Project: openmicroscopy-master File: RoiI.java View source code |
@SuppressWarnings("unchecked")
public Object mapReturnValue(IceMapper mapper, Object value) throws Ice.UserException {
RoiResult result = new RoiResult();
result.opts = opts;
if (value == null) {
result.rois = Collections.emptyList();
result.byZ = Collections.emptyMap();
result.byT = Collections.emptyMap();
result.byG = Collections.emptyMap();
result.groups = Collections.emptyMap();
// EARLY EXIT
return result;
}
List<Roi> rois = (List<Roi>) IceMapper.FILTERABLE_COLLECTION.mapReturnValue(mapper, value);
result.rois = rois;
MultiMap byZ = new MultiValueMap();
MultiMap byT = new MultiValueMap();
MultiMap byG = new MultiValueMap();
for (Roi roi : rois) {
omero.model.RoiI roii = (omero.model.RoiI) roi;
Iterator<Shape> it = roii.iterateShapes();
while (it.hasNext()) {
Shape shape = it.next();
if (shape == null) {
continue;
}
if (shape.getTheT() != null) {
byT.put(shape.getTheT().getValue(), shape);
} else {
byT.put(-1, shape);
}
if (shape.getTheZ() != null) {
byZ.put(shape.getTheZ().getValue(), shape);
} else {
byZ.put(-1, shape);
}
if (shape.getG() != null) {
byG.put(shape.getG().getValue(), shape);
} else {
byG.put("", shape);
}
}
result.byG = byG;
result.byZ = byZ;
result.byT = byT;
}
return result;
}Example 24
| Project: Portofino-master File: AbstractPageAction.java View source code |
@Override
public MultiMap initEmbeddedPageActions() {
if (embeddedPageActions == null) {
MultiMap mm = new MultiValueMap();
Layout layout = pageInstance.getLayout();
for (ChildPage childPage : layout.getChildPages()) {
String layoutContainerInParent = childPage.getContainer();
if (layoutContainerInParent != null) {
String newPath = context.getActionPath() + "/" + childPage.getName();
//#PRT-1650 Path parameters mess with include
newPath = ServletUtils.removePathParameters(newPath);
File pageDir = new File(pageInstance.getChildrenDirectory(), childPage.getName());
try {
Page page = DispatcherLogic.getPage(pageDir);
EmbeddedPageAction embeddedPageAction = new EmbeddedPageAction(childPage.getName(), childPage.getActualOrder(), newPath, page);
mm.put(layoutContainerInParent, embeddedPageAction);
} catch (PageNotActiveException e) {
logger.warn("Embedded page action is not active, skipping! " + pageDir, e);
}
}
}
for (Object entryObj : mm.entrySet()) {
Map.Entry entry = (Map.Entry) entryObj;
List pageActionContainer = (List) entry.getValue();
Collections.sort(pageActionContainer);
}
embeddedPageActions = mm;
}
return embeddedPageActions;
}Example 25
| Project: tdq-studio-se-master File: ColumnsSelectionDialog.java View source code |
/**
* init this Dialog.
*
* @param title
* @param checkedRepoNodes
*/
private void initDialog(String title, List<? extends IRepositoryNode> checkedRepoNodes) {
modelElementCheckedMap = new MultiValueMap();
initCheckedElements(checkedRepoNodes);
addFilter(new EMFObjFilter());
addFilter(new DQFolderFilter(true));
addFilter(new TDQEEConnectionFolderFilter());
// ADD msjian TDQ-10441: hide the hadoop cluster folder node
addFilter(new HadoopCLusterFolderNodeFilter());
// TDQ-10441~
// ADD msjian TDQ-11253: hide the column folder nodes and column nodes
addFilter(new ColumnAndFolderNodeFilter());
// TDQ-11253~
setTitle(title);
}Example 26
| Project: wso2-synapse-master File: ClientHandler.java View source code |
private void setHeaders(HttpContext context, HttpResponse response, MessageContext outMsgCtx, MessageContext responseMsgCtx) {
Header[] headers = response.getAllHeaders();
if (headers != null && headers.length > 0) {
Map<String, String> headerMap = new TreeMap<String, String>(new Comparator<String>() {
public int compare(String o1, String o2) {
return o1.compareToIgnoreCase(o2);
}
});
String endpointURLPrefix = (String) context.getAttribute(NhttpConstants.ENDPOINT_PREFIX);
String servicePrefix = (String) outMsgCtx.getProperty(NhttpConstants.SERVICE_PREFIX);
for (int i = 0; i < headers.length; i++) {
Header header = headers[i];
// if this header is already added
if (headerMap.containsKey(header.getName())) {
/* this is a multi-value header */
// generate the key
String key = NhttpConstants.EXCESS_TRANSPORT_HEADERS;
// get the old value
String oldValue = headerMap.get(header.getName());
// adds additional values to a list in a property of message
// context
Map map;
if (responseMsgCtx.getProperty(key) != null) {
map = (Map) responseMsgCtx.getProperty(key);
map.put(header.getName(), oldValue);
} else {
map = new MultiValueMap();
map.put(header.getName(), oldValue);
// set as a property in message context
responseMsgCtx.setProperty(key, map);
}
}
if ("Location".equals(header.getName()) && endpointURLPrefix != null && servicePrefix != null) {
// name and the port.
try {
URI serviceURI = new URI(servicePrefix);
URI endpointURI = new URI(endpointURLPrefix);
URI locationURI = new URI(header.getValue());
if (locationURI.getHost().equalsIgnoreCase(endpointURI.getHost())) {
URI newURI = new URI(locationURI.getScheme(), locationURI.getUserInfo(), serviceURI.getHost(), serviceURI.getPort(), locationURI.getPath(), locationURI.getQuery(), locationURI.getFragment());
headerMap.put(header.getName(), newURI.toString());
responseMsgCtx.setProperty(NhttpConstants.SERVICE_PREFIX, outMsgCtx.getProperty(NhttpConstants.SERVICE_PREFIX));
}
} catch (URISyntaxException e) {
log.error(e.getMessage(), e);
}
} else {
headerMap.put(header.getName(), header.getValue());
}
}
responseMsgCtx.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap);
}
}Example 27
| Project: commons-collections-master File: MapUtilsTest.java View source code |
@Test
public void testPopulateMultiMap() {
// Setup Test Data
final List<X> list = new ArrayList<X>();
list.add(new X(1, "x1"));
list.add(new X(2, "x2"));
list.add(new X(2, "x3"));
list.add(new X(5, "x4"));
list.add(new X(5, "x5"));
// Now test key transform population
final MultiValueMap<Integer, X> map = MultiValueMap.multiValueMap(new TreeMap<Integer, Collection<X>>());
MapUtils.populateMap(map, list, new Transformer<X, Integer>() {
@Override
public Integer transform(X input) {
return input.key;
}
}, TransformerUtils.<X>nopTransformer());
assertEquals(list.size(), map.totalSize());
for (int i = 0; i < list.size(); i++) {
assertEquals(true, map.containsKey(list.get(i).key));
assertEquals(true, map.containsValue(list.get(i)));
}
}Example 28
| Project: opencms-core-master File: CmsVfsService.java View source code |
/**
* @see org.opencms.gwt.shared.rpc.I_CmsVfsService#getBrokenLinks(java.lang.String)
*/
public CmsDeleteResourceBean getBrokenLinks(String sitePath) throws CmsRpcException {
try {
CmsResource entryResource = getCmsObject().readResource(sitePath, CmsResourceFilter.IGNORE_EXPIRATION);
CmsDeleteResourceBean result = null;
CmsListInfoBean info = null;
List<CmsBrokenLinkBean> brokenLinks = null;
CmsObject cms = getCmsObject();
String resourceSitePath = cms.getSitePath(entryResource);
try {
ensureSession();
List<CmsResource> descendants = new ArrayList<CmsResource>();
HashSet<CmsUUID> deleteIds = new HashSet<CmsUUID>();
descendants.add(entryResource);
if (entryResource.isFolder()) {
descendants.addAll(cms.readResources(resourceSitePath, CmsResourceFilter.IGNORE_EXPIRATION));
}
for (CmsResource deleteRes : descendants) {
deleteIds.add(deleteRes.getStructureId());
}
MultiValueMap linkMap = MultiValueMap.decorate(new HashMap<Object, Object>(), FactoryUtils.instantiateFactory(HashSet.class));
for (CmsResource resource : descendants) {
List<CmsResource> linkSources = getLinkSources(cms, resource, deleteIds);
for (CmsResource source : linkSources) {
linkMap.put(resource, source);
}
}
brokenLinks = getBrokenLinkBeans(linkMap);
info = getPageInfo(entryResource);
result = new CmsDeleteResourceBean(resourceSitePath, info, brokenLinks);
} catch (Throwable e) {
error(e);
}
return result;
} catch (CmsException e) {
error(e);
return null;
}
}Example 29
| Project: opencms-master File: CmsVfsService.java View source code |
/**
* @see org.opencms.gwt.shared.rpc.I_CmsVfsService#getBrokenLinks(java.lang.String)
*/
public CmsDeleteResourceBean getBrokenLinks(String sitePath) throws CmsRpcException {
try {
CmsResource entryResource = getCmsObject().readResource(sitePath, CmsResourceFilter.IGNORE_EXPIRATION);
CmsDeleteResourceBean result = null;
CmsListInfoBean info = null;
List<CmsBrokenLinkBean> brokenLinks = null;
CmsObject cms = getCmsObject();
String resourceSitePath = cms.getSitePath(entryResource);
try {
ensureSession();
List<CmsResource> descendants = new ArrayList<CmsResource>();
HashSet<CmsUUID> deleteIds = new HashSet<CmsUUID>();
descendants.add(entryResource);
if (entryResource.isFolder()) {
descendants.addAll(cms.readResources(resourceSitePath, CmsResourceFilter.IGNORE_EXPIRATION));
}
for (CmsResource deleteRes : descendants) {
deleteIds.add(deleteRes.getStructureId());
}
MultiValueMap linkMap = MultiValueMap.decorate(new HashMap<Object, Object>(), FactoryUtils.instantiateFactory(HashSet.class));
for (CmsResource resource : descendants) {
List<CmsResource> linkSources = getLinkSources(cms, resource, deleteIds);
for (CmsResource source : linkSources) {
linkMap.put(resource, source);
}
}
brokenLinks = getBrokenLinkBeans(linkMap);
info = getPageInfo(entryResource);
result = new CmsDeleteResourceBean(resourceSitePath, info, brokenLinks);
} catch (Throwable e) {
error(e);
}
return result;
} catch (CmsException e) {
error(e);
return null;
}
}Example 30
| Project: directory-shared-master File: Rdn.java View source code |
/**
* Add an Ava to the current Rdn
*
* @param upType The user provided type of the added Rdn.
* @param type The normalized provided type of the added Rdn.
* @param upValue The user provided value of the added Rdn
* @param value The normalized provided value of the added Rdn
* @throws LdapInvalidDnException
* If the Rdn is invalid
*/
private void addAVA(SchemaManager schemaManager, String upType, String type, Value<?> value) throws LdapInvalidDnException {
// First, let's normalize the type
AttributeType attributeType;
String normalizedType = Strings.lowerCaseAscii(type);
this.schemaManager = schemaManager;
if (schemaManager != null) {
attributeType = schemaManager.getAttributeType(normalizedType);
try {
value.apply(attributeType);
} catch (LdapInvalidAttributeValueException liave) {
throw new LdapInvalidDnException(liave.getMessage(), liave);
}
}
switch(nbAvas) {
case 0:
// This is the first Ava. Just stores it.
ava = new Ava(schemaManager, upType, normalizedType, value);
nbAvas = 1;
avaType = normalizedType;
hashCode();
return;
case 1:
// We already have an Ava. We have to put it in the HashMap
// before adding a new one.
// First, create the HashMap,
avas = new ArrayList<>();
// and store the existing Ava into it.
avas.add(ava);
avaTypes = new MultiValueMap();
avaTypes.put(avaType, ava);
ava = null;
default:
// add a new Ava
Ava newAva = new Ava(schemaManager, upType, normalizedType, value);
avas.add(newAva);
avaTypes.put(normalizedType, newAva);
nbAvas++;
hashCode();
return;
}
}Example 31
| Project: sosies-generator-master File: MapUtilsTest.java View source code |
@org.junit.Test(timeout = 1000)
public void testPopulateMultiMap_add2677() {
fr.inria.diversify.testamplification.logger.Logger.writeTestStart(Thread.currentThread(), this, "testPopulateMultiMap_add2677");
final List<X> list = new ArrayList<X>();
list.add(new X(1, "x1"));
list.add(new X(1, "x1"));
list.add(new X(2, "x2"));
list.add(new X(2, "x3"));
list.add(new X(5, "x4"));
list.add(new X(5, "x5"));
final MultiValueMap<java.lang.Integer, X> map = MultiValueMap.multiValueMap(new TreeMap<java.lang.Integer, java.util.Collection<X>>());
org.apache.commons.collections4.MapUtils.populateMap(map, list, new Transformer<X, java.lang.Integer>() {
public Integer transform(X input) {
return input.key;
}
}, org.apache.commons.collections4.TransformerUtils.<X>nopTransformer());
fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 7893, list, 7892, list.size());
fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 7895, map, 7894, map.totalSize());
for (int i = 0; i < (list.size()); i++) {
fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 7897, map, 7896, map.containsKey(list.get(i).key));
fr.inria.diversify.testamplification.logger.Logger.logAssertArgument(Thread.currentThread(), 7899, map, 7898, map.containsValue(list.get(i)));
}
fr.inria.diversify.testamplification.logger.Logger.writeTestFinish(Thread.currentThread());
}Example 32
| Project: dbvim-master File: AnnotationProcessor.java View source code |
public MultiValueMap getEvents() {
return events;
}Example 33
| Project: DSpace-master File: Query.java View source code |
/**
* Retrieve the parameters set to this Query object
*
* @return the {@link org.apache.commons.collections.map.MultiValueMap} set to this object
*/
public MultiValueMap getParameters() {
return parameters;
}Example 34
| Project: evrythng-java-sdk-master File: URIBuilder.java View source code |
/**
* Adds a query parameters to the URI
*/
public URIBuilder queryParams(final MultiValueMap params) {
parameters.putAll(params);
return this;
}Example 35
| Project: jenkins-filesize-monitor-master File: FileSizeReport.java View source code |
public MultiValueMap getFilterFiles() {
return filterFiles;
}Example 36
| Project: cocoon-master File: AbstractDoubleMapEventRegistry.java View source code |
protected void createMultiMaps() {
this.m_eventMultiMap = MultiValueMap.decorate(m_eventMap, HashSet.class);
this.m_keyMultiMap = MultiValueMap.decorate(m_keyMap, HashSet.class);
}Example 37
| Project: software-master File: Brown.java View source code |
@Override
public MultiValueMap getLinks() {
return links;
}Example 38
| Project: EclipseTrader-master File: MapUtils.java View source code |
/**
* Creates a mult-value map backed by the given map which returns
* collections of type ArrayList.
*
* @param map the map to decorate
* @return a multi-value map backed by the given map which returns ArrayLists of values.
* @see MultiValueMap
* @since Commons Collections 3.2
*/
public static Map multiValueMap(Map map) {
return MultiValueMap.decorate(map);
}Example 39
| Project: External-Projects-master File: MapUtils.java View source code |
/**
* Creates a mult-value map backed by the given map which returns
* collections of type ArrayList.
*
* @param map the map to decorate
* @return a multi-value map backed by the given map which returns ArrayLists of values.
* @see MultiValueMap
* @since Commons Collections 3.2
*/
public static Map multiValueMap(Map map) {
return MultiValueMap.decorate(map);
}Example 40
| Project: extreme-fishbowl-master File: MapUtils.java View source code |
/**
* Creates a mult-value map backed by the given map which returns
* collections of type ArrayList.
*
* @param map the map to decorate
* @return a multi-value map backed by the given map which returns ArrayLists of values.
* @see MultiValueMap
* @since Commons Collections 3.2
*/
public static Map multiValueMap(Map map) {
return MultiValueMap.decorate(map);
}Example 41
| Project: yoursway-ide-master File: MapUtils.java View source code |
/**
* Creates a mult-value map backed by the given map which returns
* collections of type ArrayList.
*
* @param map the map to decorate
* @return a multi-value map backed by the given map which returns ArrayLists of values.
* @see MultiValueMap
* @since Commons Collections 3.2
*/
public static Map multiValueMap(Map map) {
return MultiValueMap.decorate(map);
}