List of usage examples for java.util LinkedHashMap keySet
public Set<K> keySet()
From source file:net.sf.maltcms.chromaui.normalization.spi.charts.PeakGroupBoxPlot.java
protected String getPeakName(IPeakGroupDescriptor pgd) { String rt = "mean area: " + String.format("%.2f", pgd.getMeanArea(normalizer)) + "+/-" + String.format("%.2f", pgd.getAreaStdDev(normalizer)) + "; median area: " + String.format("%.2f", pgd.getMedianArea(normalizer)) + ": "; LinkedHashMap<String, Integer> names = new LinkedHashMap<>(); if (!pgd.getDisplayName().equals(pgd.getName())) { return rt + pgd.getDisplayName(); }/*from www .j a v a2 s . co m*/ for (IPeakAnnotationDescriptor ipad : pgd.getPeakAnnotationDescriptors()) { if (names.containsKey(ipad.getName())) { names.put(ipad.getName(), names.get(ipad.getName()) + 1); } else { names.put(ipad.getName(), 1); } } if (names.isEmpty()) { return rt + "<NA>"; } if (names.size() > 1) { StringBuilder sb = new StringBuilder(); for (String key : names.keySet()) { sb.append(key); sb.append(" (" + names.get(key) + ")"); sb.append(" | "); } return rt + sb.replace(sb.length() - 1, sb.length() - 1, "").toString(); } else { return rt + names.keySet().toArray(new String[0])[0]; } }
From source file:com.ikanow.aleph2.search_service.elasticsearch.utils.ElasticsearchIndexUtils.java
/** Builds a lookup table of settings * @param mapping - the mapping to use// ww w. ja va 2 s.c o m * @param type - if the index has a specific type, lookup that and _default_ ; otherwise just _default * @return */ public static LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> parseDefaultMapping( final JsonNode mapping, final Optional<String> type, final Optional<DataSchemaBean.SearchIndexSchemaBean> maybe_search_index_schema, final Optional<DataSchemaBean.DocumentSchemaBean> maybe_document_schema, final SearchIndexSchemaDefaultBean search_index_schema_override, final ObjectMapper mapper) { //(see similar code in createComplexStringLookups) final boolean tokenize_by_default = maybe_search_index_schema.map(schema -> schema.tokenize_by_default()) .orElse(true); final boolean dual_tokenize_by_default = Optional .ofNullable(search_index_schema_override.dual_tokenize_by_default()).orElse(false); final JsonNode default_string_mapping = ((ObjectNode) (ElasticsearchIndexUtils.getMapping( Tuples._2T(tokenize_by_default, dual_tokenize_by_default), search_index_schema_override, mapper, true))).put(TYPE_MATCH_NAME, "string").put(PATH_MATCH_NAME, "*"); // (this is always not tokenized but inherits dual tokenization) final ObjectNode not_analyzed_field = ((ObjectNode) (ElasticsearchIndexUtils.getMapping( Tuples._2T(false, dual_tokenize_by_default), search_index_schema_override, mapper, true))) .put(TYPE_MATCH_NAME, "string"); final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> ret = Optional .ofNullable(mapping.get("mappings")).map(m -> { if (!m.isObject()) throw new RuntimeException("mappings must be object"); return m; }) .map(m -> Optional.ofNullable(m.get(type.orElse("_default_"))) .map(mm -> !mm.isNull() ? mm : m.get("_default_")).orElse(m.get("_default_"))) .filter(m -> !m.isNull()).map(i -> { if (!i.isObject()) throw new RuntimeException(type + " must be object"); return i; }).map(i -> { // OK so I have a list of dynamic_templates, and a list of properties - and then a set of string defaults to apply // 1) want to leave the properties alone // 2) then the tokenization overrides from createComplexStringLookups // 3) then the existing templates final Map<Either<String, Tuple2<String, String>>, JsonNode> override_props = createComplexStringLookups( maybe_search_index_schema, search_index_schema_override, mapper); // ensure string doc fields aren't analyzed final Map<Either<String, Tuple2<String, String>>, String> type_override = maybe_search_index_schema .map(s -> s.type_override()).map(m -> buildTypeMap(m)).orElse(Collections.emptyMap()); final Map<Either<String, Tuple2<String, String>>, JsonNode> doc_props = maybe_document_schema .map(ds -> ds.deduplication_fields()) .<Map<Either<String, Tuple2<String, String>>, JsonNode>>map(fields -> { return fields.stream().filter(f -> !override_props.containsKey(Either.left(f))) .filter(f -> !override_props.containsKey(Either.right(Tuples._2T(f, "*")))) .filter(f -> !type_override.containsKey(Either.left(f))) .filter(f -> !type_override.containsKey(Either.right(Tuples._2T(f, "*")))) .<Tuple2<Either<String, Tuple2<String, String>>, JsonNode>>map( f -> Tuples._2T(Either.right(Tuples._2T(f, "string")), not_analyzed_field.deepCopy().put(PATH_MATCH_NAME, f))) .collect(Collectors.toMap( (Tuple2<Either<String, Tuple2<String, String>>, JsonNode> t2) -> t2 ._1(), t2 -> t2._2())); }).orElse(Collections.emptyMap()); final LinkedHashMap<Either<String, Tuple2<String, String>>, JsonNode> props = new LinkedHashMap<>(); props.putAll(doc_props); // (put these first - though actually i'm fixing the order with an explicit sort in the columnar section) props.putAll(override_props); // extra mappings and extra templates Optionals.of(() -> search_index_schema_override.extra_field_mappings()) .map(o -> mapper.convertValue(o, JsonNode.class)).ifPresent(j -> { props.putAll(getTemplates(j, default_string_mapping, props.keySet())); props.putAll(getProperties(j)); }); // full mappings at the end props.putAll(getTemplates(i, default_string_mapping, props.keySet())); props.putAll(getProperties(i)); return props; }).orElse(new LinkedHashMap<>()); return ret; }
From source file:com.amalto.workbench.dialogs.MenuEntryDialog.java
@Override protected Control createDialogArea(Composite parent) { // Should not really be here but well,.... parent.getShell().setText(this.title); Composite composite = (Composite) super.createDialogArea(parent); GridLayout layout = (GridLayout) composite.getLayout(); layout.numColumns = 3;//ww w . ja v a 2s . c o m // layout.verticalSpacing = 10; Label idLabel = new Label(composite, SWT.NONE); idLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); idLabel.setText(Messages.MenuEntryDialog_Id); if (this.isChanged) { idText = new Text(composite, SWT.NONE); } else { idText = new Text(composite, SWT.NONE | SWT.READ_ONLY); } idText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); ((GridData) idText.getLayoutData()).widthHint = 300; idText.setDoubleClickEnabled(false); Label contextLabel = new Label(composite, SWT.NONE); contextLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); contextLabel.setText(Messages.MenuEntryDialog_Context); contextText = new Text(composite, SWT.NONE); contextText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); contextText.setDoubleClickEnabled(false); Label applicationNameLabel = new Label(composite, SWT.NONE); applicationNameLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); applicationNameLabel.setText(Messages.MenuEntryDialog_Application); applicationNameText = new Text(composite, SWT.NONE); applicationNameText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 2, 1)); Label iconPathLabel = new Label(composite, SWT.NONE); iconPathLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); iconPathLabel.setText(Messages.MenuEntryDialog_IconPath); iconPathText = new FileSelectWidget(composite, "", new String[] { "*.png", "*.gif", "*.jpg" }, "", true);//$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$ //$NON-NLS-5$ // Labels descriptionsComposite = new Composite(composite, SWT.BORDER); descriptionsComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1)); descriptionsComposite.setLayout(new GridLayout(3, false)); Label descriptionsLabel = new Label(descriptionsComposite, SWT.NULL); descriptionsLabel.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1)); descriptionsLabel.setText(Messages.MenuEntryDialog_MenuEntryLabels); languagesCombo = new Combo(descriptionsComposite, SWT.READ_ONLY | SWT.DROP_DOWN | SWT.SINGLE); languagesCombo.setLayoutData(new GridData(SWT.BEGINNING, SWT.NONE, false, false, 1, 1)); Set<String> languages = Util.lang2iso.keySet(); for (Object element : languages) { String language = (String) element; languagesCombo.add(language); } languagesCombo.addModifyListener(new ModifyListener() { public void modifyText(ModifyEvent e) { } }); languagesCombo.select(0); labelText = new Text(descriptionsComposite, SWT.BORDER | SWT.SINGLE); labelText.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1)); labelText.addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { if ((e.stateMask == 0) && (e.character == SWT.CR)) { String isoCode = Util.lang2iso.get(languagesCombo.getText()); descriptionsMap.put(isoCode, labelText.getText()); descriptionsViewer.refresh(); } } }); Button addLabelButton = new Button(descriptionsComposite, SWT.PUSH); addLabelButton.setLayoutData(new GridData(SWT.FILL, SWT.FILL, false, true, 1, 1)); addLabelButton.setImage(ImageCache.getCreatedImage(EImage.ADD_OBJ.getPath())); addLabelButton.setToolTipText(Messages.MenuEntryDialog_Add); addLabelButton.addSelectionListener(new SelectionListener() { public void widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent e) { }; public void widgetSelected(org.eclipse.swt.events.SelectionEvent e) { String isoCode = Util.lang2iso.get(languagesCombo.getText()); descriptionsMap.put(isoCode, labelText.getText()); descriptionsViewer.refresh(); }; }); final String LANGUAGE = Messages.MenuEntryDialog_Language; final String LABEL = Messages.MenuEntryDialog_Label; descriptionsViewer = new TableViewer(descriptionsComposite, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL | SWT.BORDER | SWT.FULL_SELECTION); descriptionsViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 3, 1)); ((GridData) descriptionsViewer.getControl().getLayoutData()).heightHint = 100; // Set up the underlying table Table table = descriptionsViewer.getTable(); // table.setLayoutData(new GridData(GridData.FILL_BOTH)); new TableColumn(table, SWT.LEFT).setText(LANGUAGE); new TableColumn(table, SWT.CENTER).setText(LABEL); table.getColumn(0).setWidth(150); table.getColumn(1).setWidth(150); for (int i = 2, n = table.getColumnCount(); i < n; i++) { table.getColumn(i).pack(); } table.setHeaderVisible(true); table.setLinesVisible(true); // Create the cell editors --> We actually discard those later: not natural for an user CellEditor[] editors = new CellEditor[2]; editors[0] = new TextCellEditor(table); editors[1] = new TextCellEditor(table); descriptionsViewer.setCellEditors(editors); // set the content provider descriptionsViewer.setContentProvider(new IStructuredContentProvider() { public void dispose() { } public void inputChanged(Viewer viewer, Object oldInput, Object newInput) { } public Object[] getElements(Object inputElement) { // System.out.println("getElements() "); LinkedHashMap<String, String> descs = (LinkedHashMap<String, String>) inputElement; Set<String> languages = descs.keySet(); ArrayList<DescriptionLine> lines = new ArrayList<DescriptionLine>(); for (Object element : languages) { String language = (String) element; DescriptionLine line = new DescriptionLine(Util.iso2lang.get(language), descs.get(language)); lines.add(line); } // we return an instance line made of a Sring and a boolean return lines.toArray(new DescriptionLine[lines.size()]); } }); // set the label provider descriptionsViewer.setLabelProvider(new ITableLabelProvider() { public boolean isLabelProperty(Object element, String property) { return false; } public void dispose() { } public void addListener(ILabelProviderListener listener) { } public void removeListener(ILabelProviderListener listener) { } public String getColumnText(Object element, int columnIndex) { // System.out.println("getColumnText() "+columnIndex); DescriptionLine line = (DescriptionLine) element; switch (columnIndex) { case 0: return line.getLanguage(); case 1: return line.getLabel(); } return "";//$NON-NLS-1$ } public Image getColumnImage(Object element, int columnIndex) { return null; } }); // Set the column properties descriptionsViewer.setColumnProperties(new String[] { LANGUAGE, LABEL }); // set the Cell Modifier descriptionsViewer.setCellModifier(new ICellModifier() { public boolean canModify(Object element, String property) { // if (INSTANCE_ACCESS.equals(property)) return true; Deactivated return false; } public void modify(Object element, String property, Object value) { // System.out.println("modify() "+element.getClass().getName()+": "+property+": "+value); // DescriptionLine line = // (DescriptionLine)((IStructuredSelection)instancesViewer.getSelection()).getFirstElement(); // deactivated: editing in places is not natural for users } public Object getValue(Object element, String property) { // System.out.println("getValue() "+property); DescriptionLine line = (DescriptionLine) element; if (LANGUAGE.equals(property)) { return line.getLanguage(); } if (LABEL.equals(property)) { return line.getLabel(); } return null; } }); // Listen for changes in the selection of the viewer to display additional parameters descriptionsViewer.addSelectionChangedListener(new ISelectionChangedListener() { public void selectionChanged(SelectionChangedEvent event) { } }); // display for Delete Key events to delete an instance descriptionsViewer.getTable().addKeyListener(new KeyListener() { public void keyPressed(KeyEvent e) { } public void keyReleased(KeyEvent e) { // System.out.println("Table keyReleased() "); if ((e.stateMask == 0) && (e.character == SWT.DEL) && (descriptionsViewer.getSelection() != null)) { DescriptionLine line = (DescriptionLine) ((IStructuredSelection) descriptionsViewer .getSelection()).getFirstElement(); String isoCode = Util.lang2iso.get(line.getLanguage()); LinkedHashMap<String, String> descs = (LinkedHashMap<String, String>) descriptionsViewer .getInput(); descs.remove(isoCode); descriptionsViewer.refresh(); } } }); descriptionsViewer.refresh(); if (wsMenuEntry != null) { idText.setText(wsMenuEntry.getId() == null ? "" : wsMenuEntry.getId());//$NON-NLS-1$ contextText.setText(wsMenuEntry.getContext() == null ? "" : wsMenuEntry.getContext());//$NON-NLS-1$ applicationNameText.setText(wsMenuEntry.getApplication() == null ? "" : wsMenuEntry.getApplication());//$NON-NLS-1$ iconPathText.setFilename(wsMenuEntry.getIcon() == null ? "" : wsMenuEntry.getIcon());//$NON-NLS-1$ descriptionsViewer.setInput(descriptionsMap); } idText.setFocus(); return composite; }
From source file:org.openo.nfvo.emsdriver.collector.TaskThread.java
private void appendLine(LinkedHashMap<String, String> nameAndValue, BufferedOutputStream bos) { StringBuilder lineDatas = new StringBuilder(); for (String key : nameAndValue.keySet()) { lineDatas.append(nameAndValue.get(key)).append("|"); }//from w w w . j a va 2s . co m try { bos.write(lineDatas.toString().getBytes()); bos.write("\n".getBytes()); } catch (IOException e) { log.error("appendLine error " + StringUtil.getStackTrace(e)); } }
From source file:com.github.nmorel.gwtjackson.shared.advanced.jsontype.TypeNamesTester.java
public void testRoundTripMap(ObjectMapperTester<LinkedHashMap<String, Animal>> mapper) { LinkedHashMap<String, Animal> input = new LinkedHashMap<String, Animal>(); input.put("venla", new MaineCoon("Venla", true)); input.put("ama", new Dog("Amadeus", 13)); String json = mapper.write(input); assertEquals("{\"venla\":{\"TypeNamesTester$MaineCoon\":{\"name\":\"Venla\",\"purrs\":true}}," + "" + "\"ama\":{\"doggy\":{\"ageInYears\":13,\"name\":\"Amadeus\"}}}", json); LinkedHashMap<String, Animal> output = mapper.read(json); assertNotNull(output);/*w w w . j a v a 2s . c o m*/ assertEquals(input.size(), output.size()); // for some reason, straight comparison won't work... for (String name : input.keySet()) { Animal in = input.get(name); Animal out = output.get(name); if (!in.equals(out)) { fail("Animal in input was [" + in + "]; output not matching: [" + out + "]"); } } }
From source file:ubic.gemma.datastructure.matrix.ExpressionDataMatrixColumnSort.java
/** * Divide the biomaterials up into chunks based on the experimental factor given, keeping everybody in order. * //from w ww . j a va 2 s . c om * @param ef * @param bms * @return ordered map of fv->bm where fv is of ef, or null if it couldn't be done properly. */ private static LinkedHashMap<FactorValue, List<BioMaterial>> chunkOnFactor(ExperimentalFactor ef, List<BioMaterial> bms) { if (bms == null) { return null; } LinkedHashMap<FactorValue, List<BioMaterial>> chunks = new LinkedHashMap<FactorValue, List<BioMaterial>>(); /* * Get the factor values in the order we have things right now */ for (BioMaterial bm : bms) { for (FactorValue fv : bm.getFactorValues()) { if (!ef.getFactorValues().contains(fv)) { continue; } if (chunks.keySet().contains(fv)) { continue; } chunks.put(fv, new ArrayList<BioMaterial>()); } } /* * What if bm doesn't have a value for the factorvalue. Need a dummy value. */ FactorValue dummy = FactorValue.Factory.newInstance(ef); dummy.setValue(""); dummy.setId(-1L); chunks.put(dummy, new ArrayList<BioMaterial>()); for (BioMaterial bm : bms) { boolean found = false; for (FactorValue fv : bm.getFactorValues()) { if (ef.getFactorValues().contains(fv)) { found = true; assert chunks.containsKey(fv); chunks.get(fv).add(bm); } } if (!found) { if (log.isDebugEnabled()) log.debug(bm + " has no value for factor=" + ef + "; using dummy value"); chunks.get(dummy).add(bm); } } if (chunks.get(dummy).size() == 0) { if (log.isDebugEnabled()) log.debug("removing dummy"); chunks.remove(dummy); } log.debug(chunks.size() + " chunks for " + ef + ", from current chunk of size " + bms.size()); /* * Sanity check */ int total = 0; for (FactorValue fv : chunks.keySet()) { List<BioMaterial> chunk = chunks.get(fv); total += chunk.size(); } assert total == bms.size() : "expected " + bms.size() + ", got " + total; return chunks; }
From source file:ubic.gemma.visualization.ExperimentalDesignVisualizationServiceImpl.java
/** * Get the order that bioassays need to be in for the 'real' data. * //from w w w . j a v a2 s. c o m * @param layout * @return */ private Map<BioAssayValueObject, Integer> getOrdering( LinkedHashMap<BioAssayValueObject, LinkedHashMap<ExperimentalFactor, Double>> layout) { Map<BioAssayValueObject, Integer> ordering = new HashMap<BioAssayValueObject, Integer>(); int i = 0; for (BioAssayValueObject bbb : layout.keySet()) { ordering.put(bbb, i++); } return ordering; }
From source file:com.cwctravel.hudson.plugins.extended_choice_parameter.ExtendedChoiceParameterDefinition.java
public String getMultiLevelDropdownIds() throws Exception { String dropdownIds = new String(); LinkedHashMap<String, LinkedHashSet<String>> choicesByDropdownId = calculateChoicesByDropdownId(); for (String id : choicesByDropdownId.keySet()) { if (dropdownIds.length() > 0) { dropdownIds += ","; }/*from w ww . ja v a2 s . co m*/ dropdownIds += id; } return dropdownIds; /* dropdownIds is of a form like this: return name + " dropdown MultiLevelMultiSelect 0," // next select the source of the genome -- each genome gets a seperate dropdown id:" + name + " dropdown MultiLevelMultiSelect 0 HG18,dropdown MultiLevelMultiSelect 0 ZZ23," // next select the cell type of the source -- each source gets a seperate dropdown id + name + " dropdown MultiLevelMultiSelect 0 HG18 Diffuse large B-cell lymphoma, dropdown MultiLevelMultiSelect 0 HG18 Multiple Myeloma," + name + " dropdown MultiLevelMultiSelect 0 ZZ23 Neuroblastoma," // next select the name from the cell type -- each cell type gets a seperate dropdown id + name + " dropdown MultiLevelMultiSelect 0 HG18 Diffuse large B-cell lymphoma LY1," + name + " dropdown MultiLevelMultiSelect 0 HG18 Multiple Myeloma MM1S," + name + " dropdown MultiLevelMultiSelect 0 ZZ23 Neuroblastoma BE2C," + name + " dropdown MultiLevelMultiSelect 0 ZZ23 Neuroblastoma SKNAS";*/ }
From source file:com.twinsoft.convertigo.engine.migration.Migration7_0_0.java
public static void migrate(final String projectName) { try {//w ww. ja va 2 s. c o m Map<String, Reference> referenceMap = new HashMap<String, Reference>(); XmlSchema projectSchema = null; Project project = Engine.theApp.databaseObjectsManager.getOriginalProjectByName(projectName, false); // Copy all xsd files to project's xsd directory File destDir = new File(project.getXsdDirPath()); copyXsdOfProject(projectName, destDir); String projectWsdlFilePath = Engine.PROJECTS_PATH + "/" + projectName + "/" + projectName + ".wsdl"; File wsdlFile = new File(projectWsdlFilePath); String projectXsdFilePath = Engine.PROJECTS_PATH + "/" + projectName + "/" + projectName + ".xsd"; File xsdFile = new File(projectXsdFilePath); if (xsdFile.exists()) { // Load project schema from old XSD file XmlSchemaCollection collection = new XmlSchemaCollection(); collection.setSchemaResolver(new DefaultURIResolver() { public InputSource resolveEntity(String targetNamespace, String schemaLocation, String baseUri) { // Case of a c8o project location if (schemaLocation.startsWith("../") && schemaLocation.endsWith(".xsd")) { try { String targetProjectName = schemaLocation.substring(3, schemaLocation.indexOf("/", 3)); File pDir = new File(Engine.PROJECTS_PATH + "/" + targetProjectName); if (pDir.exists()) { File pFile = new File(Engine.PROJECTS_PATH + schemaLocation.substring(2)); // Case c8o project is already migrated if (!pFile.exists()) { Document doc = Engine.theApp.schemaManager .getSchemaForProject(targetProjectName).getSchemaDocument(); DOMSource source = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory.newInstance().newTransformer().transform(source, result); StringReader reader = new StringReader(writer.toString()); return new InputSource(reader); } } return null; } catch (Exception e) { Engine.logDatabaseObjectManager .warn("[Migration 7.0.0] Unable to find schema location \"" + schemaLocation + "\"", e); return null; } } else if (schemaLocation.indexOf("://") == -1 && schemaLocation.endsWith(".xsd")) { return super.resolveEntity(targetNamespace, schemaLocation, Engine.PROJECTS_PATH + "/" + projectName); } return super.resolveEntity(targetNamespace, schemaLocation, baseUri); } }); projectSchema = SchemaUtils.loadSchema(new File(projectXsdFilePath), collection); ConvertigoError.updateXmlSchemaObjects(projectSchema); SchemaMeta.setCollection(projectSchema, collection); for (Connector connector : project.getConnectorsList()) { for (Transaction transaction : connector.getTransactionsList()) { try { // Migrate transaction in case of a Web Service consumption project if (transaction instanceof XmlHttpTransaction) { XmlHttpTransaction xmlHttpTransaction = (XmlHttpTransaction) transaction; String reqn = xmlHttpTransaction.getResponseElementQName(); if (!reqn.equals("")) { boolean useRef = reqn.indexOf(";") == -1; // Doc/Literal case if (useRef) { try { String[] qn = reqn.split(":"); QName refName = new QName( projectSchema.getNamespaceContext().getNamespaceURI(qn[0]), qn[1]); xmlHttpTransaction.setXmlElementRefAffectation(new XmlQName(refName)); } catch (Exception e) { } } // RPC case else { int index, index2; try { index = reqn.indexOf(";"); String opName = reqn.substring(0, index); if ((index2 = reqn.indexOf(";", index + 1)) != -1) { String eltName = reqn.substring(index + 1, index2); String eltType = reqn.substring(index2 + 1); String[] qn = eltType.split(":"); QName typeName = new QName( projectSchema.getNamespaceContext().getNamespaceURI(qn[0]), qn[1]); String responseElementQName = opName + ";" + eltName + ";" + "{" + typeName.getNamespaceURI() + "}" + typeName.getLocalPart(); xmlHttpTransaction.setResponseElementQName(responseElementQName); } } catch (Exception e) { } } } } // Retrieve required XmlSchemaObjects for transaction QName requestQName = new QName(project.getTargetNamespace(), transaction.getXsdRequestElementName()); QName responseQName = new QName(project.getTargetNamespace(), transaction.getXsdResponseElementName()); LinkedHashMap<QName, XmlSchemaObject> map = new LinkedHashMap<QName, XmlSchemaObject>(); XmlSchemaWalker dw = XmlSchemaWalker.newDependencyWalker(map, true, false); dw.walkByElementRef(projectSchema, requestQName); dw.walkByElementRef(projectSchema, responseQName); // Create transaction schema String targetNamespace = projectSchema.getTargetNamespace(); String prefix = projectSchema.getNamespaceContext().getPrefix(targetNamespace); XmlSchema transactionSchema = SchemaUtils.createSchema(prefix, targetNamespace, XsdForm.unqualified.name(), XsdForm.unqualified.name()); // Add required prefix declarations List<String> nsList = new LinkedList<String>(); for (QName qname : map.keySet()) { String nsURI = qname.getNamespaceURI(); if (!nsURI.equals(Constants.URI_2001_SCHEMA_XSD)) { if (!nsList.contains(nsURI)) { nsList.add(nsURI); } } String nsPrefix = qname.getPrefix(); if (!nsURI.equals(targetNamespace)) { NamespaceMap nsMap = SchemaUtils.getNamespaceMap(transactionSchema); if (nsMap.getNamespaceURI(nsPrefix) == null) { nsMap.add(nsPrefix, nsURI); transactionSchema.setNamespaceContext(nsMap); } } } // Add required imports for (String namespaceURI : nsList) { XmlSchemaObjectCollection includes = projectSchema.getIncludes(); for (int i = 0; i < includes.getCount(); i++) { XmlSchemaObject xmlSchemaObject = includes.getItem(i); if (xmlSchemaObject instanceof XmlSchemaImport) { if (((XmlSchemaImport) xmlSchemaObject).getNamespace() .equals(namespaceURI)) { // do not allow import with same ns ! if (namespaceURI.equals(project.getTargetNamespace())) continue; String location = ((XmlSchemaImport) xmlSchemaObject) .getSchemaLocation(); // This is a convertigo project reference if (location.startsWith("../")) { // Copy all xsd files to xsd directory String targetProjectName = location.substring(3, location.indexOf("/", 3)); copyXsdOfProject(targetProjectName, destDir); } // Add reference addReferenceToMap(referenceMap, namespaceURI, location); // Add import addImport(transactionSchema, namespaceURI, location); } } } } QName responseTypeQName = new QName(project.getTargetNamespace(), transaction.getXsdResponseTypeName()); // Add required schema objects for (QName qname : map.keySet()) { if (qname.getNamespaceURI().equals(targetNamespace)) { XmlSchemaObject ob = map.get(qname); if (qname.getLocalPart().startsWith("ConvertigoError")) continue; transactionSchema.getItems().add(ob); // Add missing response error element and attributes if (qname.equals(responseTypeQName)) { Transaction.addSchemaResponseObjects(transactionSchema, (XmlSchemaComplexType) ob); } } } // Add missing ResponseType (with document) if (map.containsKey(responseTypeQName)) { Transaction.addSchemaResponseType(transactionSchema, transaction); } // Add everything if (map.isEmpty()) { Transaction.addSchemaObjects(transactionSchema, transaction); } // Add c8o error objects (for internal xsd edition only) ConvertigoError.updateXmlSchemaObjects(transactionSchema); // Save schema to file String transactionXsdFilePath = transaction.getSchemaFilePath(); new File(transaction.getSchemaFileDirPath()).mkdirs(); SchemaUtils.saveSchema(transactionXsdFilePath, transactionSchema); } catch (Exception e) { Engine.logDatabaseObjectManager .error("[Migration 7.0.0] An error occured while migrating transaction \"" + transaction.getName() + "\"", e); } if (transaction instanceof TransactionWithVariables) { TransactionWithVariables transactionVars = (TransactionWithVariables) transaction; handleRequestableVariable(transactionVars.getVariablesList()); // Change SQLQuery variables : i.e. {id} --> {{id}} if (transaction instanceof SqlTransaction) { String sqlQuery = ((SqlTransaction) transaction).getSqlQuery(); sqlQuery = sqlQuery.replaceAll("\\{([a-zA-Z0-9_]+)\\}", "{{$1}}"); ((SqlTransaction) transaction).setSqlQuery(sqlQuery); } } } } } else {// Should only happen for projects which version <= 4.6.0 XmlSchemaCollection collection = new XmlSchemaCollection(); String prefix = project.getName() + "_ns"; projectSchema = SchemaUtils.createSchema(prefix, project.getNamespaceUri(), XsdForm.unqualified.name(), XsdForm.unqualified.name()); ConvertigoError.addXmlSchemaObjects(projectSchema); SchemaMeta.setCollection(projectSchema, collection); for (Connector connector : project.getConnectorsList()) { for (Transaction transaction : connector.getTransactionsList()) { if (transaction instanceof TransactionWithVariables) { TransactionWithVariables transactionVars = (TransactionWithVariables) transaction; handleRequestableVariable(transactionVars.getVariablesList()); } } } } // Handle sequence objects for (Sequence sequence : project.getSequencesList()) { handleSteps(projectSchema, referenceMap, sequence.getSteps()); handleRequestableVariable(sequence.getVariablesList()); } // Add all references to project if (!referenceMap.isEmpty()) { for (Reference reference : referenceMap.values()) project.add(reference); } // Delete XSD file if (xsdFile.exists()) xsdFile.delete(); // Delete WSDL file if (wsdlFile.exists()) wsdlFile.delete(); } catch (Exception e) { Engine.logDatabaseObjectManager .error("[Migration 7.0.0] An error occured while migrating project \"" + projectName + "\"", e); } }
From source file:ubic.gemma.datastructure.matrix.ExpressionDataMatrixColumnSort.java
/** * Sort biomaterials according to a list of ordered factors * //from ww w . j av a 2s . co m * @param start biomaterials to sort * @param factorsToUse sorted list of factors to define sort order for biomaterials, cannot be null * @return */ public static List<BioMaterialValueObject> orderBiomaterialsBySortedFactorsVO( List<BioMaterialValueObject> start, List<ExperimentalFactor> factors) { if (start.size() == 1) { return start; } if (start.size() == 0) { throw new IllegalArgumentException("Must provide some biomaterials"); } if (factors == null) { throw new IllegalArgumentException("Must provide sorted factors, or at least an empty list"); } if (factors.isEmpty()) { // we're done. return start; } ExperimentalFactor simplest = factors.get(0); if (simplest == null) { // we're done. return start; } /* * Order this chunk by the selected factor */ Map<FactorValueValueObject, List<BioMaterialValueObject>> fv2bms = buildFv2BmVOMap(start); List<BioMaterialValueObject> ordered = orderByFactorVo(simplest, fv2bms, start, new HashMap<ExperimentalFactor, Collection<BioMaterialValueObject>>()); LinkedList<ExperimentalFactor> factorsStillToDo = new LinkedList<ExperimentalFactor>(); factorsStillToDo.addAll(factors); factorsStillToDo.remove(simplest); if (factorsStillToDo.size() == 0) { /* * No more ordering is necessary. */ return ordered; } log.debug("Factors: " + factors.size()); /* * Recurse in and order each chunk. First split it up, but retaining the order we just made. */ LinkedHashMap<FactorValueValueObject, List<BioMaterialValueObject>> chunks = chunkOnFactorVO(simplest, ordered); if (chunks == null) { // this means we should bail, gracefully. return start; } /* * Process each chunk. */ List<BioMaterialValueObject> result = new ArrayList<BioMaterialValueObject>(); for (FactorValueValueObject fv : chunks.keySet()) { List<BioMaterialValueObject> chunk = chunks.get(fv); if (chunk.size() < 2) { result.addAll(chunk); } else { List<BioMaterialValueObject> orderedChunk = orderBiomaterialsBySortedFactorsVO(chunk, factorsStillToDo); result.addAll(orderedChunk); } } return result; }