List of usage examples for java.util HashMap values
public Collection<V> values()
From source file:it.prato.comune.sit.LayerTerritorio.java
/** * Inserisce un nuovo oggetto territoriale in questo layer.<br> * <br>//from w w w . ja va 2 s .c om * * * @param oggettoTer Oggetto da inserire in questo layer * @param transaction transazione * @throws IOException Errore generico nell'accesso al DBStore * @throws SITException */ public void appendFeature(OggettoTerritorio oggettoTer, SITTransaction transaction) throws IOException, SITException { logger.debug("Inizio l'append dell'oggetto: " + oggettoTer.getClass() + " " + oggettoTer.getDescrizione()); HashMap<String, String> nch = oggettoTer.getFlagVariazione(); logger.debug("Campi variati dell'oggetto: " + nch); ArrayList<Object> objAttrs = new ArrayList<Object>(); ArrayList<String> nc = new ArrayList<String>(); Iterator<String> iter = nch.values().iterator(); DataStore ds = null; logger.debug("Itero l'hash map dei campi e dei valori..."); try { while (iter.hasNext()) { String nome = (String) iter.next(); if (nome.equals("##GEOM##")) { // TOB // nc.add(getDataStore().getSchema(configBean.getTypeName()).getDefaultGeometry().getName()); ds = getDataStore(); nc.add(ds.getSchema(configBean.getTypeName()).getGeometryDescriptor().getLocalName()); objAttrs.add(oggettoTer.getFeat().getDefaultGeometry()); } else { objAttrs.add(oggettoTer.getAttribute(nome)); nc.add(nome); if (oggettoTer.getAttribute(nome) != null) { logger.debug("Campo: " + nome + " - Valore: " + oggettoTer.getAttribute(nome) + " - Classe: " + oggettoTer.getAttribute(nome).getClass().getName()); } else { logger.debug("Campo: " + nome + " - Valore: " + oggettoTer.getAttribute(nome)); } } } } catch (IOException e) { logger.error("Errore durante recupero campi-valori dell'oggetto: IOException ", e); throw e; } catch (SITException e) { logger.error("Errore durante recupero campi-valori dell'oggetto: SITException ", e); throw e; } SimpleFeature newFeat = null; try { if (transaction == null) { newFeat = appendFeatureGeom(null, nc, objAttrs); } else { newFeat = appendFeatureGeom(null, nc, objAttrs, transaction); } } catch (IOException e) { logger.error("IOException durante aggiunta feature", e); throw e; } catch (SITIllegalAttributeException e) { logger.error("SITIllegalAttributeException durante aggiunta feature", e); throw e; } oggettoTer.setFeat(newFeat); }
From source file:com.cloud.network.bigswitch.BigSwitchBcfUtils.java
public TopologyData getTopology(long physicalNetworkId) { List<NetworkVO> networks; List<NicVO> nics;/*from w ww . ja v a 2 s. c o m*/ networks = _networkDao.listByPhysicalNetworkTrafficType(physicalNetworkId, TrafficType.Guest); TopologyData topo = new TopologyData(); // networks: // - all user created networks (VPC or non-VPC) // - one external network // routers: // - per VPC (handle in network loop) // - per stand-alone network (handle in network loop) // - one external router // handle external network first, only if NAT service is enabled if (networks != null) { if (!(networks.isEmpty()) && isNatEnabled()) { // get public net info - needed to set up source nat gateway NetworkVO pubNet = getPublicNetwork(physicalNetworkId); // locate subnet info SearchCriteria<VlanVO> sc = _vlanDao.createSearchCriteria(); sc.setParameters("network_id", pubNet.getId()); VlanVO vlanVO = _vlanDao.findOneBy(sc); // add tenant external network external TopologyData.Network network = topo.new Network(); network.setId("external"); network.setName("external"); network.setTenantId("external"); network.setTenantName("external"); String pubVlan = null; try { pubVlan = BroadcastDomainType.getValue(vlanVO.getVlanTag()); if (StringUtils.isNumeric(pubVlan)) { network.setVlan(Integer.valueOf(pubVlan)); } else { // untagged pubVlan = "0"; } } catch (URISyntaxException e) { e.printStackTrace(); } topo.addNetwork(network); } } // routerMap used internally for multiple updates to same tenant's router // add back to topo.routers after loop HashMap<String, RouterData> routerMap = new HashMap<String, RouterData>(); for (NetworkVO netVO : networks) { TopologyData.Network network = topo.new Network(); network.setId(netVO.getUuid()); network.setName(netVO.getName()); Integer vlan = null; if (netVO.getBroadcastUri() != null) { String vlanStr = BroadcastDomainType.getValue(netVO.getBroadcastUri()); if (StringUtils.isNumeric(vlanStr)) { vlan = Integer.valueOf(vlanStr); } else { // untagged vlan = 0; } } network.setVlan(vlan); network.setState(netVO.getState().name()); nics = _nicDao.listByNetworkId(netVO.getId()); List<Port> ports = new ArrayList<Port>(); String tenantId = null; String tenantName = null; // if VPC network, assign BCF tenant id with vpc uuid Vpc vpc = null; if (netVO.getVpcId() != null) { vpc = _vpcDao.acquireInLockTable(netVO.getVpcId()); } if (vpc != null) { tenantId = vpc.getUuid(); tenantName = vpc.getName(); } else { tenantId = netVO.getUuid(); tenantName = netVO.getName(); } for (NicVO nic : nics) { NetworkData netData = new NetworkData(); TopologyData.Port p = topo.new Port(); p.setAttachmentInfo(netData.new AttachmentInfo(nic.getUuid(), nic.getMacAddress())); VMInstanceVO vm = _vmDao.findById(nic.getInstanceId()); HostVO host = _hostDao.findById(vm.getHostId()); // if host not found, ignore this nic if (host == null) { continue; } String hostname = host.getName(); long zoneId = netVO.getDataCenterId(); String vmwareVswitchLabel = _networkModel.getDefaultGuestTrafficLabel(zoneId, HypervisorType.VMware); String[] labelArray = null; String vswitchName = null; if (vmwareVswitchLabel != null) { labelArray = vmwareVswitchLabel.split(","); vswitchName = labelArray[0]; } // hypervisor type: // kvm: ivs port name // vmware: specific portgroup naming convention String pgName = ""; if (host.getHypervisorType() == HypervisorType.KVM) { pgName = hostname; } else if (host.getHypervisorType() == HypervisorType.VMware) { pgName = hostname + "-" + vswitchName; } p.setHostId(pgName); p.setSegmentInfo(netData.new SegmentInfo(BroadcastDomainType.Vlan.name(), vlan)); p.setOwner(BigSwitchBcfApi.getCloudstackInstanceId()); List<AttachmentData.Attachment.IpAddress> ipList = new ArrayList<AttachmentData.Attachment.IpAddress>(); ipList.add(new AttachmentData().getAttachment().new IpAddress(nic.getIPv4Address())); p.setIpAddresses(ipList); p.setId(nic.getUuid()); p.setMac(nic.getMacAddress()); netData.getNetwork().setId(network.getId()); netData.getNetwork().setName(network.getName()); netData.getNetwork().setTenantId(tenantId); netData.getNetwork().setTenantName(tenantName); netData.getNetwork().setState(netVO.getState().name()); p.setNetwork(netData.getNetwork()); ports.add(p); } network.setTenantId(tenantId); network.setTenantName(tenantName); network.setPorts(ports); topo.addNetwork(network); // add router for network RouterData routerData; if (tenantId != null) { if (!routerMap.containsKey(tenantId)) { routerData = new RouterData(tenantId); routerMap.put(tenantId, routerData); } else { routerData = routerMap.get(tenantId); } routerData.getRouter().getAcls().addAll(listACLbyNetwork(netVO)); if (vpc != null) { routerData.getRouter().addExternalGateway(getPublicIpByVpc(vpc)); } else { routerData.getRouter().addExternalGateway(getPublicIpByNetwork(netVO)); } RouterInterfaceData intf = new RouterInterfaceData(tenantId, netVO.getGateway(), netVO.getCidr(), netVO.getUuid(), netVO.getName()); routerData.getRouter().addInterface(intf); } } for (RouterData rd : routerMap.values()) { topo.addRouter(rd.getRouter()); } return topo; }
From source file:edu.ku.brc.specify.tasks.subpane.wb.WorkbenchPaneSS.java
/** * //from w w w .j ava 2 s . co m */ private void readRegisteries() { HashMap<String, WBPluginInfo> plugins = new HashMap<String, WorkbenchPaneSS.WBPluginInfo>(); String fileName = "wb_registry.xml"; String path = XMLHelper.getConfigDirPath(fileName); readRegistry(path, plugins); path = AppPreferences.getLocalPrefs().getDirPath() + File.separator + fileName; readRegistry(path, plugins); for (WBPluginInfo wbp : plugins.values()) { String prefName = wbp.getPrefName(); if (StringUtils.isEmpty(prefName) || AppPreferences.getLocalPrefs().getBoolean(prefName, false)) { createPlugin(wbp.getClassName(), wbp.getIconName(), wbp.getToolTip()); } } }
From source file:algorithm.NQueens.java
public void doMain(String[] args) throws InterruptedException, IOException { CmdLineParser parser = new CmdLineParser(this); try {//w ww . ja v a 2 s. c o m /* Parse the arguments */ parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); System.err.println("java NQueens [options...] arguments..."); parser.printUsage(System.err); /* Print program sample showing all of the options */ System.err.println("\n Example: java NQueens" + parser.printExample(ALL)); System.exit(1); } try { String resultantPath = "/" + numQueens + "_q" + "/"; if (mutation == null) { resultantPath += "variable/"; } else { resultantPath += mutation.toString() + "/"; } outputDir += resultantPath; File dir = new File(outputDir); File figureDir = new File(outputDir + "/figures/"); /* * Returns true if all the directories are created * Returns false and the directories may have been made * (so far returns false every other time and it works every time) */ dir.mkdirs(); figureDir.mkdirs(); } catch (Exception e) { System.err.println(e.getMessage()); System.exit(1); } for (int count = 0; count < numRuns; ++count) { /* Create an initial population of uniformly random chromosomes */ initPopulation(); /* Initialize the Breed operation */ if (mutation != null) { Breed.init(new Random(), mutation); } else { Breed.init(new Random()); } /* Iterate until all of the solutions for the N queens problem has been found */ while (solutions.size() < distinctSolutions[numQueens - 1] && numGenerations <= maxGenerations) { /* If the percentage of similar chromosomes due to in-breeding exceeds * the minimum threshold value, increase the amount of mutation */ curSimilarity = similarChromosomes(population); if (mutation == null) { if (curSimilarity >= inbreedingThreshold) { Breed.inBreeding(true); } else { Breed.inBreeding(false); } } /* Calculate the fitness distribution of the current population */ HashMap<Chromosome, Double> fitness = Fitness.calculate(population); /* Instantiate the selection iterator using the fitness distribution, * the selection iterator uses roulette wheel selection to select * each chromosome. */ Selection selection = new Selection(new Random()); selection.init(fitness); /* Generate the next population by selecting chromosomes from the current * population using selection iterator and applying the cloning, crossover, * and mutation operations. */ ArrayList<Chromosome> nextPopulation = new ArrayList<Chromosome>(populationSize); ArrayList<Chromosome> chromosomes = new ArrayList<Chromosome>(2); while (nextPopulation.size() < populationSize) { /* Select a random number and apply the breeding operation */ Integer randomNum = random.nextInt(100); /* Pair of parent chromosomes continue on to the next generation.*/ if (Breed.CLONING.contains(randomNum)) { chromosomes.addAll(Breed.cloning(selection)); } /* Pair of parent chromosomes are cross-overed to create new pair */ else if (Breed.CROSSOVER.contains(randomNum)) { chromosomes.addAll(Breed.crossover(selection)); } /* Apply the background mutation operator to the chromosomes */ for (Chromosome chromosome : chromosomes) { randomNum = random.nextInt(100); if (Breed.MUTATION.contains(randomNum)) { nextPopulation.add(Breed.mutation(chromosome)); } else { nextPopulation.add(chromosome); } } chromosomes.clear(); } /* If there are any solutions (fitness of 1) that are unique save them */ for (Chromosome chromosome : fitness.keySet()) { if (fitness.get(chromosome) == 1.0) { if (uniqueSolution(chromosome)) { /* Save a copy of the chromosome */ Chromosome solution = new Chromosome(new ArrayList<Integer>(chromosome.get()), chromosome.size()); solutions.add(solution); solutionGeneration.put(solutions.size(), numGenerations); /* Perform three rotations then a reflection followed by three more rotations */ for (int i = 0; i < 6; ++i) { rotation = Transformation.rotate(solutions.get(solutions.size() - 1)); if (uniqueSolution(rotation)) { solutions.add(rotation); solutionGeneration.put(solutions.size(), numGenerations); } else { if (rotationMiss.containsKey(numGenerations)) { rotationMiss.put(numGenerations, rotationMiss.get(numGenerations) + 1); } else { rotationMiss.put(numGenerations, 1); } } if (i == 2) { reflection = Transformation.reflect(solution); if (uniqueSolution(reflection)) { solutions.add(reflection); solutionGeneration.put(solutions.size(), numGenerations); } else { if (reflectionMiss.containsKey(numGenerations)) { reflectionMiss.put(numGenerations, reflectionMiss.get(numGenerations) + 1); } else { reflectionMiss.put(numGenerations, 1); } } } } } else { if (duplicateBuffer.containsKey(numGenerations)) { duplicateBuffer.put(numGenerations, duplicateBuffer.get(numGenerations) + 1); } else { duplicateBuffer.put(numGenerations, 1); } } } } /* Save average fitness for the current generation */ DescriptiveStatistics descStats = new DescriptiveStatistics(Doubles.toArray(fitness.values())); fitnessBuffer.add(descStats.getMean()); /* Save chromosome similarity and mutation rate for current generation */ similarityBuffer.add(curSimilarity); /* Save the variable mutation rate */ if (mutation == null) { mutationBuffer.add((Breed.MUTATION.upperEndpoint() - Breed.MUTATION.lowerEndpoint()) / 100.0); } /* Calculate statistics for the fitness, similarity, and mutation buffer every 1000, generations */ if ((numGenerations % 1000) == 0) { calcStatistics(1000); } /* Write the current results to file every 10,000 generations */ if ((numGenerations % 10000) == 0) { writeResults(); } /* Set the current population as the NEXT population */ fitness.clear(); population = nextPopulation; ++numGenerations; } /* Calculate statistics and write any remaining results */ if (fitnessBuffer.size() > 0) { calcStatistics(1000); } writeResults(); /* Display random solutions for the number of solutions specified */ for (int j = 0; j < numDisplay; ++j) { /* Display a random solution */ Chromosome solution = solutions.get(random.nextInt(solutions.size())); try { QueenGame myGame = new QueenGame(new QueenBoard(Ints.toArray(solution.get()), numQueens)); myGame.playGame( outputDir + "/figures/" + "figure_run_" + String.valueOf(runNumber) + "_" + j + ".png"); } catch (Exception e) { System.out.println("Bad set of Queens"); } } /* Reset the current state for the next run and increment run number */ reset(); ++runNumber; } }
From source file:im.vector.contacts.ContactsManager.java
/** * List the local contacts.//w w w. ja v a2 s . c o m * @param context the context. */ public static void refreshLocalContactsSnapshot(Context context) { ContentResolver cr = context.getContentResolver(); HashMap<String, Contact> dict = new HashMap<>(); // test if the user allows to access to the contact if (isContactBookAccessAllowed(context)) { // get the names Cursor namesCur = null; try { namesCur = cr.query(ContactsContract.Data.CONTENT_URI, new String[] { ContactsContract.Contacts.DISPLAY_NAME_PRIMARY, ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID, ContactsContract.Contacts.PHOTO_THUMBNAIL_URI }, ContactsContract.Data.MIMETYPE + " = ?", new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE }, null); } catch (Exception e) { Log.e(LOG_TAG, "## refreshLocalContactsSnapshot(): Exception - Contact names query Msg=" + e.getMessage()); } if (namesCur != null) { try { while (namesCur.moveToNext()) { String displayName = namesCur .getString(namesCur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME_PRIMARY)); String contactId = namesCur.getString(namesCur .getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.CONTACT_ID)); String thumbnailUri = namesCur.getString(namesCur.getColumnIndex( ContactsContract.CommonDataKinds.StructuredName.PHOTO_THUMBNAIL_URI)); if (null != contactId) { Contact contact = dict.get(contactId); if (null == contact) { contact = new Contact(contactId); dict.put(contactId, contact); } if (null != displayName) { contact.setDisplayName(displayName); } if (null != thumbnailUri) { contact.setThumbnailUri(thumbnailUri); } } } } catch (Exception e) { Log.e(LOG_TAG, "## refreshLocalContactsSnapshot(): Exception - Contact names query2 Msg=" + e.getMessage()); } namesCur.close(); } // get the phonenumbers Cursor phonesCur = null; try { phonesCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, new String[] { ContactsContract.CommonDataKinds.Phone.DATA, // actual number ContactsContract.CommonDataKinds.Phone.CONTACT_ID }, null, null, null); } catch (Exception e) { Log.e(LOG_TAG, "## refreshLocalContactsSnapshot(): Exception - Phone numbers query Msg=" + e.getMessage()); } if (null != phonesCur) { try { while (phonesCur.moveToNext()) { String phone = phonesCur .getString(phonesCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA)); if (!TextUtils.isEmpty(phone)) { String contactId = phonesCur.getString( phonesCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID)); if (null != contactId) { Contact contact = dict.get(contactId); if (null == contact) { contact = new Contact(contactId); dict.put(contactId, contact); } contact.addPhonenumber(phone); } } } } catch (Exception e) { Log.e(LOG_TAG, "## refreshLocalContactsSnapshot(): Exception - Phone numbers query2 Msg=" + e.getMessage()); } phonesCur.close(); } // get the emails Cursor emailsCur = null; try { emailsCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, new String[] { ContactsContract.CommonDataKinds.Email.DATA, // actual email ContactsContract.CommonDataKinds.Email.CONTACT_ID }, null, null, null); } catch (Exception e) { Log.e(LOG_TAG, "## refreshLocalContactsSnapshot(): Exception - Emails query Msg=" + e.getMessage()); } if (emailsCur != null) { try { while (emailsCur.moveToNext()) { String email = emailsCur .getString(emailsCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)); if (!TextUtils.isEmpty(email)) { String contactId = emailsCur.getString( emailsCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.CONTACT_ID)); if (null != contactId) { Contact contact = dict.get(contactId); if (null == contact) { contact = new Contact(contactId); dict.put(contactId, contact); } contact.addEmailAdress(email); } } } } catch (Exception e) { Log.e(LOG_TAG, "## refreshLocalContactsSnapshot(): Exception - Emails query2 Msg=" + e.getMessage()); } emailsCur.close(); } } PIDsRetriever.getIntance().setPIDsRetrieverListener(mPIDsRetrieverListener); mContactsList = dict.values(); if (null != mListeners) { for (ContactsManagerListener listener : mListeners) { try { listener.onRefresh(); } catch (Exception e) { Log.e(LOG_TAG, "refreshLocalContactsSnapshot : onRefresh failed" + e.getLocalizedMessage()); } } } }
From source file:es.pode.catalogadorWeb.presentacion.catalogadorBasicPlus.CatBasicPlusControllerImpl.java
/** * @see es.pode.catalogadorBasicPlus.presentacion.catalogador.CatBasicPlusController#cargarDatos(org.apache.struts.action.ActionMapping, * es.pode.catalogadorBasicPlus.presentacion.catalogador.CargarDatosForm, * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) *///from w w w .j a v a 2 s . com public final void cargarDatos(ActionMapping mapping, es.pode.catalogadorWeb.presentacion.catalogadorBasicPlus.CargarDatosForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // // Load the information from the ODE specified in the request into a // LOM object within the session // String idioma = ((Locale) request.getSession().getAttribute(ConstantesAgrega.DEFAULT_LOCALE)).getLanguage(); String ficheroProperties = "/catalogadorBasicPlus.properties"; String source = AgregaPropertiesImpl.getInstance().getProperty("esquemaDeMetadatos"); InputStream is = null; ResourceBundle datosResources = I18n.getInstance().getResource("application-resources", (Locale) request.getSession().getAttribute(ConstantesAgrega.DEFAULT_LOCALE)); try { // Load the appropriate properties from the catalogadorBasicPlus.properties file is = this.getClass().getResourceAsStream(ficheroProperties); Properties prop = new Properties(); prop.load(is); // Load the vocabulary terms for field values we wish to explicitly check for HashMap vocabTerms = getVocabularyTerms(idioma); // Setup the various backing lists required for this form; we do this by // grabbing the terms specified // by the l_id array from the VocabulariosControladosService, and then // translating them from ISO form to their longer form int longVocabulario = 0; String[] l_id = { prop.getProperty("idioma"), prop.getProperty("aggregationLevel"), prop.getProperty("technicalOrCompositeType"), prop.getProperty("tipoDeRecurso"), prop.getProperty("intendedEndUserRole"), prop.getProperty("relationKind"), prop.getProperty("technicalOrCompositeName"), prop.getProperty("format") }; VocabularioVO[] vocabulario = this.getSrvVocabulariosControladosService().obtenerCombos(l_id, idioma); //vamos a ordenar vocabulario UtilidadesOrdenarCombos vocabularioOrdenado1 = new UtilidadesOrdenarCombos(); VocabularioVO[] vocabularioOrdenado = vocabularioOrdenado1.ordenarVocabulariosVO(vocabulario); longVocabulario = vocabularioOrdenado.length; for (int x = 0; x < longVocabulario; x++) { TerminoVO terminoVO = new TerminoVO(); terminoVO.setIdiomaTermino(""); terminoVO.setIdTermino(""); terminoVO.setNomTermino(""); switch (x) { case 0: // For the language (idioma) list Collection idIdioma = new ArrayList(); idIdioma.add(terminoVO); // modificamos las cadenas de idiomas TerminoVO[] terminos = vocabularioOrdenado[x].getTerminos(); for (int li = 0; li < terminos.length; li++) { TerminoVO idAux = new TerminoVO(); idAux = terminos[li]; String textoIdioma = idAux.getNomTermino(); String idiomasTra = ""; if (!textoIdioma.equals("x-none")) { idiomasTra = I18n.getInstance().obtenerIdiomaTraducido(textoIdioma, idioma); } else { idiomasTra = datosResources.getString("x-none"); } // Translate language code from short (ISO) format to long format idAux.setNomTermino(idiomasTra); } UtilidadesOrdenarCombos terminosOrd2 = new UtilidadesOrdenarCombos(); TerminoVO[] terminosOrd = terminosOrd2.ordenarTerminosVO(terminos, idioma); Collection id2 = Arrays.asList(terminosOrd); Iterator z = id2.iterator(); while (z.hasNext()) { idIdioma.add(z.next()); } // Set the language list form.setIdiomaBackingList(idIdioma, "idTermino", "nomTermino"); break; case 1: // Aggregation Level list Collection idAggLevel = new ArrayList(); idAggLevel.add(terminoVO); // Get the aggregation level terms TerminoVO[] terminosAggLevel = vocabularioOrdenado[x].getTerminos(); // Sort them UtilidadesOrdenarCombos sortAggLevel = new UtilidadesOrdenarCombos(); TerminoVO[] sortedAggLevelTerms = sortAggLevel.ordenarTerminosVO(terminosAggLevel, idioma); // Store as an ArrayList Collection idAggLevelList = Arrays.asList(sortedAggLevelTerms); Iterator zAggLevel = idAggLevelList.iterator(); while (zAggLevel.hasNext()) { TerminoVO thisAggLevelTerm = (TerminoVO) zAggLevel.next(); idAggLevel.add(thisAggLevelTerm); } // // HACK ALERT: Because the Aggregation Level form has separate labels // from values (and this is not supported in the VDEX vocabulary), we // forcibly override it here // zAggLevel = idAggLevelList.iterator(); int c = 0; while (zAggLevel.hasNext()) { TerminoVO thisAggLevelTerm = (TerminoVO) zAggLevel.next(); switch (c) { case 0: // Level 1 thisAggLevelTerm.setNomTermino("Asset"); break; case 1: // Level 2 thisAggLevelTerm.setNomTermino("Lesson part"); break; case 2: // Level 3 thisAggLevelTerm.setNomTermino("Full lesson or topic"); break; case 3: // Level 4 thisAggLevelTerm.setNomTermino("Course"); break; } c++; } // Set the aggregation level list form.setAggregationLevelBackingList(idAggLevel, "idTermino", "nomTermino"); break; case 2: // Technical OrComposite type list Collection tTechOrCompositeType = new ArrayList(); tTechOrCompositeType.add(terminoVO); Collection tTechOrCompositeType2 = Arrays.asList(vocabularioOrdenado[x].getTerminos()); Iterator contTechOrCompositeType = tTechOrCompositeType2.iterator(); while (contTechOrCompositeType.hasNext()) { TerminoVO thisTechOrCompositeTypeTerm = (TerminoVO) contTechOrCompositeType.next(); tTechOrCompositeType.add(thisTechOrCompositeTypeTerm); } // Set the technical OrComposite type backing list form.setTechnicalOrCompositeTypeBackingList(tTechOrCompositeType, "idTermino", "nomTermino"); break; case 3: // Resource type list Collection tResourceType = new ArrayList(); tResourceType.add(terminoVO); Collection tResourceType2 = Arrays.asList(vocabularioOrdenado[x].getTerminos()); Iterator contResourceType = tResourceType2.iterator(); while (contResourceType.hasNext()) { TerminoVO thisTipoRecursoTerm = (TerminoVO) contResourceType.next(); tResourceType.add(thisTipoRecursoTerm); } // Set the resource type backing list form.setTipoRecursoBackingList(tResourceType, "idTermino", "nomTermino"); break; case 4: // Intended end user role list Collection tIntendedEndUserRole = new ArrayList(); tIntendedEndUserRole.add(terminoVO); Collection tIntendedEndUserRole2 = Arrays.asList(vocabularioOrdenado[x].getTerminos()); Iterator contIntendedEndUserRoleType = tIntendedEndUserRole2.iterator(); while (contIntendedEndUserRoleType.hasNext()) { TerminoVO thisIntendedEndUserRoleTerm = (TerminoVO) contIntendedEndUserRoleType.next(); tIntendedEndUserRole.add(thisIntendedEndUserRoleTerm); } // Set the intended user role backing list form.setIntendedEndUserRoleBackingList(tIntendedEndUserRole, "idTermino", "nomTermino"); break; case 5: // Relation kind list Collection tRelationKind = new ArrayList(); tRelationKind.add(terminoVO); Collection tRelationKind2 = Arrays.asList(vocabularioOrdenado[x].getTerminos()); Iterator contRelationKindType = tRelationKind2.iterator(); while (contRelationKindType.hasNext()) { TerminoVO thisRelationKindTerm = (TerminoVO) contRelationKindType.next(); tRelationKind.add(thisRelationKindTerm); } // Set the relation kind backing list form.setRelationKindBackingList(tRelationKind, "idTermino", "nomTermino"); break; case 6: // Technical OrComposite name list Collection tTechOrCompositeName = new ArrayList(); tTechOrCompositeName.add(terminoVO); Collection tTechOrCompositeName2 = Arrays.asList(vocabularioOrdenado[x].getTerminos()); Iterator contTechOrCompositeName = tTechOrCompositeName2.iterator(); while (contTechOrCompositeName.hasNext()) { TerminoVO thisTechOrCompositeNameTerm = (TerminoVO) contTechOrCompositeName.next(); tTechOrCompositeName.add(thisTechOrCompositeNameTerm); } // Set the technical OrComposite type backing list form.setTechnicalOrCompositeNameBackingList(tTechOrCompositeName, "idTermino", "nomTermino"); break; case 7: // Format list Collection tFormat = new ArrayList(); tFormat.add(terminoVO); TerminoVO[] formatTVOs = vocabularioOrdenado[x].getTerminos(); // // The default vocab term ordering uses name (a format MIME // type) as the sort key which makes the label list look // inconsistent; for instance, in the NWLG's label list, // "Text/PDF" corresponds to the MIME type "application/pdf" // and "Image/PS" to "application/postscript". // // Therefore, we use the term ID as the sort key for an // ascending order sort instead; the order in which the // format terms appear in the vocabulary is the order // of the backing list. // // In terms of overhead, this little merge sort is not even // close to the ugly sort in ordenarVocabulariosVO; which is // performed just above this loop. Note that the frequency // of invocation in this method is the same for both sorts. // Arrays.sort(formatTVOs, new TerminoVOByIdComparator()); for (TerminoVO ftvo : formatTVOs) { // // If we find a user-friendly label for this MIME type, // we use that instead. // String label = MIMEToLabelMap.get(ftvo.getNomTermino()); if (label != null) { ftvo.setNomTermino(label); } tFormat.add(ftvo); } // Set the format backing list form.setFormatBackingList(tFormat, "idTermino", "nomTermino"); break; } } // Setup the advanced LOM CatalogadorBPSession os = this.getCatalogadorBPSession(request); LomAvanzadoVO lomAdvanced; if (os.getMBOSesion() == null) { // If the session object has not been set, load some defaults... String usuario = LdapUserDetailsUtils.getUsuario(); String identificador = request.getParameter("identificador");//"idLOM1";// //introducido nuevo parametro para vuelta al empaquetador String returnURL = request.getParameter("returnURL"); //PortalEmpaquetador/Inicio/Inicio.do os.setIdioma(idioma); os.setIdentificador(identificador); os.setUsuario(usuario); //metemos en la sesion el parametro de vuelta al empaquetador os.setReturnURL(returnURL); // If we get here then we are entering the cataloguer for the first // time. Hence we need to make sure that the following sections of // the LOM exist: // - General // - Technical // - Educational // - Lifecycle // - Relation // Grab the advanced LOM for this ODE lomAdvanced = this.getSrvCatalogacionAvanzadaService().obtenerLomAvanzado(identificador, usuario, idioma); if (lomAdvanced.getGeneral() == null) lomAdvanced.setGeneral(new AvGeneralVO()); if (lomAdvanced.getTechnical() == null) lomAdvanced.setTechnical(new AvTechnicalVO()); if (lomAdvanced.getEducational() == null) lomAdvanced.setEducational(new AvEducationalVO[] { new AvEducationalVO() }); if (lomAdvanced.getRelaciones() == null) lomAdvanced.setRelaciones(new AvRelationVO[] { new AvRelationVO() }); if (lomAdvanced.getLifeCycle() == null) lomAdvanced.setLifeCycle(new AvLifeCycleVO()); if (lomAdvanced.getMetaMetadata() == null) lomAdvanced.setMetaMetadata(new AvMetametadataVO()); // Store this LOM in the session this.getCatalogadorBPSession(request).setMBOSesion(lomAdvanced); } else { // If we are already editing an object (i.e. it's in the session) // then we simply set the form values to be those set in the // LOM object within the session lomAdvanced = os.getMBOSesion(); } // Set the title if (lomAdvanced.getGeneral().getTitulo() == null) { TituloVO tmpTituloVO = new TituloVO(); lomAdvanced.getGeneral().setTitulo(tmpTituloVO); LangStringVO tmpLangStringVO = new LangStringVO(); tmpLangStringVO.setIdioma("en"); tmpLangStringVO.setTexto(""); tmpTituloVO.setTextos(new LangStringVO[] { tmpLangStringVO }); } // Set the language if (lomAdvanced.getGeneral().getIdiomas() == null || lomAdvanced.getGeneral().getIdiomas().length == 0) { IdiomaVO[] tmpIdiomaVOArray = new IdiomaVO[1]; IdiomaVO tmpIdiomaVO = new IdiomaVO(); tmpIdiomaVO.setTexto(""); tmpIdiomaVOArray[0] = tmpIdiomaVO; lomAdvanced.getGeneral().setIdiomas(tmpIdiomaVOArray); } // Set the description (we allow one field only in this cataloguer) if (lomAdvanced.getGeneral().getDescripciones() == null || lomAdvanced.getGeneral().getDescripciones().length == 0) { DescripcionVO tmpDescriptionVO = new DescripcionVO(); LangStringVO tmpLangStringVO = new LangStringVO(); tmpLangStringVO.setIdioma("en"); tmpLangStringVO.setTexto(""); tmpDescriptionVO.setTextos(new LangStringVO[] { tmpLangStringVO }); lomAdvanced.getGeneral().setDescripciones(new DescripcionVO[] { tmpDescriptionVO }); } // Set the keyword (we allow one field in this cataloguer) if (lomAdvanced.getGeneral().getPalabrasClave() == null || lomAdvanced.getGeneral().getPalabrasClave().length == 0) { PalabraClaveVO tmpKeywordVO = new PalabraClaveVO(); LangStringVO tmpLangStringVO = new LangStringVO(); tmpLangStringVO.setIdioma("en"); tmpLangStringVO.setTexto(""); tmpKeywordVO.setTextos(new LangStringVO[] { tmpLangStringVO }); lomAdvanced.getGeneral().setPalabrasClave(new PalabraClaveVO[] { tmpKeywordVO }); } // Get a reference to the aggregation level object, creating one if it // doesn't already exist if (lomAdvanced.getGeneral().getNivelAgregacion() == null) { SourceValueVO tmpSourceValue = new SourceValueVO(); tmpSourceValue.setSource(source); tmpSourceValue.setValor(""); lomAdvanced.getGeneral().setNivelAgregacion(tmpSourceValue); } else { // Catch the case where the LOM has a general section, but no // initial value set if (lomAdvanced.getGeneral().getNivelAgregacion().getValor() == null) lomAdvanced.getGeneral().getNivelAgregacion().setValor(""); } // We're about to set some fields based upon particular contributor values // so let's get the contribution list if (lomAdvanced.getLifeCycle().getContribuciones() == null) { // Create an empty collection to keep things working lomAdvanced.getLifeCycle().setContribuciones(new ContribucionVO[] {}); } // Create a HashMap containing the contributions already within // the LOM keyed by contributor type HashMap contributorHashMap = new HashMap(); for (int i = 0; i < lomAdvanced.getLifeCycle().getContribuciones().length; i++) contributorHashMap.put(lomAdvanced.getLifeCycle().getContribuciones()[i].getTipo().getValor(), lomAdvanced.getLifeCycle().getContribuciones()[i]); // Check to see if the author is present, and add it if not if (contributorHashMap.get((String) vocabTerms.get("lifecycleAuthor")) == null) { ContribucionVO thisContribution = new ContribucionVO(); SourceValueVO tmpContributorSourceValueVO = new SourceValueVO(); tmpContributorSourceValueVO.setSource(source); tmpContributorSourceValueVO.setValor((String) vocabTerms.get("lifecycleAuthor")); thisContribution.setTipo(tmpContributorSourceValueVO); thisContribution.setEntidades(new EntidadVO[] { new EntidadVO() }); // Store back in the HashMap contributorHashMap.put((String) vocabTerms.get("lifecycleAuthor"), thisContribution); } // Check to see if the content provider is present, and add it if not if (contributorHashMap.get((String) vocabTerms.get("lifecycleContentProvider")) == null) { ContribucionVO thisContribution = new ContribucionVO(); SourceValueVO tmpContributorSourceValueVO = new SourceValueVO(); tmpContributorSourceValueVO.setSource(source); tmpContributorSourceValueVO.setValor((String) vocabTerms.get("lifecycleContentProvider")); thisContribution.setTipo(tmpContributorSourceValueVO); thisContribution.setEntidades(new EntidadVO[] { new EntidadVO() }); // Store back in the HashMap contributorHashMap.put((String) vocabTerms.get("lifecycleContentProvider"), thisContribution); } // Convert the HashMap values back into an array and store in the LOM lomAdvanced.getLifeCycle().setContribuciones( (ContribucionVO[]) contributorHashMap.values().toArray(new ContribucionVO[] {})); // Create a LifeCycle status object if it doesn't already exist... if (lomAdvanced.getLifeCycle().getEstado() == null) { SourceValueVO tmpState = new SourceValueVO(); tmpState.setSource(source); tmpState.setValor((String) vocabTerms.get("lifeCycleStatusFinal")); lomAdvanced.getLifeCycle().setEstado(tmpState); } // Set the installation remarks if (lomAdvanced.getTechnical().getPautasInstalacion() == null) { PautasInstalacionVO tmpInstallationNotes = new PautasInstalacionVO(); LangStringVO tmpLangStringVO = new LangStringVO(); tmpLangStringVO.setIdioma("en"); tmpLangStringVO.setTexto(""); tmpInstallationNotes.setTextos(new LangStringVO[] { tmpLangStringVO }); lomAdvanced.getTechnical().setPautasInstalacion(tmpInstallationNotes); } // Set the platform requirements if (lomAdvanced.getTechnical().getOtrosRequisitos() == null) { OtrosRequisitosVO tmpPlatformRequirements = new OtrosRequisitosVO(); LangStringVO tmpLangStringVO = new LangStringVO(); tmpLangStringVO.setIdioma("en"); tmpLangStringVO.setTexto(""); tmpPlatformRequirements.setTextos(new LangStringVO[] { tmpLangStringVO }); lomAdvanced.getTechnical().setOtrosRequisitos(tmpPlatformRequirements); } // Set the duration fields // From Advanced: expresion regular P[yY][mM][dD][T[hH][nM][s[.s]S]] if (lomAdvanced.getTechnical().getDuracion() == null) { DuracionVO tmpDuration = new DuracionVO(); DescripcionVO tmpDescription = new DescripcionVO(); LangStringVO tmpLangStringVO = new LangStringVO(); tmpLangStringVO.setIdioma("en"); tmpLangStringVO.setTexto(""); tmpDescription.setTextos(new LangStringVO[] { tmpLangStringVO }); tmpDuration.setDescripcion(tmpDescription); lomAdvanced.getTechnical().setDuracion(tmpDuration); } // Create the requirements section with an single blank // OrRequirement if it doesn't exist in the LOM if (lomAdvanced.getTechnical().getRequisitos() == null || lomAdvanced.getTechnical().getRequisitos().length == 0) { RequisitoVO tmpRequirement = new RequisitoVO(); AgregadorORVO tmpOrRequirement = new AgregadorORVO(); SourceValueVO tmpOrRequirementType = new SourceValueVO(); tmpOrRequirementType.setSource(source); tmpOrRequirementType.setValor(""); SourceValueVO tmpOrRequirementName = new SourceValueVO(); tmpOrRequirementName.setSource(source); tmpOrRequirementName.setValor(""); tmpOrRequirement.setTipo(tmpOrRequirementType); tmpOrRequirement.setNombre(tmpOrRequirementName); tmpRequirement.setAgregadoresOR(new AgregadorORVO[] { tmpOrRequirement }); lomAdvanced.getTechnical().setRequisitos(new RequisitoVO[] { tmpRequirement }); } // Create the format section with a single blank format if it // doesn't exist in the LOM if (lomAdvanced.getTechnical().getFormatos() == null || lomAdvanced.getTechnical().getFormatos().length == 0) { FormatoVO tmpFormat = new FormatoVO(); tmpFormat.setTexto(""); lomAdvanced.getTechnical().setFormatos(new FormatoVO[] { tmpFormat }); } // Create the annotation section with a single blank note if it // doesn't exist in the LOM if (lomAdvanced.getAnotaciones() == null || lomAdvanced.getAnotaciones().length == 0) { lomAdvanced.setAnotaciones(new AvAnnotationVO[] { createDefaultAnnotation() }); } // Get a reference to the resource type object, creating one if it // doesn't already exist if (lomAdvanced.getEducational()[0].getTiposrecursoedu() == null || lomAdvanced.getEducational()[0].getTiposrecursoedu().length == 0) { SourceValueVO tmpSourceValue = new SourceValueVO(); tmpSourceValue.setSource(source); tmpSourceValue.setValor(""); lomAdvanced.getEducational()[0].setTiposrecursoedu(new SourceValueVO[] { tmpSourceValue }); } else { // Catch the case where the LOM has an educational section, but no // initial value set if (lomAdvanced.getEducational()[0].getTiposrecursoedu()[0].getValor() == null) lomAdvanced.getEducational()[0].getTiposrecursoedu()[0].setValor(""); } // Get a reference to the intended end user role object, creating one if it // doesn't already exist if (lomAdvanced.getEducational()[0].getDestinatarios() == null || lomAdvanced.getEducational()[0].getDestinatarios().length == 0) { SourceValueVO tmpSourceValue = new SourceValueVO(); tmpSourceValue.setSource(source); tmpSourceValue.setValor(""); lomAdvanced.getEducational()[0].setDestinatarios(new SourceValueVO[] { tmpSourceValue }); } else { // Catch the case where the LOM has an educational section, but no // initial value set if (lomAdvanced.getEducational()[0].getDestinatarios()[0].getValor() == null) lomAdvanced.getEducational()[0].getDestinatarios()[0].setValor(""); } // Set the typical learning time fields if (lomAdvanced.getEducational()[0].getTiempoAprendizaje() == null) { DuracionVO tmpDuration = new DuracionVO(); DescripcionVO tmpDescription = new DescripcionVO(); LangStringVO tmpLangStringVO = new LangStringVO(); tmpLangStringVO.setIdioma("en"); tmpLangStringVO.setTexto(""); tmpDescription.setTextos(new LangStringVO[] { tmpLangStringVO }); tmpDuration.setDescripcion(tmpDescription); lomAdvanced.getEducational()[0].setTiempoAprendizaje(tmpDuration); } // // Load the curriculum trees from the LOM // // Make sure we have a classification object, and that we do not // overwrite the in-session curricular tree array when we reach here // from the curriculum tree browser. if (os.getCurriculumTreesArray() == null && lomAdvanced.getClasificaciones() != null && lomAdvanced.getClasificaciones().length > 0) { // And a taxonPath object if (lomAdvanced.getClasificaciones()[0].getRutasTaxonomicas() != null && lomAdvanced.getClasificaciones()[0].getRutasTaxonomicas().length > 0) { // Create an array of ArbolCurricularVO objects containing // the information from the LOM ArbolCurricularVO[] curriculumTreeArray = new ArbolCurricularVO[lomAdvanced .getClasificaciones()[0].getRutasTaxonomicas().length]; int treeId = 0; for (int i = 0; i < lomAdvanced.getClasificaciones()[0].getRutasTaxonomicas().length; i++) { RutaTaxonomicaVO thisTaxonPath = lomAdvanced.getClasificaciones()[0] .getRutasTaxonomicas()[i]; curriculumTreeArray[i] = new ArbolCurricularVO(); // Convert taxons array from CBTaxonVO to TaxonVO CBTaxonVO[] curriculumTaxonVO = new CBTaxonVO[thisTaxonPath.getTaxones().length]; int n = thisTaxonPath.getTaxones().length; for (int j = 0; j < n; j++) { TaxonVO thisTaxon = thisTaxonPath.getTaxones()[(n - 1) - j]; curriculumTaxonVO[j] = new CBTaxonVO(); curriculumTaxonVO[j].setId(thisTaxon.getId().getTexto()); curriculumTaxonVO[j].setValorTax(thisTaxon.getEntry().getTextos()[0].getTexto()); } // Store in the curriculum tree array. Note the tree identifier is just set // as an dummy 0.X value (where X increments by 1) for use as // a unique identifier for deleting curriculumTreeArray[i].setIdArbol("0." + treeId); curriculumTreeArray[i].setTaxones(curriculumTaxonVO); treeId++; } // Finally store the trees in the session os.setCurriculumTreesArray(curriculumTreeArray); } } // Get a reference to the relation kind object, creating one if it // doesn't already exist. Note that this field is optional. if (lomAdvanced.getRelaciones().length == 0) lomAdvanced.setRelaciones(new AvRelationVO[] { new AvRelationVO() }); if (lomAdvanced.getRelaciones()[0].getTipo() == null) { SourceValueVO tmpSourceValue = new SourceValueVO(); tmpSourceValue.setSource(source); tmpSourceValue.setValor(""); lomAdvanced.getRelaciones()[0].setTipo(tmpSourceValue); } else { // Catch the case where the LOM has an relation section, but no // initial value set if (lomAdvanced.getRelaciones()[0].getTipo().getValor() == null) lomAdvanced.getRelaciones()[0].getTipo().setValor(""); } // Set the relation kind description if (lomAdvanced.getRelaciones()[0].getRecurso() == null) { RecursoVO tmpResource = new RecursoVO(); DescripcionVO tmpDescription = new DescripcionVO(); LangStringVO tmpLangString = new LangStringVO(); tmpLangString.setIdioma("en"); tmpLangString.setTexto(""); tmpDescription.setTextos(new LangStringVO[] { tmpLangString }); IdentificadorVO tmpIdentifier = new IdentificadorVO(); tmpIdentifier.setCatalogo(""); tmpIdentifier.setEntrada(""); tmpResource.setIdentificador(tmpIdentifier); tmpResource.setDescripciones(new DescripcionVO[] { tmpDescription }); lomAdvanced.getRelaciones()[0].setRecurso(tmpResource); } // Force the list of items in the typicalLearningTimeFull backing list form.setTypicalLearningTimeFullLabelList(new String[] { "", "Less than 10 mins", "10 - 30 mins", "30 mins - 1 hour", "1 - 8 hours", "More than 8 hours" }); form.setTypicalLearningTimeFullValueList(new String[] { "", "00-00-00-00-10-00", "00-00-00-00-30-00", "00-00-00-01-00-00", "00-00-00-08-00-00", "00-00-07-00-00-00" }); // // Now load all of the form values from the LOM // // Set the title form.setTitulo(lomAdvanced.getGeneral().getTitulo().getTextos()[0].getTexto()); // Set the description form.setDescription(lomAdvanced.getGeneral().getDescripciones()[0].getTextos()[0].getTexto()); // Set the keyword form.setKeyword(lomAdvanced.getGeneral().getPalabrasClave()[0].getTextos()[0].getTexto()); // Set the author/content provider lifecycle contributions ContribucionVO[] contributions = lomAdvanced.getLifeCycle().getContribuciones(); for (int i = 0; i < contributions.length; i++) { ContribucionVO thisContribution = contributions[i]; // Check for author contributor type if (thisContribution.getTipo().getValor().equals(vocabTerms.get("lifecycleAuthor"))) { logger.debug("Located the author lifecycle entity"); // Grab the vCard string String vCardString = thisContribution.getEntidades()[0].getTexto(); // Parse it into a vCard object CataloguerVCard cvc = new CataloguerVCard(vCardString); if (cvc != null) { // Set the LifeCycle -> Author field if (cvc.getFullName() != null) form.setAuthorFullName(cvc.getFullName()); else form.setAuthorFullName(""); // Set the LifeCycle -> Organisation field if (cvc.getOrganisation() != null) form.setAuthorOrganisation(cvc.getOrganisation()); else form.setAuthorOrganisation(""); } } // Check for content provider contributor type if (thisContribution.getTipo().getValor().equals(vocabTerms.get("lifecycleContentProvider"))) { logger.debug("Located the provider lifecycle entity"); // Grab the vCard string String vCardString = thisContribution.getEntidades()[0].getTexto(); // Parse it into a vCard object CataloguerVCard cvc = new CataloguerVCard(vCardString); if (cvc != null) { // Set the LifeCycle -> Contributor field if (cvc.getFullName() != null) form.setProviderFullName(cvc.getFullName()); else form.setProviderFullName(""); } } } // Set the installation remarks form.setInstallationNotes(lomAdvanced.getTechnical().getPautasInstalacion().getTextos()[0].getTexto()); // Set the platform requirements form.setPlatformRequirements(lomAdvanced.getTechnical().getOtrosRequisitos().getTextos()[0].getTexto()); // Set the notes form.setNotes(lomAdvanced.getAnotaciones()[0].getDescripcion().getTextos()[0].getTexto()); // Set the duration fields: remember technical duration is optional... if (lomAdvanced.getTechnical().getDuracion() != null) { CataloguerDuration d1 = new CataloguerDuration( lomAdvanced.getTechnical().getDuracion().getDuracion()); form.setDurationYears(d1.getYears()); form.setDurationMonths(d1.getMonths()); form.setDurationDays(d1.getDays()); form.setDurationHours(d1.getHours()); form.setDurationMinutes(d1.getMinutes()); form.setDurationSeconds(d1.getSeconds()); } // Set the typical learning time fields CataloguerDuration d2 = new CataloguerDuration( lomAdvanced.getEducational()[0].getTiempoAprendizaje().getDuracion()); // We currently use a string of the form YY-MM-DD-HH-MM-SS to represent // the typical time within the form. Set let's generate this and then // set it. StringBuilder typicalLearningTimeFull = new StringBuilder(); typicalLearningTimeFull.append(zeroFromEmpty(d2.getYears()) + "-"); typicalLearningTimeFull.append(zeroFromEmpty(d2.getMonths()) + "-"); typicalLearningTimeFull.append(zeroFromEmpty(d2.getDays()) + "-"); typicalLearningTimeFull.append(zeroFromEmpty(d2.getHours()) + "-"); typicalLearningTimeFull.append(zeroFromEmpty(d2.getMinutes()) + "-"); typicalLearningTimeFull.append(zeroFromEmpty(d2.getSeconds())); form.setTypicalLearningTimeFull(typicalLearningTimeFull.toString()); // Set the relation kind entry (optional) if (lomAdvanced.getRelaciones().length > 0) { form.setRelationKindEntry( lomAdvanced.getRelaciones()[0].getRecurso().getIdentificador().getEntrada()); // Set the relation kind description form.setRelationKindDescription( lomAdvanced.getRelaciones()[0].getRecurso().getDescripciones()[0].getTextos()[0] .getTexto()); } // // For the LOM fields that are based upon backing lists (and so are // referenced by termIds rather than values), obtain the values for // the specified termIds from the vocabulary service so we can set // the form fields // TerminoYPadreVO[] terminoypadrear = new TerminoYPadreVO[longVocabulario]; for (int i = 0; i < longVocabulario; i++) { TerminoYPadreVO terminoypadreVO = new TerminoYPadreVO(); terminoypadreVO.setIdiomaTermino("en"); terminoypadreVO.setIdVocabulario(l_id[i]); terminoypadreVO.setIdTermino(""); switch (i) { case 0: // For the language (idioma) term terminoypadreVO.setNomTermino(lomAdvanced.getGeneral().getIdiomas()[0].getTexto()); break; case 1: // Aggregation Level term terminoypadreVO.setNomTermino(lomAdvanced.getGeneral().getNivelAgregacion().getValor()); break; case 2: // Technical OrComposite type term terminoypadreVO .setNomTermino(lomAdvanced.getTechnical().getRequisitos()[0].getAgregadoresOR()[0] .getTipo().getValor()); break; case 3: // Resource type term terminoypadreVO .setNomTermino(lomAdvanced.getEducational()[0].getTiposrecursoedu()[0].getValor()); break; case 4: // Intended end user role term terminoypadreVO.setNomTermino(lomAdvanced.getEducational()[0].getDestinatarios()[0].getValor()); break; case 5: // Relation kind term terminoypadreVO.setNomTermino(lomAdvanced.getRelaciones()[0].getTipo().getValor()); break; case 6: // Technical OrComposite name term terminoypadreVO .setNomTermino(lomAdvanced.getTechnical().getRequisitos()[0].getAgregadoresOR()[0] .getNombre().getValor()); break; case 7: // Format term terminoypadreVO.setNomTermino(lomAdvanced.getTechnical().getFormatos()[0].getTexto()); break; } terminoypadrear[i] = terminoypadreVO; } // Lookup the terms from the termIds TerminoYPadreVO[] terminoYPadreVuelta = this.getSrvVocabulariosControladosService() .obtenerIdTermino(terminoypadrear); String idi; // Set language term idi = terminoYPadreVuelta[0].getIdTermino(); if (idi != null) form.setIdioma(idi); // Set the aggregation level term idi = terminoYPadreVuelta[1].getIdTermino(); if (idi != null) form.setAggregationLevel(idi); // Set the technical OrComposite type term idi = terminoYPadreVuelta[2].getIdTermino(); if (idi != null) form.setTechnicalOrCompositeType(idi); // Set the resource type term idi = terminoYPadreVuelta[3].getIdTermino(); if (idi != null) form.setTipoRecurso(idi); // Set the intended end user role term idi = terminoYPadreVuelta[4].getIdTermino(); if (idi != null) form.setIntendedEndUserRole(idi); // Set the relation kind term idi = terminoYPadreVuelta[5].getIdTermino(); if (idi != null) form.setRelationKind(idi); // Set the technical OrComposite name term idi = terminoYPadreVuelta[6].getIdTermino(); if (idi != null) form.setTechnicalOrCompositeName(idi); // Set the format term idi = terminoYPadreVuelta[7].getIdTermino(); if (idi != null) form.setFormat(idi); // // Finally set the curriculum trees form variable so we can // display them // form.setCurriculumTreesAsArray(os.getCurriculumTreesArray()); } catch (Exception e) { logger.error("could not open catalogadorBasicPlus.properties file"); return; } logger.debug("#### Finished setting LomAdvanced"); }
From source file:com.cloud.hypervisor.vmware.resource.VmwareResource.java
protected OptionValue[] configureVnc(OptionValue[] optionsToMerge, VmwareHypervisorHost hyperHost, String vmName, String vncPassword, String keyboardLayout) throws Exception { VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); if (!mgr.beginExclusiveOperation(600)) throw new Exception("Unable to begin exclusive operation, lock time out"); try {/* ww w.j ava2s. c o m*/ int maxVncPorts = 64; int vncPort = 0; Random random = new Random(); HostMO vmOwnerHost = vmMo.getRunningHost(); ManagedObjectReference morParent = vmOwnerHost.getParentMor(); HashMap<String, Integer> portInfo; if (morParent.getType().equalsIgnoreCase("ClusterComputeResource")) { ClusterMO clusterMo = new ClusterMO(vmOwnerHost.getContext(), morParent); portInfo = clusterMo.getVmVncPortsOnCluster(); } else { portInfo = vmOwnerHost.getVmVncPortsOnHost(); } // allocate first at 5900 - 5964 range Collection<Integer> existingPorts = portInfo.values(); int val = random.nextInt(maxVncPorts); int startVal = val; do { if (!existingPorts.contains(5900 + val)) { vncPort = 5900 + val; break; } val = (++val) % maxVncPorts; } while (val != startVal); if (vncPort == 0) { s_logger.info( "we've run out of range for ports between 5900-5964 for the cluster, we will try port range at 59000-60000"); Pair<Integer, Integer> additionalRange = mgr.getAddiionalVncPortRange(); maxVncPorts = additionalRange.second(); val = random.nextInt(maxVncPorts); startVal = val; do { if (!existingPorts.contains(additionalRange.first() + val)) { vncPort = additionalRange.first() + val; break; } val = (++val) % maxVncPorts; } while (val != startVal); } if (vncPort == 0) { throw new Exception("Unable to find an available VNC port on host"); } if (s_logger.isInfoEnabled()) { s_logger.info("Configure VNC port for VM " + vmName + ", port: " + vncPort + ", host: " + vmOwnerHost.getHyperHostName()); } return VmwareHelper.composeVncOptions(optionsToMerge, true, vncPassword, vncPort, keyboardLayout); } finally { try { mgr.endExclusiveOperation(); } catch (Throwable e) { assert (false); s_logger.error("Unexpected exception ", e); } } }
From source file:es.pode.buscar.negocio.buscar.servicios.SrvBuscarServiceImpl.java
/** * @see es.pode.buscar.negocio.servicios.SrvBuscarServiceBase#handleBusquedaFederadaLocal(es.pode.buscar.negocio.servicios.ParametrosBusquedaAvanzadaVO) * @param ParametrosBusquedaAvanzadaVO Este VO alberga los parametros que configuran la busqueda avanzada * @return DocumentosVO Representa los resultados de la busqueda avanzada en todos los nodos */// w ww . j ava 2 s. c o m protected DocumentosVO handleBusquedaFederadaLocal(ParametrosBusquedaAvanzadaVO parametros) throws Exception { if (logger.isDebugEnabled()) logger.debug("SrvBuscarServiceImpl - handleBusquedaFederadaLocal : Comienzo"); List<DocumentosVO> documentos = new ArrayList<DocumentosVO>(); List<String> sugerencias = new ArrayList<String>(); HashMap<String, TaxonVO> tesauros = new HashMap<String, TaxonVO>(); boolean existenResultados = false; List<NodoVO> comunidades = obtenerComunidades(parametros.getComunidadesSeleccionadas()); NodoVO nodoComunidadPeticion = new NodoVO(); int numeroSugerencias = 0; int numeroTesauros = 0; nodoComunidadPeticion.setNodo(LOCALHOST); nodoComunidadPeticion.setUrlWS(LOCALHOST); nodoComunidadPeticion.setUrl(LOCALHOST); nodoComunidadPeticion.setPuerto(props.getProperty("puertoFederada")); comunidades.add(comunidades.get(0)); comunidades.set(0, nodoComunidadPeticion); if (parametros.getNumeroResultados() != null && parametros.getNumeroResultados().intValue() != -1) parametros.setNumeroResultados(Integer.valueOf(parametros.getNumeroResultados().intValue() / (comunidades.size() < 5 ? 5 : comunidades.size()))); DocumentosVO[] documents = MultiSearcher.searchDocuments(parametros, comunidades, props.getProperty("srvFederada"), Integer.parseInt(props.getProperty("maxWaitThread")), Integer.parseInt(props.getProperty("maxWaitPool"))); for (int i = 0; i < documents.length; i++) { if (documents[i] != null && documents[i].getResultados() != null && documents[i].getResultados().length > 0) { if (logger.isDebugEnabled()) logger.debug("SrvBuscarServiceImpl - handleBusquedaFederadaLocal: " + documents[i].getResultados().length + " docuemntos para =" + comunidades.get(i).toString()); existenResultados = true; documentos.add(documents[i]); } if (documents[i] != null && documents[i].getSugerencias() != null && documents[i].getSugerencias().length > 0) { if (logger.isDebugEnabled()) logger.debug("SrvBuscarServiceImpl - handleBusquedaFederadaLocal: " + documents[i].getSugerencias().length + " sugerencias para =" + comunidades.get(i).toString()); for (int j = 0; j < documents[i].getSugerencias().length && Integer.parseInt(props.getProperty("numero_sugerencias")) >= numeroSugerencias; j++) { if (!sugerencias.contains(documents[i].getSugerencias()[j])) { sugerencias.add(documents[i].getSugerencias()[j]); numeroSugerencias++; } } } if (documents[i] != null && documents[i].getTesauros() != null && documents[i].getTesauros().length > 0) { if (logger.isDebugEnabled()) logger.debug("SrvBuscarServiceImpl - handleBusquedaFederadaLocal: " + documents[i].getTesauros().length + " tesauros para =" + comunidades.get(i).toString()); for (int j = 0; j < documents[i].getTesauros().length && Integer.parseInt(props.getProperty("numero_tesauros")) >= numeroTesauros; j++) { if (!tesauros.containsKey(documents[i].getTesauros()[j].getNombre())) { tesauros.put(documents[i].getTesauros()[j].getNombre(), documents[i].getTesauros()[j]); numeroTesauros++; } } } } if (logger.isDebugEnabled()) logger.debug( "SrvBuscarServiceImpl - handleBusquedaFederadaLocal :Se ordenan resultados o sugerencias y se devuelve resultado."); DocumentosVO documentosSugerenciasTesauros = new DocumentosVO(); if ((documentos != null) && (documentos.size() > 0) && existenResultados) { // 16/11/2010 Fernando Garcia // Default sorting of Lucene is enough // original line //DocumentosVO resultadosOrdenados= ordenarResultados(documentos); DocumentosVO resultadosOrdenados = documentos.get(0); documentosSugerenciasTesauros.setNumDocumentosIndice(resultadosOrdenados.getNumDocumentosIndice()); documentosSugerenciasTesauros.setNumeroResultados(resultadosOrdenados.getNumeroResultados()); documentosSugerenciasTesauros.setResultados(resultadosOrdenados.getResultados()); documentosSugerenciasTesauros.setTotalResultados(resultadosOrdenados.getTotalResultados()); } if (sugerencias != null && sugerencias.size() > 0) { Collections.sort(sugerencias); documentosSugerenciasTesauros.setSugerencias(sugerencias.toArray(new String[0])); } else documentosSugerenciasTesauros.setSugerencias(new String[] {}); if (tesauros != null && tesauros.size() > 0) { List<TaxonVO> tesaurosOrdenados = new ArrayList<TaxonVO>(tesauros.values()); Collections.sort(tesaurosOrdenados, new TaxonNombreComparator()); documentosSugerenciasTesauros.setTesauros(tesaurosOrdenados.toArray(new TaxonVO[0])); } else documentosSugerenciasTesauros .setTesauros(new es.pode.indexador.negocio.servicios.busqueda.TaxonVO[] {}); return documentosSugerenciasTesauros; }
From source file:org.dasein.cloud.ibm.sce.compute.vm.SCEVirtualMachine.java
@Override public Iterable<VirtualMachineProduct> listProducts(Architecture architecture) throws InternalException, CloudException { if (products == null) { ProviderContext ctx = provider.getContext(); if (ctx == null) { throw new SCEConfigException("No context was configured for this request"); }//from www . j a v a 2s . co m SCEMethod method = new SCEMethod(provider); Document xml = method.getAsXML("offerings/image"); if (xml == null) { return Collections.emptyList(); } HashMap<String, VirtualMachineProduct> t = new HashMap<String, VirtualMachineProduct>(); HashMap<String, VirtualMachineProduct> s = new HashMap<String, VirtualMachineProduct>(); NodeList items = xml.getElementsByTagName("Image"); for (int i = 0; i < items.getLength(); i++) { HashMap<String, VirtualMachineProduct> prdMap = new HashMap<String, VirtualMachineProduct>(); NodeList attrs = items.item(i).getChildNodes(); Architecture a = null; for (int j = 0; j < attrs.getLength(); j++) { Node attr = attrs.item(j); if (attr.getNodeName().equalsIgnoreCase("Architecture") && attr.hasChildNodes()) { String val = attr.getFirstChild().getNodeValue().trim(); if (val.equals("i386")) { a = Architecture.I32; } else if (val.startsWith("x86")) { a = Architecture.I64; } else { System.out.println("DEBUG: Unknown architecture: " + val); a = Architecture.I32; } } else if (attr.getNodeName().equalsIgnoreCase("SupportedInstanceTypes") && attr.hasChildNodes()) { NodeList types = attr.getChildNodes(); for (int k = 0; k < types.getLength(); k++) { Node type = types.item(k); if (type.getNodeName().equalsIgnoreCase("InstanceType") && type.hasChildNodes()) { VirtualMachineProduct prd = new VirtualMachineProduct(); NodeList nodes = type.getChildNodes(); for (int l = 0; l < nodes.getLength(); l++) { Node node = nodes.item(l); if (node.getNodeName().equals("ID") && node.hasChildNodes()) { prd.setProviderProductId(node.getFirstChild().getNodeValue().trim()); } else if (node.getNodeName().equals("Label") && node.hasChildNodes()) { prd.setName(node.getFirstChild().getNodeValue().trim()); } else if (node.getNodeName().equals("Detail") && node.hasChildNodes()) { prd.setDescription(node.getFirstChild().getNodeValue().trim()); } } if (prd.getProviderProductId() != null) { String[] parts = prd.getProviderProductId().split("/"); if (parts.length == 3) { String[] sub = parts[0].split("\\."); if (sub.length > 0) { parts[0] = sub[sub.length - 1]; } try { prd.setCpuCount(Integer.parseInt(parts[0])); } catch (NumberFormatException ignore) { // ignore } try { prd.setRamSize(new Storage<Megabyte>(Integer.parseInt(parts[1]), Storage.MEGABYTE)); } catch (NumberFormatException ignore) { // ignore } try { int idx = parts[2].indexOf("*"); if (idx < 1) { prd.setRootVolumeSize(new Storage<Gigabyte>( Integer.parseInt(parts[2]), Storage.GIGABYTE)); } else { prd.setRootVolumeSize(new Storage<Gigabyte>( Integer.parseInt(parts[2].substring(0, idx)), Storage.GIGABYTE)); } } catch (NumberFormatException ignore) { // ignore } } prdMap.put(prd.getProviderProductId(), prd); } } } } } if (a != null) { if (a.equals(Architecture.I32)) { t.putAll(prdMap); } else if (a.equals(Architecture.I64)) { s.putAll(prdMap); } } } HashMap<Architecture, Collection<VirtualMachineProduct>> tmp = new HashMap<Architecture, Collection<VirtualMachineProduct>>(); tmp.put(Architecture.I32, Collections.unmodifiableCollection(t.values())); tmp.put(Architecture.I64, Collections.unmodifiableCollection(s.values())); products = tmp; } return products.get(architecture); }
From source file:com.truledger.client.Client.java
/** * Get a sorted list of all the assets in balances for the current account * @return//from w w w . jav a 2 s .c o m * @throws ClientException */ public Asset[] getAssets() throws ClientException { if (serverid == null) return null; String key = this.userBalanceKey(); ClientDB.AccountDB acctDB = db.getAccountDB(); String[] accts = acctDB.contents(key); HashMap<String, Asset> assets = new HashMap<String, Asset>(accts.length); for (String acct : accts) { for (String assetid : acctDB.contents(key, acct)) { if (assets.get(assetid) == null) { Asset asset = this.getAsset(assetid); if (asset != null) assets.put(assetid, asset); } } } Asset[] res = new Asset[assets.size()]; int i = 0; for (Asset asset : assets.values()) res[i++] = asset; Arrays.sort(res, new Comparator<Asset>() { public int compare(Asset a1, Asset a2) { return assetCompare(a1, a2); } }); return res; }