List of usage examples for java.util Hashtable containsKey
public synchronized boolean containsKey(Object key)
From source file:es.pode.catalogadorWeb.presentacion.categoriasAvanzado.clasificacion.detalleClasificacion.DetalleClasificacionControllerImpl.java
private void cambioFormulario(HttpServletRequest request, int longitudTextosDesc, int[] longitudTextosPCla, int longitudPalabrasClave, int longitudRutasTax, int[] longiTextosFuente, int[] longiTaxones, Object formRequestSession) throws Exception { descripcion = new DescripcionVO(); palabrasClave = new PalabraClaveVO[longitudPalabrasClave]; rutasTaxonomicas = new RutaTaxonomicaVO[longitudRutasTax]; String[] textoDescripcion = new String[longitudTextosDesc]; String[] idiomaDescripcion = new String[longitudTextosDesc]; ArrayList[] textoPalabrasClave = new ArrayList[longitudPalabrasClave]; ArrayList[] idiomaPalabrasClave = new ArrayList[longitudPalabrasClave]; ArrayList[] textoRutasTaxFuente = new ArrayList[longitudRutasTax]; ArrayList textoRutasTaxTaxones = new ArrayList(); Hashtable hDatos = new Hashtable(); for (Enumeration names = request.getParameterNames(); names.hasMoreElements();) { String name = String.valueOf(names.nextElement()); if (name.startsWith("Des")) { //Descripciones if (name.startsWith("DesTex")) { int i = Integer.parseInt(name.substring(6, name.length())); textoDescripcion[i] = request.getParameter(name); }/*from ww w . j ava 2 s . co m*/ if (name.startsWith("DesIdio")) { int i = Integer.parseInt(name.substring(7, name.length())); idiomaDescripcion[i] = request.getParameter(name); } } else if (name.startsWith("Pcla")) {//Palabras Clave String[] namePartido = name.split("_"); int i = Integer.parseInt(namePartido[0].substring(4, namePartido[0].length())); if (namePartido[1].startsWith("Tex")) { int j = Integer.parseInt(namePartido[1].substring(3, namePartido[1].length())); ArrayList lPCla = textoPalabrasClave[i]; if (lPCla == null) { lPCla = new ArrayList(); for (int k = 0; k < longitudTextosPCla[i]; k++) lPCla.add(""); } lPCla.set(j, request.getParameter(name)); textoPalabrasClave[i] = lPCla; } else {//Idio int j = Integer.parseInt(namePartido[1].substring(4, namePartido[1].length())); ArrayList lPCla = idiomaPalabrasClave[i]; if (lPCla == null) { lPCla = new ArrayList(); for (int k = 0; k < longitudTextosPCla[i]; k++) lPCla.add(""); } lPCla.set(j, request.getParameter(name)); idiomaPalabrasClave[i] = lPCla; } } else if (name.startsWith("rutaTax")) { // rutaTax${i }_source, rutaTax${i}_taxon${t}_Id${u }//rutaTax${i}_taxon${t}_EntryTex${u} //rutaTax${i}_taxon${t}_EntryIdio${u} hDatos.put(name, request.getParameter(name)); } else if (name.startsWith("razon")) { razon = request.getParameter(name); } } if (hDatos.size() > 0) { ArrayList arrRutaTax = new ArrayList(); for (int i = 0; i < longitudRutasTax; i++) { RutaTaxonomicaVO rutavo = new RutaTaxonomicaVO(); //rellenams fuentes // String source= hDatos.get("rutaTax" + i + "_source").toString(); String source = hDatos.get("rutaTax" + i + "_source") != null ? hDatos.get("rutaTax" + i + "_source").toString() : ""; // String idio= hDatos.get("rutaTax" + i + "_idio").toString(); String idio = hDatos.get("rutaTax" + i + "_idio") != null ? hDatos.get("rutaTax" + i + "_idio").toString() : ""; LangStringVO textFuente = new LangStringVO(); textFuente.setTexto(source); textFuente.setIdioma(idio); FuenteVO fuente = new FuenteVO(); LangStringVO[] textosFuentes = new LangStringVO[1]; textosFuentes[0] = textFuente; fuente.setTextos(textosFuentes);//metidas las fuentes de una RutaTaxonomica //rutasTaxonomicas[i].setFuente(fuente); //ahora metemos los taxones para esa fuente ArrayList taxones = new ArrayList(); for (int j = 0; j < longiTaxones[i]; j++) { ArrayList taxonij = new ArrayList(); TaxonVO tax = new TaxonVO(); EntryVO entry = new EntryVO(); ArrayList lans = new ArrayList(); String textoId = ""; if (hDatos.get("rutaTax" + i + "_taxon" + j + "_Id" + 0) != null) textoId = hDatos.get("rutaTax" + i + "_taxon" + j + "_Id" + 0).toString(); IdVO id = new IdVO(); id.setTexto(textoId); for (int u = 0; u < hDatos.size(); u++) { LangStringVO lanvo = new LangStringVO(); if (hDatos.containsKey("rutaTax" + i + "_taxon" + j + "_EntryTex" + u)) { String textoTax = ""; if (hDatos.get("rutaTax" + i + "_taxon" + j + "_EntryTex" + u) != null) textoTax = hDatos.get("rutaTax" + i + "_taxon" + j + "_EntryTex" + u).toString(); lanvo.setTexto(textoTax); String idioTax = ""; if (hDatos.get("rutaTax" + i + "_taxon" + j + "_EntryIdio" + u) != null) idioTax = hDatos.get("rutaTax" + i + "_taxon" + j + "_EntryIdio" + u).toString(); lanvo.setIdioma(idioTax); lans.add(lanvo); //array d langs para entryvo } } //***************** if (lans.size() == 0) { LangStringVO lanvo = new LangStringVO(); lanvo.setIdioma(""); lanvo.setTexto(""); lans.add(lanvo); } //***************** LangStringVO[] textosEnt = (LangStringVO[]) lans.toArray(new LangStringVO[lans.size()]); entry.setTextos(textosEnt); tax.setId(id); tax.setEntry(entry); //un Taxon taxones.add(tax); } TaxonVO[] rutaTaxones = (TaxonVO[]) taxones.toArray(new TaxonVO[taxones.size()]); rutavo.setFuente(fuente); rutavo.setTaxones(rutaTaxones);//tenemos una RutaTaxonomica arrRutaTax.add(rutavo); } rutasTaxonomicas = (RutaTaxonomicaVO[]) arrRutaTax.toArray(new RutaTaxonomicaVO[arrRutaTax.size()]); RutaTaxonomicaVO[] rutasTaxonomicas2 = rutaLimpia(rutasTaxonomicas); rutasTaxonomicas = new RutaTaxonomicaVO[rutasTaxonomicas2.length]; rutasTaxonomicas = rutasTaxonomicas2; } //descripcion DescripcionVO descVO = new DescripcionVO(); LangStringVO[] aLangDescripciones = new LangStringVO[textoDescripcion.length]; for (int i = 0; i < textoDescripcion.length; i++) { LangStringVO langDescripciones = new LangStringVO(); langDescripciones.setTexto(textoDescripcion[i]); langDescripciones.setIdioma(idiomaDescripcion[i]); aLangDescripciones[i] = langDescripciones; } descVO.setTextos(aLangDescripciones); descripcion = descVO; //palabras clave for (int i = 0; i < textoPalabrasClave.length; i++) { PalabraClaveVO pClaVO = new PalabraClaveVO(); if (textoPalabrasClave[i] != null) { LangStringVO[] aLangPCla = new LangStringVO[textoPalabrasClave[i].size()]; for (int j = 0; j < textoPalabrasClave[i].size(); j++) { LangStringVO langPCla = new LangStringVO(); langPCla.setTexto(textoPalabrasClave[i].get(j).toString()); langPCla.setIdioma(idiomaPalabrasClave[i].get(j).toString()); aLangPCla[j] = langPCla; } pClaVO.setTextos(aLangPCla); } else { LangStringVO[] aLangString = new LangStringVO[1]; LangStringVO langString = new LangStringVO(); langString.setIdioma(""); langString.setTexto(""); aLangString[0] = langString; pClaVO.setTextos(aLangString); } palabrasClave[i] = pClaVO; } }
From source file:imapi.IMAPIClass.java
public int performComparison(Hashtable<Float, Vector<ResultSourceTargetPair>> resultInstances) { //Utilities//from w w w. j ava2 s.c o m DataRetrievalOperations retrieveData = new DataRetrievalOperations(this); BaseComparisonClass compClass = new BaseComparisonClass(this); //Internal structures used SourceDataHolder inputSourceInfo = new SourceDataHolder(); Hashtable<SourceTargetPair, SequenceSimilarityResultVector> pairSimilaritiesInSequences = new Hashtable<SourceTargetPair, SequenceSimilarityResultVector>(); //If Comaprison with online database is selected check if it is avaliable if (this.userConfig.getComparisonMode() != ApiConstants.TargetSourceChoice.FILE_COMPARISON) { OnlineDatabase db = this.conf.getOnlineDb(this.userConfig.getComparisonMode()); if (db == null) { this.setErrorMessage(ApiConstants.IMAPIFailCode, "Not supported Database"); return ApiConstants.IMAPIFailCode; } OnlineDatabaseActions qSource = new OnlineDatabaseActions(this, db); int ret = qSource.checkIfDBisAvailable(); if (ret != ApiConstants.IMAPISuccessCode) { return ret; } } //retrieve all needed namespaces from internet Hashtable<String, Model> allRetrievedModels = retrieveData.retrieveAllDeclaredNamespacesModels(); //read Source Files info Vector<CidocCrmCompatibleFile> inputFiles = this.userConfig.getSourceInputFiles(); for (int inputFileIndex = 0; inputFileIndex < inputFiles.size(); inputFileIndex++) { CidocCrmCompatibleFile inputFile = inputFiles.get(inputFileIndex); try { int ret = retrieveData.retrieveDataFrom_SourceFile(inputFile, allRetrievedModels, inputSourceInfo); if (ret != ApiConstants.IMAPISuccessCode) { return ret; } } catch (FileNotFoundException ex) { Utilities.handleException(ex); return ApiConstants.IMAPIFailCode; } if (inputFileIndex < (inputFiles.size() - 1)) ; System.out.println("======================================="); } int totalNumberOfSourceInstanceValuesFound = 0; Enumeration<String> fileEnum = inputSourceInfo.keys(); while (fileEnum.hasMoreElements()) { String fpath = fileEnum.nextElement(); totalNumberOfSourceInstanceValuesFound += inputSourceInfo.get(fpath).keySet().size(); } //print what data was found in source files System.out.println("\n\n============================================================"); System.out.println("============================================================"); System.out.println("============================================================"); System.out.println("Found " + totalNumberOfSourceInstanceValuesFound + " instances in all \"\"SOURCE\"\" input files."); printSourceInfo(inputSourceInfo); /* if(IMAPIClass.DEBUG){ if(inputSourceInfo!=null){ System.out.println("Found: " + inputSourceInfo.size() +" instances."); return ApiConstants.IMAPISuccessCode; } } */ //make an analysis if quick method can be followed Utilities u = new Utilities(this); Vector<Boolean> canQuickFilteringMethodBeFollowedForeachSequence = new Vector<Boolean>(); u.canAllSequencesFollowFastApproach(this.userConfig.getUserQueriesCopy(), inputSourceInfo, canQuickFilteringMethodBeFollowedForeachSequence); //Read Info from Target Files or Online Database System.out.println("\n======================================="); System.out.println("======================================="); System.out.println("=======================================\n\n"); ApiConstants.TargetSourceChoice comparisonChoice = this.userConfig.getComparisonMode(); System.out.println("Starting queries on TARGET source: " + comparisonChoice.toString() + "\n\n"); boolean targetDataCollectedCorrectly = false; switch (comparisonChoice) { case FILE_COMPARISON: { Vector<CidocCrmCompatibleFile> targetFiles = this.userConfig.getTargetInputFiles(); for (int targetFileIndex = 0; targetFileIndex < targetFiles.size(); targetFileIndex++) { CidocCrmCompatibleFile targetFile = targetFiles.get(targetFileIndex); try { int ret = retrieveData.retrieveDataFrom_TargetFileAndCollectSimilarities(targetFile, allRetrievedModels, inputSourceInfo, canQuickFilteringMethodBeFollowedForeachSequence, pairSimilaritiesInSequences); if (ret == ApiConstants.IMAPISuccessCode) { targetDataCollectedCorrectly = true; } else { return ret; } } catch (FileNotFoundException ex) { Utilities.handleException(ex); return ApiConstants.IMAPIFailCode; } } break; } // a target online db is selected default: { OnlineDatabase db = this.conf.getOnlineDb(comparisonChoice); if (db == null) { this.setErrorMessage(ApiConstants.IMAPIFailCode, "TargetSourceChoice not set correctly check user configuration xml file again."); return ApiConstants.IMAPIFailCode; } else { /* if(db.getDbType().equals("owlim")){ int ret = retrieveData.retrieveDataFrom_OWLIM_DB(db,allRetrievedModels, inputSourceInfo, pairSimilaritiesInSequences); if(ret==ApiConstants.IMAPISuccessCode){ targetDataCollectedCorrectly = true; } } else{ */ int ret = retrieveData.retrieveDataFrom_OnlineDatabaseAndCollectSimilarities(db, allRetrievedModels, inputSourceInfo, canQuickFilteringMethodBeFollowedForeachSequence, pairSimilaritiesInSequences); if (ret == ApiConstants.IMAPISuccessCode) { targetDataCollectedCorrectly = true; } //} } break; } } inputSourceInfo = null; //start comparing //find out the denominator in order to normalize results double similarityDenominator = 0; int maxNumberOfQueriesIndex = this.userConfig.getNumberOfSequences(); for (int i = 0; i < maxNumberOfQueriesIndex; i++) { similarityDenominator += this.userConfig.getWeightAtUserQueryIndex(i); } //PRINT OUT //System.out.println("Total Number of results with similarity > 0:\r\n################# " + allSimilaritiesHash.keySet().size() + " ##################"); System.out.println("\n\n============================================================"); System.out.println("============================================================"); System.out.println("============================================================"); //for each sequence save the parameter name - type compared values and the similarity Enumeration<SourceTargetPair> similarityIterator = pairSimilaritiesInSequences.keys(); while (similarityIterator.hasMoreElements()) { SourceTargetPair pair = similarityIterator.nextElement(); SequenceSimilarityResultVector similarities = pairSimilaritiesInSequences.get(pair); //Vector<SequenceSimilarityResult> similarityResults = new Vector<SequenceSimilarityResult>(); int calculatedSimilarity = 0; if (pair.getSourceInstance().getInstanceUri().equals(pair.getTargetInstance().getInstanceUri())) { calculatedSimilarity = 100; } else { calculatedSimilarity = compClass.calculateFinalSimilarity(similarities, similarityDenominator); } if (calculatedSimilarity >= (userConfig.getResultsThreshold() * 100)) { float floatVal = (float) ((float) calculatedSimilarity / 100f); SequenceSimilarityResultVector tripVec = pairSimilaritiesInSequences.get(pair); if (resultInstances.containsKey(floatVal)) { ResultSourceTargetPair newVal = new ResultSourceTargetPair(pair, tripVec); resultInstances.get(floatVal).add(newVal); } else { Vector<ResultSourceTargetPair> newVal = new Vector<ResultSourceTargetPair>(); newVal.add(new ResultSourceTargetPair(pair, tripVec)); resultInstances.put(floatVal, newVal); } } } if (targetDataCollectedCorrectly == false) { System.out.println("Note that while collected data from target Error Occurred"); } return ApiConstants.IMAPISuccessCode; }
From source file:base.BasePlayer.FileRead.java
public ArrayList<Gene> getExons(String chrom) { ArrayList<Gene> transcriptsTemp = new ArrayList<Gene>(); try {//from w ww . java2s . co m if (Main.genomehash.size() == 0 || Main.genomehash.get(Main.defaultGenome).size() == 0) { return new ArrayList<Gene>(); } if (ChromDraw.exonReader != null) { ChromDraw.exonReader.close(); } ChromDraw.exonReader = new TabixReader( Main.genomehash.get(Main.defaultGenome).get(Main.annotation).getCanonicalPath()); if (chrom == null) { return null; } TabixReader.Iterator exonIterator = null; try { if (!ChromDraw.exonReader.getChromosomes().contains(chrom)) { String[] gene = { Main.chromosomeDropdown.getSelectedItem().toString(), "1", "" + Main.drawCanvas.splits.get(0).chromEnd, Main.chromosomeDropdown.getSelectedItem().toString(), "1", "+", "-", "-", "-", "-", "-", "1", "1", "1", "" + Main.drawCanvas.splits.get(0).chromEnd, "-1,", "-" }; Gene addGene = new Gene(gene); Transcript addtrans = null; try { addtrans = new Transcript(gene); } catch (Exception e) { e.printStackTrace(); } addGene.addTranscript(addtrans); addGene.setLongest(addtrans); addtrans.setGene(addGene); transcriptsTemp.add(addGene); return transcriptsTemp; //return new ArrayList<Gene>(); } else { exonIterator = ChromDraw.exonReader.query(chrom); } } catch (Exception e) { try { if (chrom.matches("\\w+")) { exonIterator = ChromDraw.exonReader.query("M"); } } catch (Exception ex) { System.out.println(chrom); e.printStackTrace(); } } String s; String[] exonSplit; Transcript addtrans = null; Hashtable<String, Gene> genes = new Hashtable<String, Gene>(); Gene setGene; while (exonIterator != null && (s = exonIterator.next()) != null) { exonSplit = s.split("\t"); if (exonSplit[0].equals("23")) { exonSplit[0] = "X"; } else if (exonSplit[0].equals("24")) { exonSplit[0] = "Y"; } else if (exonSplit[0].equals("25")) { exonSplit[0] = "MT"; } addtrans = new Transcript(exonSplit); if (!genes.containsKey(exonSplit[6])) { Gene addgene = new Gene(exonSplit); genes.put(exonSplit[6], addgene); addgene.addTranscript(addtrans); addgene.setLongest(addtrans); addtrans.setGene(addgene); transcriptsTemp.add(addgene); } else { setGene = genes.get(exonSplit[6]); setGene.addTranscript(addtrans); addtrans.setGene(setGene); if (addtrans.getLength() > setGene.getLongest().getLength()) { setGene.setLongest(addtrans); } } } genes.clear(); ChromDraw.exonReader.close(); } catch (Exception e) { ErrorLog.addError(e.getStackTrace()); e.printStackTrace(); } return transcriptsTemp; }
From source file:org.LexGrid.LexBIG.Impl.dataAccess.SQLImplementedMethods.java
public static Entity buildCodedEntry(String internalCodingSchemeName, String internalVersionString, String code, String namespace, LocalNameList restrictToProperties, PropertyType[] restrictToPropertyTypes) throws UnexpectedInternalError, MissingResourceException { try {//from www . j a v a 2 s . c o m Entity concept = new Entity(); concept.setEntityCode(code); SQLInterface si = ResourceManager.instance().getSQLInterface(internalCodingSchemeName, internalVersionString); //if the namespace is null (and its 2009 model), set it to the default (which is //equal to the codingSchemeName. //This shouldn't ever happen -- all classes that call this method should provide //a namespace. if (si.supports2009Model() && StringUtils.isBlank(namespace)) { namespace = internalCodingSchemeName; } ArrayList<Definition> definitions = new ArrayList<Definition>(); ArrayList<Presentation> presentations = new ArrayList<Presentation>(); ArrayList<Property> properties = new ArrayList<Property>(); ArrayList<Comment> comments = new ArrayList<Comment>(); ArrayList<PropertyLink> links = new ArrayList<PropertyLink>(); PreparedStatement getEntityCode = null; PreparedStatement getEntityType = null; PreparedStatement getEntityProperties = null; PreparedStatement getPropertyLinks = null; try { StringBuffer buildEntity = new StringBuffer(); buildEntity .append("Select * " + " from " + si.getTableName(SQLTableConstants.ENTITY) + " {AS} t1 "); if (si.supports2009Model()) { buildEntity.append("left join " + si.getTableName(SQLTableConstants.ENTRY_STATE) + " {AS} t2 " + "on t1." + SQLTableConstants.TBLCOL_ENTRYSTATEID + " = t2." + SQLTableConstants.TBLCOL_ENTRYSTATEID); } buildEntity.append(" where " + si.getSQLTableConstants().codingSchemeNameOrId + " = ? AND " + si.getSQLTableConstants().entityCodeOrId + " = ?"); if (si.supports2009Model()) { buildEntity.append(" AND " + SQLTableConstants.TBLCOL_ENTITYCODENAMESPACE + " = ?"); } getEntityCode = si.modifyAndCheckOutPreparedStatement(buildEntity.toString()); getEntityCode.setString(1, internalCodingSchemeName); getEntityCode.setString(2, code); if (si.supports2009Model()) { getEntityCode.setString(3, namespace); } ResultSet results = getEntityCode.executeQuery(); // one and only one result if (results.next()) { concept.setIsDefined( DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISDEFINED)); concept.setIsAnonymous( DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISANONYMOUS)); concept.setIsActive( DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISACTIVE)); if (!si.supports2009Model()) { concept.setStatus(results.getString(SQLTableConstants.TBLCOL_CONCEPTSTATUS)); } else { concept.setEntityCodeNamespace(namespace); } EntityDescription ed = new EntityDescription(); ed.setContent(results.getString(SQLTableConstants.TBLCOL_ENTITYDESCRIPTION)); concept.setEntityDescription(ed); if (si.supports2009Model()) { String owner = results.getString(SQLTableConstants.TBLCOL_OWNER); String status = results.getString(SQLTableConstants.TBLCOL_STATUS); Timestamp effectiveDate = results.getTimestamp(SQLTableConstants.TBLCOL_EFFECTIVEDATE); Timestamp expirationDate = results.getTimestamp(SQLTableConstants.TBLCOL_EXPIRATIONDATE); String revisionId = results.getString(SQLTableConstants.TBLCOL_REVISIONID); String prevRevisionId = results.getString(SQLTableConstants.TBLCOL_PREVREVISIONID); String changeType = results.getString(SQLTableConstants.TBLCOL_CHANGETYPE); String relativeOrder = results.getString(SQLTableConstants.TBLCOL_RELATIVEORDER); EntryState es = new EntryState(); if (!StringUtils.isBlank(changeType)) { es.setChangeType(org.LexGrid.versions.types.ChangeType.valueOf(changeType)); } es.setContainingRevision(revisionId); es.setPrevRevision(prevRevisionId); es.setRelativeOrder(computeRelativeOrder(relativeOrder)); concept.setEntryState(es); if (owner != null) { concept.setOwner(owner); } concept.setStatus(status); concept.setEffectiveDate(effectiveDate); concept.setExpirationDate(expirationDate); } } results.close(); si.checkInPreparedStatement(getEntityCode); if (si.supports2009Model()) { getEntityType = si.checkOutPreparedStatement( "Select * " + " from " + si.getTableName(SQLTableConstants.ENTITY_TYPE) + " where " + si.getSQLTableConstants().codingSchemeNameOrId + " = ? AND " + si.getSQLTableConstants().entityCodeOrId + " = ? AND " + SQLTableConstants.TBLCOL_ENTITYCODENAMESPACE + " = ?"); getEntityType.setString(1, internalCodingSchemeName); getEntityType.setString(2, code); getEntityType.setString(3, namespace); results = getEntityType.executeQuery(); while (results.next()) { concept.addEntityType(results.getString(SQLTableConstants.TBLCOL_ENTITYTYPE)); } results.close(); si.checkInPreparedStatement(getEntityType); } else { concept.addEntityType(SQLTableConstants.ENTITYTYPE_CONCEPT); } // populate the property links String addWhereSegment = (!si.supports2009Model() ? (si.getSQLTableConstants().entityType + " = '" + SQLTableConstants.ENTITYTYPE_CONCEPT + "' and ") : ""); getPropertyLinks = si .checkOutPreparedStatement("Select " + SQLTableConstants.TBLCOL_SOURCEPROPERTYID + ", " + SQLTableConstants.TBLCOL_LINK + ", " + SQLTableConstants.TBLCOL_TARGETPROPERTYID + " from " + si.getTableName(SQLTableConstants.ENTITY_PROPERTY_LINKS) + " where " + addWhereSegment + si.getSQLTableConstants().entityCodeOrEntityId + " = ? and " + si.getSQLTableConstants().codingSchemeNameOrId + " = ?"); getPropertyLinks.setString(1, code); getPropertyLinks.setString(2, internalCodingSchemeName); results = getPropertyLinks.executeQuery(); while (results.next()) { String sourcePropertyId = results.getString(SQLTableConstants.TBLCOL_SOURCEPROPERTYID); String link = results.getString(SQLTableConstants.TBLCOL_LINK); String targetPropertyId = results.getString(SQLTableConstants.TBLCOL_TARGETPROPERTYID); PropertyLink pl = new PropertyLink(); pl.setPropertyLink(link); pl.setSourceProperty(sourcePropertyId); pl.setTargetProperty(targetPropertyId); links.add(pl); } results.close(); si.checkInPreparedStatement(getPropertyLinks); // codedEntry.setModVersion(null); StringBuffer propertyQuery = new StringBuffer(); // I'm constructing a left join query to get the property // results I need from 3 (or 2 in 1.5 table version) different // tables at once, rather than doing a query on each. propertyQuery.append("SELECT a." + SQLTableConstants.TBLCOL_PROPERTYID + ", a." + SQLTableConstants.TBLCOL_PROPERTYNAME + ", a." + SQLTableConstants.TBLCOL_LANGUAGE + ", a." + SQLTableConstants.TBLCOL_FORMAT + ", a." + SQLTableConstants.TBLCOL_ISPREFERRED + ", a." + SQLTableConstants.TBLCOL_DEGREEOFFIDELITY + ", a." + SQLTableConstants.TBLCOL_MATCHIFNOCONTEXT + ", a." + SQLTableConstants.TBLCOL_REPRESENTATIONALFORM + ", a." + SQLTableConstants.TBLCOL_PROPERTYVALUE + ", a." + SQLTableConstants.TBLCOL_PROPERTYTYPE + (si.supports2009Model() ? (", a." + SQLTableConstants.TBLCOL_ENTRYSTATEID) : "") + (si.supports2009Model() ? ", es.*" : "") + ", b." + SQLTableConstants.TBLCOL_TYPENAME + ", b." + SQLTableConstants.TBLCOL_ATTRIBUTEVALUE + ", b." + SQLTableConstants.TBLCOL_VAL1 + ", b." + SQLTableConstants.TBLCOL_VAL2); propertyQuery.append(" FROM "); String codingSchemeName = si.getSQLTableConstants().codingSchemeNameOrId; String concptCode = si.getSQLTableConstants().entityCodeOrEntityId; propertyQuery.append(si.getTableName(SQLTableConstants.ENTITY_PROPERTY) + " {AS} a "); propertyQuery.append( " left join " + si.getTableName(SQLTableConstants.ENTITY_PROPERTY_MULTI_ATTRIBUTES)); propertyQuery.append(" {AS} b on a." + codingSchemeName + " = b." + codingSchemeName + " and a." + concptCode + " = b." + concptCode + " and a." + SQLTableConstants.TBLCOL_PROPERTYID + " = b." + SQLTableConstants.TBLCOL_PROPERTYID); if (si.supports2009Model()) { propertyQuery .append(" left join " + si.getTableName(SQLTableConstants.ENTRY_STATE) + " {AS} es "); propertyQuery.append("on a." + SQLTableConstants.TBLCOL_ENTRYSTATEID); propertyQuery.append(" = es." + SQLTableConstants.TBLCOL_ENTRYSTATEID); } propertyQuery.append(" where a." + concptCode + " = ? " + "and a." + codingSchemeName + " = ?"); if (si.supports2009Model()) { propertyQuery.append(" and a." + SQLTableConstants.TBLCOL_ENTITYCODENAMESPACE + " = ?"); } if (restrictToProperties != null && restrictToProperties.getEntryCount() > 0) { propertyQuery.append(" AND ("); for (int i = 0; i < restrictToProperties.getEntryCount(); i++) { propertyQuery.append(" " + si.getSQLTableConstants().propertyOrPropertyName + " = ? "); if (i + 1 < restrictToProperties.getEntryCount()) { propertyQuery.append(" OR "); } } propertyQuery.append(")"); } if (restrictToPropertyTypes != null && restrictToPropertyTypes.length > 0) { propertyQuery.append(" AND ("); for (int i = 0; i < restrictToPropertyTypes.length; i++) { propertyQuery.append(" " + SQLTableConstants.TBLCOL_PROPERTYTYPE + " = ? "); if (i + 1 < restrictToPropertyTypes.length) { propertyQuery.append(" OR "); } } propertyQuery.append(")"); } getEntityProperties = si.modifyAndCheckOutPreparedStatement(propertyQuery.toString()); int i = 1; getEntityProperties.setString(i++, code); getEntityProperties.setString(i++, internalCodingSchemeName); if (si.supports2009Model()) { getEntityProperties.setString(i++, namespace); } if (restrictToProperties != null && restrictToProperties.getEntryCount() > 0) { for (int j = 0; j < restrictToProperties.getEntryCount(); j++) { getEntityProperties.setString(i++, restrictToProperties.getEntry(j)); } } if (restrictToPropertyTypes != null && restrictToPropertyTypes.length > 0) { for (int j = 0; j < restrictToPropertyTypes.length; j++) { String pts = RestrictionImplementations.mapPropertyType(restrictToPropertyTypes[j]); getEntityProperties.setString(i++, pts); } } results = getEntityProperties.executeQuery(); // store the property from the last row org.LexGrid.commonTypes.Property newProperty = null; // all of the fields that come from the Property table String propertyType, property, propertyValue, language, presentationFormat, degreeOfFidelity, propertyId, representationalForm; Boolean matchIfNoContext, isPreferred; // holders for attributes, qualifiers Hashtable<String, Source> sources = null; HashSet<String> usageContexts = null; Hashtable<String, PropertyQualifier> propertyQualifiers = null; // As I process the result rows, I will get back duplicates of // the property information // if the property has more than one qualifer and/or source , // etc. while (results.next()) { propertyId = results.getString(SQLTableConstants.TBLCOL_PROPERTYID); if (newProperty == null || !propertyId.equals(newProperty.getPropertyId())) { // not equal means we have started a new property property = results.getString(si.getSQLTableConstants().propertyOrPropertyName); propertyType = results.getString(SQLTableConstants.TBLCOL_PROPERTYTYPE); propertyValue = results.getString(SQLTableConstants.TBLCOL_PROPERTYVALUE); language = results.getString(SQLTableConstants.TBLCOL_LANGUAGE); presentationFormat = results .getString(si.getSQLTableConstants().formatOrPresentationFormat); degreeOfFidelity = results.getString(SQLTableConstants.TBLCOL_DEGREEOFFIDELITY); representationalForm = results.getString(SQLTableConstants.TBLCOL_REPRESENTATIONALFORM); matchIfNoContext = DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_MATCHIFNOCONTEXT); isPreferred = DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISPREFERRED); // add all of the collected sources, usage contexts, and // qualifiers to // the previous property if (newProperty != null) { newProperty.setSource(sources.values().toArray(new Source[sources.size()])); newProperty.setUsageContext(usageContexts.toArray(new String[usageContexts.size()])); if (!propertyQualifiers.isEmpty()) newProperty.setPropertyQualifier(propertyQualifiers.values() .toArray(new PropertyQualifier[propertyQualifiers.size()])); } // we are starting a new property, so clear out the old // holders. sources = new Hashtable<String, Source>(); usageContexts = new HashSet<String>(); propertyQualifiers = new Hashtable<String, PropertyQualifier>(); // process the property portion of the result if (propertyType.equals(SQLTableConstants.TBLCOLVAL_DEFINITION)) { Definition def = new Definition(); def.setIsPreferred(isPreferred); def.setLanguage(language); def.setPropertyName(property); def.setPropertyId(propertyId); Text text = new Text(); text.setContent(propertyValue); text.setDataType(presentationFormat); def.setValue(text); definitions.add(def); newProperty = def; } else if (propertyType.equals(SQLTableConstants.TBLCOLVAL_PRESENTATION)) { Presentation presentation = new Presentation(); presentation.setIsPreferred(isPreferred); presentation.setLanguage(language); presentation.setPropertyName(property); presentation.setPropertyId(propertyId); Text text = new Text(); text.setContent(propertyValue); text.setDataType(presentationFormat); presentation.setValue(text); presentation.setDegreeOfFidelity(degreeOfFidelity); presentation.setMatchIfNoContext(matchIfNoContext); presentation.setRepresentationalForm(representationalForm); presentations.add(presentation); newProperty = presentation; } else if (propertyType.equals(SQLTableConstants.TBLCOLVAL_COMMENT)) { Comment comment = new Comment(); comment.setLanguage(language); comment.setPropertyName(property); comment.setPropertyId(propertyId); Text text = new Text(); text.setContent(propertyValue); text.setDataType(presentationFormat); comment.setValue(text); comments.add(comment); newProperty = comment; } else { Property theProperty = new Property(); theProperty.setLanguage(language); theProperty.setPropertyName(property); theProperty.setPropertyId(propertyId); Text text = new Text(); text.setContent(propertyValue); text.setDataType(presentationFormat); theProperty.setValue(text); properties.add(theProperty); newProperty = theProperty; } newProperty.setPropertyType(propertyType); if (si.supports2009Model()) { String owner = results.getString(SQLTableConstants.TBLCOL_OWNER); String status = results.getString(SQLTableConstants.TBLCOL_STATUS); Timestamp effectiveDate = results.getTimestamp(SQLTableConstants.TBLCOL_EFFECTIVEDATE); Timestamp expirationDate = results .getTimestamp(SQLTableConstants.TBLCOL_EXPIRATIONDATE); String revisionId = results.getString(SQLTableConstants.TBLCOL_REVISIONID); String prevRevisionId = results.getString(SQLTableConstants.TBLCOL_PREVREVISIONID); String changeType = results.getString(SQLTableConstants.TBLCOL_CHANGETYPE); String relativeOrder = results.getString(SQLTableConstants.TBLCOL_RELATIVEORDER); if (revisionId != null) { EntryState es = new EntryState(); if (!StringUtils.isBlank(changeType)) { es.setChangeType(org.LexGrid.versions.types.ChangeType.valueOf(changeType)); } es.setContainingRevision(revisionId); es.setPrevRevision(prevRevisionId); es.setRelativeOrder(computeRelativeOrder(relativeOrder)); newProperty.setEntryState(es); } if (owner != null) { newProperty.setOwner(owner); } if (status != null) newProperty.setStatus(status); if (effectiveDate != null) newProperty.setEffectiveDate(effectiveDate); if (expirationDate != null) newProperty.setExpirationDate(expirationDate); } } String type = null; String value = null; String val1 = null; String val2 = null; // collect values from the multiAttributes table type = results.getString(SQLTableConstants.TBLCOL_TYPENAME); value = results.getString(SQLTableConstants.TBLCOL_ATTRIBUTEVALUE); val1 = results.getString(SQLTableConstants.TBLCOL_VAL1); if (StringUtils.isBlank(val1)) val1 = null; val2 = results.getString(SQLTableConstants.TBLCOL_VAL2); if (StringUtils.isBlank(val2)) val2 = null; // hashsets to remove dupes (table doesn't allow dupes, but // left join will create some) if (type != null) { if (type.equalsIgnoreCase(SQLTableConstants.TBLCOLVAL_SOURCE)) { if (!sources.containsKey(createUniqueKeyForSource(value, val1))) { Source s = new Source(); s.setContent(value); s.setRole(val2); s.setSubRef(val1); sources.put(createUniqueKeyForSource(value, val1), s); } } else if (type.equalsIgnoreCase(SQLTableConstants.TBLCOLVAL_USAGECONTEXT)) { usageContexts.add(value); } else if (type.equalsIgnoreCase(SQLTableConstants.TBLCOLVAL_QUALIFIER)) { // nulls are a side affect of left join if (!propertyQualifiers.containsKey(val1 + ":" + value)) { PropertyQualifier pq = new PropertyQualifier(); Text txt = new Text(); txt.setContent(val1); pq.setValue(txt); pq.setPropertyQualifierName(value); propertyQualifiers.put(val1 + ":" + value, pq); } } else { getLogger().warn("There is invalid data in the 'typeName' column in the table " + si.getTableName(SQLTableConstants.ENTITY_PROPERTY_MULTI_ATTRIBUTES) + " for the concept code: " + code + " propertyId: " + propertyId + " codingSchemeName: " + internalCodingSchemeName); } } } // add all of the collected sources, usage contexts, and // qualifiers to // the previous property before exiting ... if (newProperty != null) { newProperty.setSource(sources.values().toArray(new Source[sources.size()])); newProperty.setUsageContext(usageContexts.toArray(new String[usageContexts.size()])); if (!propertyQualifiers.isEmpty()) newProperty.setPropertyQualifier(propertyQualifiers.values() .toArray(new PropertyQualifier[propertyQualifiers.size()])); } results.close(); } finally { si.checkInPreparedStatement(getEntityCode); si.checkInPreparedStatement(getEntityProperties); si.checkInPreparedStatement(getPropertyLinks); } concept.setComment(comments.toArray(new Comment[comments.size()])); concept.setDefinition(definitions.toArray(new Definition[definitions.size()])); concept.setPropertyLink(links.toArray(new PropertyLink[links.size()])); concept.setPresentation(presentations.toArray(new Presentation[presentations.size()])); concept.setProperty(properties.toArray(new Property[properties.size()])); return concept; } catch (MissingResourceException e) { throw e; } catch (Exception e) { throw new UnexpectedInternalError("There was an unexpected internal error.", e); } }
From source file:org.lexevs.dao.database.sqlimplementedmethods.SQLImplementedMethodsDao.java
/** * Builds the coded entry.// w ww .j a v a2 s. c om * * @param internalCodingSchemeName the internal coding scheme name * @param internalVersionString the internal version string * @param code the code * @param namespace the namespace * @param restrictToProperties the restrict to properties * @param restrictToPropertyTypes the restrict to property types * * @return the entity * * @throws UnexpectedInternalError the unexpected internal error * @throws MissingResourceException the missing resource exception */ public Entity buildCodedEntry(String internalCodingSchemeName, String internalVersionString, String code, String namespace, LocalNameList restrictToProperties, PropertyType[] restrictToPropertyTypes) throws UnexpectedInternalError, MissingResourceException { try { Entity concept = new Entity(); concept.setEntityCode(code); SQLInterface si = resourceManager.getSQLInterface(internalCodingSchemeName, internalVersionString); //if the namespace is null (and its 2009 model), set it to the default (which is //equal to the codingSchemeName. //This shouldn't ever happen -- all classes that call this method should provide //a namespace. if (si.supports2009Model() && StringUtils.isBlank(namespace)) { namespace = internalCodingSchemeName; } ArrayList<Definition> definitions = new ArrayList<Definition>(); ArrayList<Presentation> presentations = new ArrayList<Presentation>(); ArrayList<Property> properties = new ArrayList<Property>(); ArrayList<Comment> comments = new ArrayList<Comment>(); ArrayList<PropertyLink> links = new ArrayList<PropertyLink>(); PreparedStatement getEntityCode = null; PreparedStatement getEntityType = null; PreparedStatement getEntityProperties = null; PreparedStatement getPropertyLinks = null; try { StringBuffer buildEntity = new StringBuffer(); buildEntity .append("Select * " + " from " + si.getTableName(SQLTableConstants.ENTITY) + " {AS} t1 "); if (si.supports2009Model()) { buildEntity.append("left join " + si.getTableName(SQLTableConstants.ENTRY_STATE) + " {AS} t2 " + "on t1." + SQLTableConstants.TBLCOL_ENTRYSTATEID + " = t2." + SQLTableConstants.TBLCOL_ENTRYSTATEID); } buildEntity.append(" where " + si.getSQLTableConstants().codingSchemeNameOrId + " = ? AND " + si.getSQLTableConstants().entityCodeOrId + " = ?"); if (si.supports2009Model()) { buildEntity.append(" AND " + SQLTableConstants.TBLCOL_ENTITYCODENAMESPACE + " = ?"); } getEntityCode = si.modifyAndCheckOutPreparedStatement(buildEntity.toString()); getEntityCode.setString(1, internalCodingSchemeName); getEntityCode.setString(2, code); if (si.supports2009Model()) { getEntityCode.setString(3, namespace); } ResultSet results = getEntityCode.executeQuery(); // one and only one result if (results.next()) { concept.setIsDefined( DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISDEFINED)); concept.setIsAnonymous( DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISANONYMOUS)); concept.setIsActive( DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISACTIVE)); if (!si.supports2009Model()) { concept.setStatus(results.getString(SQLTableConstants.TBLCOL_CONCEPTSTATUS)); } else { concept.setEntityCodeNamespace(namespace); } EntityDescription ed = new EntityDescription(); ed.setContent(results.getString(SQLTableConstants.TBLCOL_ENTITYDESCRIPTION)); concept.setEntityDescription(ed); if (si.supports2009Model()) { String owner = results.getString(SQLTableConstants.TBLCOL_OWNER); String status = results.getString(SQLTableConstants.TBLCOL_STATUS); Timestamp effectiveDate = results.getTimestamp(SQLTableConstants.TBLCOL_EFFECTIVEDATE); Timestamp expirationDate = results.getTimestamp(SQLTableConstants.TBLCOL_EXPIRATIONDATE); String revisionId = results.getString(SQLTableConstants.TBLCOL_REVISIONID); String prevRevisionId = results.getString(SQLTableConstants.TBLCOL_PREVREVISIONID); String changeType = results.getString(SQLTableConstants.TBLCOL_CHANGETYPE); String relativeOrder = results.getString(SQLTableConstants.TBLCOL_RELATIVEORDER); EntryState es = new EntryState(); if (!StringUtils.isBlank(changeType)) { es.setChangeType(org.LexGrid.versions.types.ChangeType.valueOf(changeType)); } es.setContainingRevision(revisionId); es.setPrevRevision(prevRevisionId); es.setRelativeOrder(computeRelativeOrder(relativeOrder)); concept.setEntryState(es); if (owner != null) { concept.setOwner(owner); } concept.setStatus(status); concept.setEffectiveDate(effectiveDate); concept.setExpirationDate(expirationDate); } } results.close(); si.checkInPreparedStatement(getEntityCode); if (si.supports2009Model()) { getEntityType = si.checkOutPreparedStatement( "Select * " + " from " + si.getTableName(SQLTableConstants.ENTITY_TYPE) + " where " + si.getSQLTableConstants().codingSchemeNameOrId + " = ? AND " + si.getSQLTableConstants().entityCodeOrId + " = ? AND " + SQLTableConstants.TBLCOL_ENTITYCODENAMESPACE + " = ?"); getEntityType.setString(1, internalCodingSchemeName); getEntityType.setString(2, code); getEntityType.setString(3, namespace); results = getEntityType.executeQuery(); while (results.next()) { concept.addEntityType(results.getString(SQLTableConstants.TBLCOL_ENTITYTYPE)); } results.close(); si.checkInPreparedStatement(getEntityType); } else { concept.addEntityType(SQLTableConstants.ENTITYTYPE_CONCEPT); } // populate the property links String addWhereSegment = (!si.supports2009Model() ? (si.getSQLTableConstants().entityType + " = '" + SQLTableConstants.ENTITYTYPE_CONCEPT + "' and ") : ""); getPropertyLinks = si .checkOutPreparedStatement("Select " + SQLTableConstants.TBLCOL_SOURCEPROPERTYID + ", " + SQLTableConstants.TBLCOL_LINK + ", " + SQLTableConstants.TBLCOL_TARGETPROPERTYID + " from " + si.getTableName(SQLTableConstants.ENTITY_PROPERTY_LINKS) + " where " + addWhereSegment + si.getSQLTableConstants().entityCodeOrEntityId + " = ? and " + si.getSQLTableConstants().codingSchemeNameOrId + " = ?"); getPropertyLinks.setString(1, code); getPropertyLinks.setString(2, internalCodingSchemeName); results = getPropertyLinks.executeQuery(); while (results.next()) { String sourcePropertyId = results.getString(SQLTableConstants.TBLCOL_SOURCEPROPERTYID); String link = results.getString(SQLTableConstants.TBLCOL_LINK); String targetPropertyId = results.getString(SQLTableConstants.TBLCOL_TARGETPROPERTYID); PropertyLink pl = new PropertyLink(); pl.setPropertyLink(link); pl.setSourceProperty(sourcePropertyId); pl.setTargetProperty(targetPropertyId); links.add(pl); } results.close(); si.checkInPreparedStatement(getPropertyLinks); // codedEntry.setModVersion(null); StringBuffer propertyQuery = new StringBuffer(); // I'm constructing a left join query to get the property // results I need from 3 (or 2 in 1.5 table version) different // tables at once, rather than doing a query on each. propertyQuery.append("SELECT a." + SQLTableConstants.TBLCOL_PROPERTYID + ", a." + SQLTableConstants.TBLCOL_PROPERTYNAME + ", a." + SQLTableConstants.TBLCOL_LANGUAGE + ", a." + SQLTableConstants.TBLCOL_FORMAT + ", a." + SQLTableConstants.TBLCOL_ISPREFERRED + ", a." + SQLTableConstants.TBLCOL_DEGREEOFFIDELITY + ", a." + SQLTableConstants.TBLCOL_MATCHIFNOCONTEXT + ", a." + SQLTableConstants.TBLCOL_REPRESENTATIONALFORM + ", a." + SQLTableConstants.TBLCOL_PROPERTYVALUE + ", a." + SQLTableConstants.TBLCOL_PROPERTYTYPE + (si.supports2009Model() ? (", a." + SQLTableConstants.TBLCOL_ENTRYSTATEID) : "") + (si.supports2009Model() ? ", es.*" : "") + ", b." + SQLTableConstants.TBLCOL_TYPENAME + ", b." + SQLTableConstants.TBLCOL_ATTRIBUTEVALUE + ", b." + SQLTableConstants.TBLCOL_VAL1 + ", b." + SQLTableConstants.TBLCOL_VAL2); propertyQuery.append(" FROM "); String codingSchemeName = si.getSQLTableConstants().codingSchemeNameOrId; String concptCode = si.getSQLTableConstants().entityCodeOrEntityId; propertyQuery.append(si.getTableName(SQLTableConstants.ENTITY_PROPERTY) + " {AS} a "); propertyQuery.append( " left join " + si.getTableName(SQLTableConstants.ENTITY_PROPERTY_MULTI_ATTRIBUTES)); propertyQuery.append(" {AS} b on a." + codingSchemeName + " = b." + codingSchemeName + " and a." + concptCode + " = b." + concptCode + " and a." + SQLTableConstants.TBLCOL_PROPERTYID + " = b." + SQLTableConstants.TBLCOL_PROPERTYID); if (si.supports2009Model()) { propertyQuery .append(" left join " + si.getTableName(SQLTableConstants.ENTRY_STATE) + " {AS} es "); propertyQuery.append("on a." + SQLTableConstants.TBLCOL_ENTRYSTATEID); propertyQuery.append(" = es." + SQLTableConstants.TBLCOL_ENTRYSTATEID); } propertyQuery.append(" where a." + concptCode + " = ? " + "and a." + codingSchemeName + " = ?"); if (si.supports2009Model()) { propertyQuery.append(" and a." + SQLTableConstants.TBLCOL_ENTITYCODENAMESPACE + " = ?"); } if (restrictToProperties != null && restrictToProperties.getEntryCount() > 0) { propertyQuery.append(" AND ("); for (int i = 0; i < restrictToProperties.getEntryCount(); i++) { propertyQuery.append(" " + si.getSQLTableConstants().propertyOrPropertyName + " = ? "); if (i + 1 < restrictToProperties.getEntryCount()) { propertyQuery.append(" OR "); } } propertyQuery.append(")"); } if (restrictToPropertyTypes != null && restrictToPropertyTypes.length > 0) { propertyQuery.append(" AND ("); for (int i = 0; i < restrictToPropertyTypes.length; i++) { propertyQuery.append(" " + SQLTableConstants.TBLCOL_PROPERTYTYPE + " = ? "); if (i + 1 < restrictToPropertyTypes.length) { propertyQuery.append(" OR "); } } propertyQuery.append(")"); } getEntityProperties = si.modifyAndCheckOutPreparedStatement(propertyQuery.toString()); int i = 1; getEntityProperties.setString(i++, code); getEntityProperties.setString(i++, internalCodingSchemeName); if (si.supports2009Model()) { getEntityProperties.setString(i++, namespace); } if (restrictToProperties != null && restrictToProperties.getEntryCount() > 0) { for (int j = 0; j < restrictToProperties.getEntryCount(); j++) { getEntityProperties.setString(i++, restrictToProperties.getEntry(j)); } } if (restrictToPropertyTypes != null && restrictToPropertyTypes.length > 0) { for (int j = 0; j < restrictToPropertyTypes.length; j++) { String pts = DaoUtility.propertyTypeToStringMap.get(restrictToPropertyTypes[j]); getEntityProperties.setString(i++, pts); } } results = getEntityProperties.executeQuery(); // store the property from the last row org.LexGrid.commonTypes.Property newProperty = null; // all of the fields that come from the Property table String propertyType, property, propertyValue, language, presentationFormat, degreeOfFidelity, propertyId, representationalForm; Boolean matchIfNoContext, isPreferred; // holders for attributes, qualifiers Hashtable<String, Source> sources = null; HashSet<String> usageContexts = null; Hashtable<String, PropertyQualifier> propertyQualifiers = null; // As I process the result rows, I will get back duplicates of // the property information // if the property has more than one qualifer and/or source , // etc. while (results.next()) { propertyId = results.getString(SQLTableConstants.TBLCOL_PROPERTYID); if (newProperty == null || !propertyId.equals(newProperty.getPropertyId())) { // not equal means we have started a new property property = results.getString(si.getSQLTableConstants().propertyOrPropertyName); propertyType = results.getString(SQLTableConstants.TBLCOL_PROPERTYTYPE); propertyValue = results.getString(SQLTableConstants.TBLCOL_PROPERTYVALUE); language = results.getString(SQLTableConstants.TBLCOL_LANGUAGE); presentationFormat = results .getString(si.getSQLTableConstants().formatOrPresentationFormat); degreeOfFidelity = results.getString(SQLTableConstants.TBLCOL_DEGREEOFFIDELITY); representationalForm = results.getString(SQLTableConstants.TBLCOL_REPRESENTATIONALFORM); matchIfNoContext = DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_MATCHIFNOCONTEXT); isPreferred = DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISPREFERRED); // add all of the collected sources, usage contexts, and // qualifiers to // the previous property if (newProperty != null) { newProperty.setSource(sources.values().toArray(new Source[sources.size()])); newProperty.setUsageContext(usageContexts.toArray(new String[usageContexts.size()])); if (!propertyQualifiers.isEmpty()) newProperty.setPropertyQualifier(propertyQualifiers.values() .toArray(new PropertyQualifier[propertyQualifiers.size()])); } // we are starting a new property, so clear out the old // holders. sources = new Hashtable<String, Source>(); usageContexts = new HashSet<String>(); propertyQualifiers = new Hashtable<String, PropertyQualifier>(); // process the property portion of the result if (propertyType.equals(SQLTableConstants.TBLCOLVAL_DEFINITION)) { Definition def = new Definition(); def.setIsPreferred(isPreferred); def.setLanguage(language); def.setPropertyName(property); def.setPropertyId(propertyId); Text text = new Text(); text.setContent(propertyValue); text.setDataType(presentationFormat); def.setValue(text); definitions.add(def); newProperty = def; } else if (propertyType.equals(SQLTableConstants.TBLCOLVAL_PRESENTATION)) { Presentation presentation = new Presentation(); presentation.setIsPreferred(isPreferred); presentation.setLanguage(language); presentation.setPropertyName(property); presentation.setPropertyId(propertyId); Text text = new Text(); text.setContent(propertyValue); text.setDataType(presentationFormat); presentation.setValue(text); presentation.setDegreeOfFidelity(degreeOfFidelity); presentation.setMatchIfNoContext(matchIfNoContext); presentation.setRepresentationalForm(representationalForm); presentations.add(presentation); newProperty = presentation; } else if (propertyType.equals(SQLTableConstants.TBLCOLVAL_COMMENT)) { Comment comment = new Comment(); comment.setLanguage(language); comment.setPropertyName(property); comment.setPropertyId(propertyId); Text text = new Text(); text.setContent(propertyValue); text.setDataType(presentationFormat); comment.setValue(text); comments.add(comment); newProperty = comment; } else { Property theProperty = new Property(); theProperty.setLanguage(language); theProperty.setPropertyName(property); theProperty.setPropertyId(propertyId); Text text = new Text(); text.setContent(propertyValue); text.setDataType(presentationFormat); theProperty.setValue(text); properties.add(theProperty); newProperty = theProperty; } newProperty.setPropertyType(propertyType); if (si.supports2009Model()) { String owner = results.getString(SQLTableConstants.TBLCOL_OWNER); String status = results.getString(SQLTableConstants.TBLCOL_STATUS); Timestamp effectiveDate = results.getTimestamp(SQLTableConstants.TBLCOL_EFFECTIVEDATE); Timestamp expirationDate = results .getTimestamp(SQLTableConstants.TBLCOL_EXPIRATIONDATE); String revisionId = results.getString(SQLTableConstants.TBLCOL_REVISIONID); String prevRevisionId = results.getString(SQLTableConstants.TBLCOL_PREVREVISIONID); String changeType = results.getString(SQLTableConstants.TBLCOL_CHANGETYPE); String relativeOrder = results.getString(SQLTableConstants.TBLCOL_RELATIVEORDER); if (revisionId != null) { EntryState es = new EntryState(); if (!StringUtils.isBlank(changeType)) { es.setChangeType(org.LexGrid.versions.types.ChangeType.valueOf(changeType)); } es.setContainingRevision(revisionId); es.setPrevRevision(prevRevisionId); es.setRelativeOrder(computeRelativeOrder(relativeOrder)); newProperty.setEntryState(es); } if (owner != null) { newProperty.setOwner(owner); } if (status != null) newProperty.setStatus(status); if (effectiveDate != null) newProperty.setEffectiveDate(effectiveDate); if (expirationDate != null) newProperty.setExpirationDate(expirationDate); } } String type = null; String value = null; String val1 = null; String val2 = null; // collect values from the multiAttributes table type = results.getString(SQLTableConstants.TBLCOL_TYPENAME); value = results.getString(SQLTableConstants.TBLCOL_ATTRIBUTEVALUE); val1 = results.getString(SQLTableConstants.TBLCOL_VAL1); if (StringUtils.isBlank(val1)) val1 = null; val2 = results.getString(SQLTableConstants.TBLCOL_VAL2); if (StringUtils.isBlank(val2)) val2 = null; // hashsets to remove dupes (table doesn't allow dupes, but // left join will create some) if (type != null) { if (type.equalsIgnoreCase(SQLTableConstants.TBLCOLVAL_SOURCE)) { if (!sources.containsKey(createUniqueKeyForSource(value, val1))) { Source s = new Source(); s.setContent(value); s.setRole(val2); s.setSubRef(val1); sources.put(createUniqueKeyForSource(value, val1), s); } } else if (type.equalsIgnoreCase(SQLTableConstants.TBLCOLVAL_USAGECONTEXT)) { usageContexts.add(value); } else if (type.equalsIgnoreCase(SQLTableConstants.TBLCOLVAL_QUALIFIER)) { // nulls are a side affect of left join if (!propertyQualifiers.containsKey(val1 + ":" + value)) { PropertyQualifier pq = new PropertyQualifier(); Text txt = new Text(); txt.setContent(val1); pq.setValue(txt); pq.setPropertyQualifierName(value); propertyQualifiers.put(val1 + ":" + value, pq); } } else { getLogger().warn("There is invalid data in the 'typeName' column in the table " + si.getTableName(SQLTableConstants.ENTITY_PROPERTY_MULTI_ATTRIBUTES) + " for the concept code: " + code + " propertyId: " + propertyId + " codingSchemeName: " + internalCodingSchemeName); } } } // add all of the collected sources, usage contexts, and // qualifiers to // the previous property before exiting ... if (newProperty != null) { newProperty.setSource(sources.values().toArray(new Source[sources.size()])); newProperty.setUsageContext(usageContexts.toArray(new String[usageContexts.size()])); if (!propertyQualifiers.isEmpty()) newProperty.setPropertyQualifier(propertyQualifiers.values() .toArray(new PropertyQualifier[propertyQualifiers.size()])); } results.close(); } finally { si.checkInPreparedStatement(getEntityCode); si.checkInPreparedStatement(getEntityProperties); si.checkInPreparedStatement(getPropertyLinks); } concept.setComment(comments.toArray(new Comment[comments.size()])); concept.setDefinition(definitions.toArray(new Definition[definitions.size()])); concept.setPropertyLink(links.toArray(new PropertyLink[links.size()])); concept.setPresentation(presentations.toArray(new Presentation[presentations.size()])); concept.setProperty(properties.toArray(new Property[properties.size()])); return concept; } catch (MissingResourceException e) { throw e; } catch (Exception e) { throw new UnexpectedInternalError("There was an unexpected internal error.", e); } }
From source file:sos.settings.SOSSettingsDialog.java
/** * Alle Applikationen anzeigen/*w ww . j a v a2 s . com*/ * * @param applicationsTitle * Titel * @param applications * Werte (siehe getDialogApplications) * @return boolean Fehlerzustand * @throws Exception * @see #showDialogApplications(String, Vector) */ private boolean showDialogApplications(String applicationsTitle, Vector applications) throws Exception { this.debug(3, "showDialogApplications : applicationsTitle = " + applicationsTitle + " applications = " + applications); if (applicationsTitle != null) { this.dialogApplicationsTitle = applicationsTitle; } if (applications != null) { this.dialogApplications = applications; } if (this.dialogApplications == null) { this.dialogApplications = new Vector(); } if (this.dialogApplications.size() == 0) { if (this.error() == false) { this.setError(this.rb.getMessage("sos.settings.dialog.err_not_found_apps"), SOSClassUtil.getMethodName()); } } this.showTableBegin(); this.showNavigation(new Integer(1), null, null, null); try { this.getTopLevelRights(); } catch (Exception e) { this.setError(e.getMessage(), SOSClassUtil.getMethodName()); this.showTableEnd(); return false; } if (!this.hasTopLevelReadRight && !this.hasTopLevelCreateRight) { this.showTableEnd(); return false; } // JS Code fir's Help schreiben this.openHelpWin(); //$normalize_field_name = $this->normalize_field_name; String imgLink = "<img src=\"" + this.imgDir + this.imgAction + "\" border=\"0\" hspace=\"4\" vspace=\"1\">"; String thisCon = (this.site.indexOf('?') != -1) ? "&" : "?"; String querySession = "?"; if (!this.sessionUseTransSID && !this.sessionVAR.equals("")) { querySession = thisCon + this.sessionVAR + "=" + this.sessionID + "&"; } else { querySession = thisCon; } if (this.enableApplicationManager == true && this.hasTopLevelCreateRight) { this.out.println(" <tr class=\"" + this.styleTr + "\">"); String link = "<a class=\"" + this.styleLinkNavigation + "\" href=\"" + this.site + querySession + "action=new&range=application\">"; this.out.println(" <td class=\"" + this.styleTd + "\">"); if (this.hasCreateRight == true) { this.out.println(link + imgLink + this.dialogApplicationsNewTitle + "</a>"); } this.out.println(" </td>"); this.out.println(" </tr>"); } String sqlHelp = " select \"APPLICATION\",\"SECTION\", \"NAME\" "; sqlHelp += " from " + this.settings.source + " s "; sqlHelp += " where s.\"" + this.settings.entryApplication + "\" = s.\"" + this.settings.entrySection + "\" and "; sqlHelp += " s.\"" + this.settings.entryApplication + "\" = s.\"" + this.settings.entryName + "\" and "; sqlHelp += " s.\"DOCUMENTATION\" is not null "; Hashtable helpTexts = new Hashtable(); try { Vector helpText = this.connection.getArrayAsVector(sqlHelp); if (helpText.size() > 0) { for (Enumeration el = helpText.elements(); el.hasMoreElements();) { HashMap hm = (HashMap) el.nextElement(); helpTexts.put(hm.get("application").toString() + hm.get("section").toString() + hm.get("name").toString(), "Help"); } this.hasHelps = true; } } catch (Exception e) { this.setError(e.getMessage(), SOSClassUtil.getMethodName()); } try { for (Enumeration el = this.dialogApplications.elements(); el.hasMoreElements();) { HashMap application = (HashMap) el.nextElement(); String linkSections = "<a href=\"" + this.site + querySession + "action=show&range=sections&application=" + this.response .encodeURL(application.get(this.settings.entryApplication.toLowerCase()).toString()) + "&application_type=" + application.get("entry_type") + "\">"; String linkApplication = ""; if (this.enableApplicationManager == true) { linkApplication = "<a href=\"" + this.site + querySession + "action=show&range=application&application=" + this.response.encodeURL( application.get(this.settings.entryApplication.toLowerCase()).toString()) + "\">"; } else { linkApplication = linkSections; } String k = application.get(this.settings.entryApplication.toLowerCase()).toString() + application.get(this.settings.entrySection.toLowerCase()).toString() + application.get(this.settings.entryName.toLowerCase()).toString(); String linkHelp = " "; if (helpTexts.containsKey(k)) { String session = "''"; if (!this.sessionID.equals("")) { session = "'" + this.sessionID + "'"; } String helpHref = "source=" + this.settings.source + "&application=" + this.response.encodeURL( application.get(this.settings.entryApplication.toLowerCase()).toString()) + "§ion=" + this.response .encodeURL(application.get(this.settings.entrySection.toLowerCase()).toString()) + "&entry=" + this.response .encodeURL(application.get(this.settings.entryName.toLowerCase()).toString()); linkHelp = "<a href=\"javascript:openHelpWin('" + helpHref + "'," + session + ");\"><img src=\"" + this.imgDir + this.imgHelp + "\" border=\"0\" title=\"" + this.rb.getMessage("sos.settings.dialog.label_help") + "\"></a>"; } try { this.getRights(application.get("application").toString(), null, null); if (this.hasReadRight == false && this.hasCreateRight == false) { continue; } } catch (Exception e) { this.out.println(" <tr class=\"" + this.styleTr + "\">"); this.out.println(" <td class=\"" + this.styleTd + "\">"); this.out.println(" <table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">"); this.out.println(" <tr>"); this.out.println(" <td class=\"" + this.styleTd + "\" width=\"50%\">"); this.out.println(" " + application.get(this.settings.entrySettingTitle.toLowerCase())); this.out.println(" </td>"); this.out.print(" <td>"); this.showError("ACL : " + e.getMessage()); this.out.println("</td>"); this.out.println(" </tr>"); this.out.println(" </table>"); this.out.println(" </td>"); this.out.println(" </tr>"); continue; } this.out.println(" <tr class=\"" + this.styleTr + "\">"); this.out.println(" <td class=\"" + this.styleTd + "\">"); this.out.println(" <table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">"); this.out.println(" <tr>"); this.out.println(" <td class=\"" + this.styleTd + "\" width=\"50%\">"); this.out.println(linkApplication + imgLink + "</a>" + linkSections + application.get(this.settings.entrySettingTitle.toLowerCase()) + "</a>"); this.out.println(" </td>"); this.out.println(" <td>" + linkHelp + "</td>"); this.out.println(" </tr>"); this.out.println(" </table>"); this.out.println(" </td>"); this.out.println(" </tr>"); } } catch (Exception e) { this.setError(e.getMessage(), SOSClassUtil.getMethodName()); } this.showActions(new Integer(1), null, null, null); this.showTableEnd(); return true; }
From source file:sos.settings.SOSSettingsDialog.java
/** * Alle Sektionen einer Applikation anzeigen * /*from w w w . j a v a2 s.c o m*/ * @param sectionsTitle * Titel * @param sections * Werte (siehe getDialogSections) * @return boolean Fehlerzustand * @throws Exception * @see #showDialogSections(String, Vector) */ private boolean showDialogSections(String sectionsTitle, Vector sections) throws Exception { this.debug(3, "showDialogSections : sectionsTitle = " + sectionsTitle + " sections = " + sections); if (sectionsTitle != null) { this.dialogSectionsTitle = sectionsTitle; } if (sections != null) { this.dialogSections = sections; } if (this.dialogSections == null) { this.dialogSections = new Vector(); } if (this.dialogSections.size() == 0) { if (this.error() == false) { this.setError(this.rb.getMessage("sos.settings.dialog.err_not_found_sections"), SOSClassUtil.getMethodName()); } } String imgLink = "<img src=\"" + this.imgDir + this.imgAction + "\" border=\"0\" hspace=\"4\" vspace=\"1\">"; String thisCon = (this.site.indexOf('?') != -1) ? "&" : "?"; String querySession = "?"; if (!this.sessionUseTransSID && !this.sessionVAR.equals("")) { querySession = thisCon + this.sessionVAR + "=" + this.sessionID + "&"; } else { querySession = thisCon; } this.showTableBegin(); this.showNavigation(new Integer(1), this.dialogApplicationIndex, null, null); this.aclRange = "application"; try { this.getRights(this.settings.application, null, null); } catch (Exception e) { this.setError("ACL : " + e.getMessage(), SOSClassUtil.getMethodName()); } // JS Code fir's Help schreiben this.openHelpWin(); String link = ""; if (this.dialogApplicationIndex.intValue() >= 0 && this.enableSectionManager == true) { if (this.applicationType == 1) { // Schema if (this.hasReadRight == true || this.hasWriteRight == true || this.hasCreateRight == true) { this.out.println("<tr class=\"" + this.styleTr + "\">"); link = "<a class=\"" + this.styleLinkNavigation + "\" href=\"" + this.site + querySession + "action=new&range=section&application=" + this.response.encodeURL(this.settings.application) + "&application_type=" + this.applicationType + "\">"; this.out.println(" <td class=\"" + this.styleTd + "\">" + link + imgLink + this.dialogSectionsNewTitle + "</a></td>"); this.out.println(" </tr>"); } } else { if (this.hasCreateRight == true) { this.out.println(" <tr class=\"" + this.styleTr + "\">"); link = "<a class=\"" + this.styleLinkNavigation + "\" href=\"" + this.site + querySession + "action=new&range=section&application=" + this.response.encodeURL(this.settings.application) + "&application_type=" + this.applicationType + "\">"; this.out.println(" <td class=\"" + this.styleTd + "\">" + link + imgLink + this.dialogSectionsNewTitle + "</a></td>"); this.out.println(" </tr>"); } } } String sqlHelp = " select \"APPLICATION\",\"SECTION\", \"NAME\" "; sqlHelp += " from " + this.settings.source + " s "; sqlHelp += " where s.\"" + this.settings.entryApplication + "\" = " + this.dbQuoted(this.settings.application) + " and "; sqlHelp += " s.\"" + this.settings.entryApplication + "\" <> s.\"" + this.settings.entrySection + "\" and "; sqlHelp += " s.\"" + this.settings.entrySection + "\" = s.\"" + this.settings.entryName + "\" and "; sqlHelp += " s.\"DOCUMENTATION\" is not null "; Hashtable helpTexts = new Hashtable(); try { Vector helpText = this.connection.getArrayAsVector(sqlHelp); if (helpText.size() > 0) { for (Enumeration el = helpText.elements(); el.hasMoreElements();) { HashMap hm = (HashMap) el.nextElement(); helpTexts.put(hm.get("application").toString() + hm.get("section").toString() + hm.get("name").toString(), "Help"); } this.hasHelps = true; } } catch (Exception e) { this.setError(e.getMessage(), SOSClassUtil.getMethodName()); } for (Enumeration el = this.dialogSections.elements(); el.hasMoreElements();) { HashMap section = (HashMap) el.nextElement(); String linkHelp = " "; String linkEntries = ""; String linkSection = ""; boolean hasRights = true; boolean isSchema = false; if (section.get("name").toString().equals(this.settings.entrySchemaSection)) { isSchema = true; if (this.hasCreateRight == true) { // Schema bearbeiten linkEntries = "<a class=\"" + this.styleLinkNavigation + "\" href=\"" + this.site + querySession + "action=show&range=entries&application=" + this.response.encodeURL(this.settings.application) + "§ion=" + this.response .encodeURL(section.get(this.settings.entrySection.toLowerCase()).toString()) + "&application_type=" + this.applicationType + "§ion_type=" + section.get("entry_type").toString() + "\">"; linkSection = linkEntries; } else { hasRights = false; } } else { String k = this.settings.application + section.get(this.settings.entrySection.toLowerCase()).toString() + section.get(this.settings.entrySection.toLowerCase()).toString(); if (helpTexts.containsKey(k)) { String session = "''"; if (!this.sessionID.equals("")) { session = "'" + this.sessionID + "'"; } String helpHref = "source=" + this.settings.source + "&application=" + this.response.encodeURL(this.settings.application) + "§ion=" + this.response .encodeURL(section.get(this.settings.entrySection.toLowerCase()).toString()) + "&entry=" + this.response .encodeURL(section.get(this.settings.entrySection.toLowerCase()).toString()); linkHelp = "<a href=\"javascript:openHelpWin('" + helpHref + "'," + session + ");\"><img src=\"" + this.imgDir + this.imgHelp + "\" border=\"0\" title=\"" + this.rb.getMessage("sos.settings.dialog.label_help") + "\"></a>"; } linkEntries = "<a href=\"" + this.site + querySession + "action=show&range=entries&application=" + this.response.encodeURL(this.settings.application) + "§ion=" + this.response.encodeURL(section.get(this.settings.entrySection.toLowerCase()).toString()) + "&application_type=" + this.applicationType + "§ion_type=" + section.get("entry_type").toString() + "\">"; linkSection = (this.enableSectionManager == true) ? "<a href=\"" + this.site + querySession + "action=show&range=section&application=" + this.response.encodeURL(this.settings.application) + "§ion=" + this.response.encodeURL( section.get(this.settings.entrySection.toLowerCase()).toString()) + "\">" : linkEntries; } this.aclRange = "section"; try { this.getRights(section.get("application").toString(), section.get("section").toString(), null); if (this.hasReadRight == false && this.hasCreateRight == false) { continue; } } catch (Exception e) { this.out.println(" <tr class=\"" + this.styleTr + "\">"); this.out.println(" <td class=\"" + this.styleTd + "\">"); this.out.println(" <table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">"); this.out.println(" <tr>"); this.out.println(" <td class=\"" + this.styleTd + "\" width=\"50%\">"); this.out.println(" " + section.get(this.settings.entrySettingTitle.toLowerCase()).toString()); this.out.println(" </td>"); this.out.println(" <td>"); this.showError("ACL : " + e.getMessage()); this.out.println(" </td>"); this.out.println(" </tr>"); this.out.println(" </table>"); this.out.println(" </td>"); this.out.println(" </tr>"); continue; } if (hasRights) { String sectionTitle = (isSchema) ? this.rb.getMessage("sos.settings.dialog.dialog_sections_schema_title") : section.get(this.settings.entrySettingTitle.toLowerCase()).toString(); this.out.println(" <tr class=\"" + this.styleTr + "\">"); this.out.println(" <td class=\"" + this.styleTd + "\">"); this.out.println(" <table width=\"100%\" border=\"0\" cellpadding=\"0\" cellspacing=\"0\">"); this.out.println(" <tr>"); this.out.println(" <td class=\"" + this.styleTd + "\" width=\"50%\">"); this.out.println(" " + linkSection + imgLink + "</a>" + linkEntries + sectionTitle + "</a>"); this.out.println(" </td>"); this.out.println(" <td>" + linkHelp + "</td>"); this.out.println(" </tr>"); this.out.println(" </table>"); this.out.println(" </td>"); this.out.println(" </tr>"); } } // enumeration this.showActions(new Integer(1), this.dialogApplicationIndex, null, null); this.showTableEnd(); return true; }
From source file:org.sakaiproject.site.tool.SiteAction.java
/** * do called when "eventSubmit_do" is in the request parameters to c is * called from site list menu entry Revise... to get a locked site as * editable and to go to the correct template to begin DB version of writes * changes to disk at site commit whereas XML version writes at server * shutdown/*ww w. jav a 2s. c o m*/ */ public void doGet_site(RunData data) { SessionState state = ((JetspeedRunData) data).getPortletSessionState(((JetspeedRunData) data).getJs_peid()); ParameterParser params = data.getParameters(); // check form filled out correctly if (params.getStrings("selectedMembers") == null) { addAlert(state, rb.getString("java.nosites")); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); return; } List chosenList = new ArrayList(Arrays.asList(params.getStrings("selectedMembers"))); // Site id's of checked // sites String siteId = ""; if (!chosenList.isEmpty()) { if (chosenList.size() != 1) { addAlert(state, rb.getString("java.please")); state.setAttribute(STATE_TEMPLATE_INDEX, "0"); return; } siteId = (String) chosenList.get(0); getReviseSite(state, siteId); state.setAttribute(SORTED_BY, SiteConstants.SORTED_BY_PARTICIPANT_NAME); state.setAttribute(SORTED_ASC, Boolean.TRUE.toString()); } // reset the paging info resetPaging(state); if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP)) { state.setAttribute(STATE_PAGESIZE_SITESETUP, state.getAttribute(STATE_PAGESIZE)); } Hashtable h = (Hashtable) state.getAttribute(STATE_PAGESIZE_SITEINFO); if (!h.containsKey(siteId)) { // when first entered Site Info, set the participant list size to // 200 as default state.setAttribute(STATE_PAGESIZE, Integer.valueOf(200)); // update h.put(siteId, Integer.valueOf(200)); state.setAttribute(STATE_PAGESIZE_SITEINFO, h); } else { // restore the page size in site info tool state.setAttribute(STATE_PAGESIZE, h.get(siteId)); } }
From source file:org.sakaiproject.site.tool.SiteAction.java
/** * init/*from w w w . j a v a 2s . c o m*/ * */ private void init(VelocityPortlet portlet, RunData data, SessionState state) { state.setAttribute(STATE_ACTION, "SiteAction"); setupFormNamesAndConstants(state); if (state.getAttribute(STATE_PAGESIZE_SITEINFO) == null) { state.setAttribute(STATE_PAGESIZE_SITEINFO, new Hashtable()); } if (SITE_MODE_SITESETUP.equalsIgnoreCase((String) state.getAttribute(STATE_SITE_MODE))) { state.setAttribute(STATE_TEMPLATE_INDEX, "0"); // need to watch out for the config question.xml existence. // read the file and put it to backup folder. if (SiteSetupQuestionFileParser.isConfigurationXmlAvailable()) { SiteSetupQuestionFileParser.updateConfig(); } } else if (SITE_MODE_HELPER.equalsIgnoreCase((String) state.getAttribute(STATE_SITE_MODE))) { state.setAttribute(STATE_TEMPLATE_INDEX, "1"); } else if (SITE_MODE_SITEINFO.equalsIgnoreCase((String) state.getAttribute(STATE_SITE_MODE))) { String siteId = ToolManager.getCurrentPlacement().getContext(); getReviseSite(state, siteId); Hashtable h = (Hashtable) state.getAttribute(STATE_PAGESIZE_SITEINFO); if (!h.containsKey(siteId)) { // update h.put(siteId, Integer.valueOf(200)); state.setAttribute(STATE_PAGESIZE_SITEINFO, h); state.setAttribute(STATE_PAGESIZE, Integer.valueOf(200)); } } if (state.getAttribute(STATE_SITE_TYPES) == null) { PortletConfig config = portlet.getPortletConfig(); // all site types (SITE_DEFAULT_LIST overrides tool config) String t = StringUtils.trimToNull(SITE_DEFAULT_LIST); if (t == null) t = StringUtils.trimToNull(config.getInitParameter("siteTypes")); if (t != null) { List types = new ArrayList(Arrays.asList(t.split(","))); if (cms == null) { // if there is no CourseManagementService, disable the process of creating course site List<String> courseTypes = SiteTypeUtil.getCourseSiteTypes(); types.remove(courseTypes); } state.setAttribute(STATE_SITE_TYPES, types); } else { t = (String) state.getAttribute(SiteHelper.SITE_CREATE_SITE_TYPES); if (t != null) { state.setAttribute(STATE_SITE_TYPES, new ArrayList(Arrays.asList(t.split(",")))); } else { state.setAttribute(STATE_SITE_TYPES, new Vector()); } } } // show UI for adding non-official participant(s) or not // if nonOfficialAccount variable is set to be false inside sakai.properties file, do not show the UI section for adding them. // the setting defaults to be true if (state.getAttribute(ADD_NON_OFFICIAL_PARTICIPANT) == null) { state.setAttribute(ADD_NON_OFFICIAL_PARTICIPANT, ServerConfigurationService.getString("nonOfficialAccount", "true")); } if (state.getAttribute(STATE_VISITED_TEMPLATES) == null) { List<String> templates = new Vector<String>(); if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITESETUP)) { templates.add("0"); // the default page of WSetup tool } else if (((String) state.getAttribute(STATE_SITE_MODE)).equalsIgnoreCase(SITE_MODE_SITEINFO)) { templates.add("12");// the default page of Site Info tool } state.setAttribute(STATE_VISITED_TEMPLATES, templates); } if (state.getAttribute(STATE_SITE_TITLE_MAX) == null) { int siteTitleMaxLength = ServerConfigurationService.getInt("site.title.maxlength", 25); state.setAttribute(STATE_SITE_TITLE_MAX, siteTitleMaxLength); } }
From source file:org.sakaiproject.site.tool.SiteAction.java
/** * getFeatures gets features for a new site * /*from w ww . j a v a 2 s .co m*/ */ private void getFeatures(ParameterParser params, SessionState state, String continuePageIndex) { List idsSelected = new Vector(); List existTools = state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST) == null ? new Vector() : (List) state.getAttribute(STATE_TOOL_REGISTRATION_OLD_SELECTED_LIST); // to reset the state variable of the multiple tool instances Set multipleToolIdSet = state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET) != null ? (Set) state.getAttribute(STATE_MULTIPLE_TOOL_ID_SET) : new HashSet(); // get the map of titles of multiple tool instances Map multipleToolIdTitleMap = state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) != null ? (Map) state.getAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP) : new HashMap(); // related to LTI Tool selection Map<String, Map<String, Object>> existingLtiIds = state .getAttribute(STATE_LTITOOL_EXISTING_SELECTED_LIST) != null ? (Map<String, Map<String, Object>>) state .getAttribute(STATE_LTITOOL_EXISTING_SELECTED_LIST) : null; HashMap<String, Map<String, Object>> ltiTools = (HashMap<String, Map<String, Object>>) state .getAttribute(STATE_LTITOOL_LIST); HashMap<String, Map<String, Object>> ltiSelectedTools = new HashMap<String, Map<String, Object>>(); boolean goToToolConfigPage = false; boolean homeSelected = false; // lti tool selection boolean ltiToolSelected = false; // Add new pages and tools, if any if (params.getStrings("selectedTools") == null && params.getStrings("selectedLtiTools") == null) { addAlert(state, rb.getString("atleastonetool")); } else { List l = new ArrayList(Arrays.asList(params.getStrings("selectedTools"))); // toolId's of chosen tools for (int i = 0; i < l.size(); i++) { String toolId = (String) l.get(i); if (toolId.equals(TOOL_ID_HOME)) { homeSelected = true; if (!idsSelected.contains(toolId)) idsSelected.add(toolId); } else if (toolId.startsWith(LTITOOL_ID_PREFIX)) { String ltiToolId = toolId.substring(LTITOOL_ID_PREFIX.length()); // whether there is any lti tool been selected if (existingLtiIds == null) { ltiToolSelected = true; } else { if (!existingLtiIds.keySet().contains(ltiToolId)) { // there are some new lti tool(s) selected ltiToolSelected = true; } } // add tool entry to list ltiSelectedTools.put(ltiToolId, ltiTools.get(ltiToolId)); } else { String originId = findOriginalToolId(state, toolId); if (isMultipleInstancesAllowed(originId)) { // if user is adding either EmailArchive tool, News tool // or Web Content tool, go to the Customize page for the // tool if (!existTools.contains(toolId)) { goToToolConfigPage = true; if (!multipleToolIdSet.contains(toolId)) multipleToolIdSet.add(toolId); if (!multipleToolIdTitleMap.containsKey(toolId)) { // reset tool title if there is a different title config setting String titleConfig = ServerConfigurationService .getString(CONFIG_TOOL_TITLE + originId); if (titleConfig != null && titleConfig.length() > 0) { multipleToolIdTitleMap.put(toolId, titleConfig); } else { multipleToolIdTitleMap.put(toolId, ToolManager.getTool(originId).getTitle()); } } } } else if ("sakai.mailbox".equals(toolId)) { // get the email alias when an Email Archive tool // has been selected String alias = getSiteAlias( mailArchiveChannelReference((String) state.getAttribute(STATE_SITE_INSTANCE_ID))); if (alias != null) { state.setAttribute(STATE_TOOL_EMAIL_ADDRESS, alias); } // go to the config page if (!existTools.contains(toolId)) { goToToolConfigPage = true; } } if (!idsSelected.contains(toolId)) idsSelected.add(toolId); } } state.setAttribute(STATE_TOOL_HOME_SELECTED, Boolean.valueOf(homeSelected)); if (!ltiSelectedTools.isEmpty()) { state.setAttribute(STATE_LTITOOL_SELECTED_LIST, ltiSelectedTools); } else { state.removeAttribute(STATE_LTITOOL_SELECTED_LIST); } } state.setAttribute(STATE_TOOL_REGISTRATION_SELECTED_LIST, idsSelected); // List of ToolRegistration toolId's // in case of import String importString = params.getString("import"); if (importString != null && importString.equalsIgnoreCase(Boolean.TRUE.toString())) { state.setAttribute(STATE_IMPORT, Boolean.TRUE); List importSites = new Vector(); if (params.getStrings("importSites") != null) { importSites = new ArrayList(Arrays.asList(params.getStrings("importSites"))); } if (importSites.size() == 0) { addAlert(state, rb.getString("java.toimport") + " "); } else { Hashtable sites = new Hashtable(); for (int index = 0; index < importSites.size(); index++) { try { Site s = SiteService.getSite((String) importSites.get(index)); if (!sites.containsKey(s)) { sites.put(s, new Vector()); } } catch (IdUnusedException e) { } } state.setAttribute(STATE_IMPORT_SITES, sites); } } else { state.removeAttribute(STATE_IMPORT); } // of // ToolRegistration // toolId's if (state.getAttribute(STATE_MESSAGE) == null) { if (state.getAttribute(STATE_IMPORT) != null) { // go to import tool page state.setAttribute(STATE_TEMPLATE_INDEX, "27"); } else if (goToToolConfigPage || ltiToolSelected) { state.setAttribute(STATE_MULTIPLE_TOOL_INSTANCE_SELECTED, Boolean.valueOf(goToToolConfigPage)); // go to the configuration page for multiple instances of tools state.setAttribute(STATE_TEMPLATE_INDEX, "26"); } else { // go to next page state.setAttribute(STATE_TEMPLATE_INDEX, continuePageIndex); } state.setAttribute(STATE_MULTIPLE_TOOL_ID_SET, multipleToolIdSet); state.setAttribute(STATE_MULTIPLE_TOOL_ID_TITLE_MAP, multipleToolIdTitleMap); } }