List of usage examples for java.util List listIterator
ListIterator<E> listIterator();
From source file:org.apache.cloudstack.storage.image.TemplateServiceImpl.java
@Override public void handleTemplateSync(DataStore store) { if (store == null) { s_logger.warn("Huh? image store is null"); return;//from ww w . j a v a2s . com } long storeId = store.getId(); // add lock to make template sync for a data store only be done once String lockString = "templatesync.storeId:" + storeId; GlobalLock syncLock = GlobalLock.getInternLock(lockString); try { if (syncLock.lock(3)) { try { Long zoneId = store.getScope().getScopeId(); Map<String, TemplateProp> templateInfos = listTemplate(store); if (templateInfos == null) { return; } Set<VMTemplateVO> toBeDownloaded = new HashSet<VMTemplateVO>(); List<VMTemplateVO> allTemplates = null; if (zoneId == null) { // region wide store allTemplates = _templateDao.listByState(VirtualMachineTemplate.State.Active, VirtualMachineTemplate.State.NotUploaded, VirtualMachineTemplate.State.UploadInProgress); } else { // zone wide store allTemplates = _templateDao.listInZoneByState(zoneId, VirtualMachineTemplate.State.Active, VirtualMachineTemplate.State.NotUploaded, VirtualMachineTemplate.State.UploadInProgress); } List<VMTemplateVO> rtngTmplts = _templateDao.listAllSystemVMTemplates(); List<VMTemplateVO> defaultBuiltin = _templateDao.listDefaultBuiltinTemplates(); if (rtngTmplts != null) { for (VMTemplateVO rtngTmplt : rtngTmplts) { if (!allTemplates.contains(rtngTmplt)) { allTemplates.add(rtngTmplt); } } } if (defaultBuiltin != null) { for (VMTemplateVO builtinTmplt : defaultBuiltin) { if (!allTemplates.contains(builtinTmplt)) { allTemplates.add(builtinTmplt); } } } for (Iterator<VMTemplateVO> iter = allTemplates.listIterator(); iter.hasNext();) { VMTemplateVO child_template = iter.next(); if (child_template.getParentTemplateId() != null) { String uniqueName = child_template.getUniqueName(); if (templateInfos.containsKey(uniqueName)) { templateInfos.remove(uniqueName); } iter.remove(); } } toBeDownloaded.addAll(allTemplates); final StateMachine2<VirtualMachineTemplate.State, VirtualMachineTemplate.Event, VirtualMachineTemplate> stateMachine = VirtualMachineTemplate.State .getStateMachine(); for (VMTemplateVO tmplt : allTemplates) { String uniqueName = tmplt.getUniqueName(); TemplateDataStoreVO tmpltStore = _vmTemplateStoreDao.findByStoreTemplate(storeId, tmplt.getId()); if (templateInfos.containsKey(uniqueName)) { TemplateProp tmpltInfo = templateInfos.remove(uniqueName); toBeDownloaded.remove(tmplt); if (tmpltStore != null) { s_logger.info("Template Sync found " + uniqueName + " already in the image store"); if (tmpltStore.getDownloadState() != Status.DOWNLOADED) { tmpltStore.setErrorString(""); } if (tmpltInfo.isCorrupted()) { tmpltStore.setDownloadState(Status.DOWNLOAD_ERROR); String msg = "Template " + tmplt.getName() + ":" + tmplt.getId() + " is corrupted on secondary storage " + tmpltStore.getId(); tmpltStore.setErrorString(msg); s_logger.info(msg); _alertMgr.sendAlert(AlertManager.AlertType.ALERT_TYPE_UPLOAD_FAILED, zoneId, null, msg, msg); if (tmplt.getState() == VirtualMachineTemplate.State.NotUploaded || tmplt.getState() == VirtualMachineTemplate.State.UploadInProgress) { s_logger.info("Template Sync found " + uniqueName + " on image store " + storeId + " uploaded using SSVM as corrupted, marking it as failed"); tmpltStore.setState(State.Failed); try { stateMachine.transitTo(tmplt, VirtualMachineTemplate.Event.OperationFailed, null, _templateDao); } catch (NoTransitionException e) { s_logger.error("Unexpected state transition exception for template " + tmplt.getName() + ". Details: " + e.getMessage()); } } else if (tmplt.getUrl() == null) { msg = "Private template (" + tmplt + ") with install path " + tmpltInfo.getInstallPath() + " is corrupted, please check in image store: " + tmpltStore.getDataStoreId(); s_logger.warn(msg); } else { s_logger.info("Removing template_store_ref entry for corrupted template " + tmplt.getName()); _vmTemplateStoreDao.remove(tmpltStore.getId()); toBeDownloaded.add(tmplt); } } else { if (tmpltStore.getDownloadState() != Status.DOWNLOADED) { String etype = EventTypes.EVENT_TEMPLATE_CREATE; if (tmplt.getFormat() == ImageFormat.ISO) { etype = EventTypes.EVENT_ISO_CREATE; } if (zoneId != null) { UsageEventUtils.publishUsageEvent(etype, tmplt.getAccountId(), zoneId, tmplt.getId(), tmplt.getName(), null, null, tmpltInfo.getPhysicalSize(), tmpltInfo.getSize(), VirtualMachineTemplate.class.getName(), tmplt.getUuid()); } } tmpltStore.setDownloadPercent(100); tmpltStore.setDownloadState(Status.DOWNLOADED); tmpltStore.setState(ObjectInDataStoreStateMachine.State.Ready); tmpltStore.setInstallPath(tmpltInfo.getInstallPath()); tmpltStore.setSize(tmpltInfo.getSize()); tmpltStore.setPhysicalSize(tmpltInfo.getPhysicalSize()); tmpltStore.setLastUpdated(new Date()); // update size in vm_template table VMTemplateVO tmlpt = _templateDao.findById(tmplt.getId()); tmlpt.setSize(tmpltInfo.getSize()); _templateDao.update(tmplt.getId(), tmlpt); if (tmplt.getState() == VirtualMachineTemplate.State.NotUploaded || tmplt.getState() == VirtualMachineTemplate.State.UploadInProgress) { try { stateMachine.transitTo(tmplt, VirtualMachineTemplate.Event.OperationSucceeded, null, _templateDao); } catch (NoTransitionException e) { s_logger.error("Unexpected state transition exception for template " + tmplt.getName() + ". Details: " + e.getMessage()); } } // Skipping limit checks for SYSTEM Account and for the templates created from volumes or snapshots // which already got checked and incremented during createTemplate API call. if (tmpltInfo.getSize() > 0 && tmplt.getAccountId() != Account.ACCOUNT_ID_SYSTEM && tmplt.getUrl() != null) { long accountId = tmplt.getAccountId(); try { _resourceLimitMgr.checkResourceLimit(_accountMgr.getAccount(accountId), com.cloud.configuration.Resource.ResourceType.secondary_storage, tmpltInfo.getSize() - UriUtils.getRemoteSize(tmplt.getUrl())); } catch (ResourceAllocationException e) { s_logger.warn(e.getMessage()); _alertMgr.sendAlert( AlertManager.AlertType.ALERT_TYPE_RESOURCE_LIMIT_EXCEEDED, zoneId, null, e.getMessage(), e.getMessage()); } finally { _resourceLimitMgr.recalculateResourceCount(accountId, _accountMgr.getAccount(accountId).getDomainId(), com.cloud.configuration.Resource.ResourceType.secondary_storage .getOrdinal()); } } } _vmTemplateStoreDao.update(tmpltStore.getId(), tmpltStore); } else { tmpltStore = new TemplateDataStoreVO(storeId, tmplt.getId(), new Date(), 100, Status.DOWNLOADED, null, null, null, tmpltInfo.getInstallPath(), tmplt.getUrl()); tmpltStore.setSize(tmpltInfo.getSize()); tmpltStore.setPhysicalSize(tmpltInfo.getPhysicalSize()); tmpltStore.setDataStoreRole(store.getRole()); _vmTemplateStoreDao.persist(tmpltStore); // update size in vm_template table VMTemplateVO tmlpt = _templateDao.findById(tmplt.getId()); tmlpt.setSize(tmpltInfo.getSize()); _templateDao.update(tmplt.getId(), tmlpt); associateTemplateToZone(tmplt.getId(), zoneId); String etype = EventTypes.EVENT_TEMPLATE_CREATE; if (tmplt.getFormat() == ImageFormat.ISO) { etype = EventTypes.EVENT_ISO_CREATE; } UsageEventUtils.publishUsageEvent(etype, tmplt.getAccountId(), zoneId, tmplt.getId(), tmplt.getName(), null, null, tmpltInfo.getPhysicalSize(), tmpltInfo.getSize(), VirtualMachineTemplate.class.getName(), tmplt.getUuid()); } } else if (tmplt.getState() == VirtualMachineTemplate.State.NotUploaded || tmplt.getState() == VirtualMachineTemplate.State.UploadInProgress) { s_logger.info("Template Sync did not find " + uniqueName + " on image store " + storeId + " uploaded using SSVM, marking it as failed"); toBeDownloaded.remove(tmplt); tmpltStore.setDownloadState(Status.DOWNLOAD_ERROR); String msg = "Template " + tmplt.getName() + ":" + tmplt.getId() + " is corrupted on secondary storage " + tmpltStore.getId(); tmpltStore.setErrorString(msg); tmpltStore.setState(State.Failed); _vmTemplateStoreDao.update(tmpltStore.getId(), tmpltStore); try { stateMachine.transitTo(tmplt, VirtualMachineTemplate.Event.OperationFailed, null, _templateDao); } catch (NoTransitionException e) { s_logger.error("Unexpected state transition exception for template " + tmplt.getName() + ". Details: " + e.getMessage()); } } else if (tmplt.isDirectDownload()) { s_logger.info("Template " + tmplt.getName() + ":" + tmplt.getId() + " is marked for direct download, discarding it for download on image stores"); toBeDownloaded.remove(tmplt); } else { s_logger.info("Template Sync did not find " + uniqueName + " on image store " + storeId + ", may request download based on available hypervisor types"); if (tmpltStore != null) { if (_storeMgr.isRegionStore(store) && tmpltStore .getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOADED && tmpltStore.getState() == State.Ready && tmpltStore.getInstallPath() == null) { s_logger.info( "Keep fake entry in template store table for migration of previous NFS to object store"); } else { s_logger.info("Removing leftover template " + uniqueName + " entry from template store table"); // remove those leftover entries _vmTemplateStoreDao.remove(tmpltStore.getId()); } } } } if (toBeDownloaded.size() > 0) { /* Only download templates whose hypervirsor type is in the zone */ List<HypervisorType> availHypers = _clusterDao.getAvailableHypervisorInZone(zoneId); if (availHypers.isEmpty()) { /* * This is for cloudzone, local secondary storage resource * started before cluster created */ availHypers.add(HypervisorType.KVM); } /* Baremetal need not to download any template */ availHypers.remove(HypervisorType.BareMetal); availHypers.add(HypervisorType.None); // bug 9809: resume ISO // download. for (VMTemplateVO tmplt : toBeDownloaded) { if (tmplt.getUrl() == null) { // If url is null, skip downloading s_logger.info("Skip downloading template " + tmplt.getUniqueName() + " since no url is specified."); continue; } // if this is private template, skip sync to a new image store if (!tmplt.isPublicTemplate() && !tmplt.isFeatured() && tmplt.getTemplateType() != TemplateType.SYSTEM) { s_logger.info("Skip sync downloading private template " + tmplt.getUniqueName() + " to a new image store"); continue; } // if this is a region store, and there is already an DOWNLOADED entry there without install_path information, which // means that this is a duplicate entry from migration of previous NFS to staging. if (_storeMgr.isRegionStore(store)) { TemplateDataStoreVO tmpltStore = _vmTemplateStoreDao.findByStoreTemplate(storeId, tmplt.getId()); if (tmpltStore != null && tmpltStore .getDownloadState() == VMTemplateStorageResourceAssoc.Status.DOWNLOADED && tmpltStore.getState() == State.Ready && tmpltStore.getInstallPath() == null) { s_logger.info( "Skip sync template for migration of previous NFS to object store"); continue; } } if (availHypers.contains(tmplt.getHypervisorType())) { s_logger.info("Downloading template " + tmplt.getUniqueName() + " to image store " + store.getName()); associateTemplateToZone(tmplt.getId(), zoneId); TemplateInfo tmpl = _templateFactory.getTemplate(tmplt.getId(), store); TemplateOpContext<TemplateApiResult> context = new TemplateOpContext<>(null, (TemplateObject) tmpl, null); AsyncCallbackDispatcher<TemplateServiceImpl, TemplateApiResult> caller = AsyncCallbackDispatcher .create(this); caller.setCallback(caller.getTarget().createTemplateAsyncCallBack(null, null)); caller.setContext(context); createTemplateAsync(tmpl, store, caller); } else { s_logger.info("Skip downloading template " + tmplt.getUniqueName() + " since current data center does not have hypervisor " + tmplt.getHypervisorType().toString()); } } } for (String uniqueName : templateInfos.keySet()) { TemplateProp tInfo = templateInfos.get(uniqueName); if (_tmpltMgr.templateIsDeleteable(tInfo.getId())) { // we cannot directly call deleteTemplateSync here to reuse delete logic since in this case db does not have this template at all. TemplateObjectTO tmplTO = new TemplateObjectTO(); tmplTO.setDataStore(store.getTO()); tmplTO.setPath(tInfo.getInstallPath()); tmplTO.setId(tInfo.getId()); DeleteCommand dtCommand = new DeleteCommand(tmplTO); EndPoint ep = _epSelector.select(store); Answer answer = null; if (ep == null) { String errMsg = "No remote endpoint to send command, check if host or ssvm is down?"; s_logger.error(errMsg); answer = new Answer(dtCommand, false, errMsg); } else { answer = ep.sendMessage(dtCommand); } if (answer == null || !answer.getResult()) { s_logger.info("Failed to deleted template at store: " + store.getName()); } else { String description = "Deleted template " + tInfo.getTemplateName() + " on secondary storage " + storeId; s_logger.info(description); } } } } finally { syncLock.unlock(); } } else { s_logger.info("Couldn't get global lock on " + lockString + ", another thread may be doing template sync on data store " + storeId + " now."); } } finally { syncLock.releaseRef(); } }
From source file:org.apereo.portal.tools.dbloader.HibernateDbLoader.java
@Override public void process(DbLoaderConfig configuration) throws ParserConfigurationException, SAXException, IOException { final String scriptFile = configuration.getScriptFile(); final List<String> script; if (scriptFile == null) { script = null;/*from w w w . j a v a 2 s .c o m*/ } else { script = new LinkedList<String>(); } final ITableDataProvider tableData = this.loadTables(configuration, dialect); //Handle table drop/create if (configuration.isDropTables() || configuration.isCreateTables()) { //Load Table object model final Map<String, Table> tables = tableData.getTables(); final Mapping mapping = this.configuration.buildMapping(); final String defaultCatalog = this.configuration.getProperty(Environment.DEFAULT_CATALOG); final String defaultSchema = this.configuration.getProperty(Environment.DEFAULT_SCHEMA); final Map<String, DataAccessException> failedSql = new LinkedHashMap<String, DataAccessException>(); //Generate and execute drop table scripts if (configuration.isDropTables()) { final List<String> dropScript = this.dropScript(tables.values(), dialect, defaultCatalog, defaultSchema); if (script == null) { this.logger.info("Dropping existing tables"); for (final String sql : dropScript) { this.logger.info(sql); try { jdbcOperations.update(sql); } catch (NonTransientDataAccessResourceException dae) { throw dae; } catch (DataAccessException dae) { failedSql.put(sql, dae); } } } else { script.addAll(dropScript); } } //Log any drop/create statements that failed for (final Map.Entry<String, DataAccessException> failedSqlEntry : failedSql.entrySet()) { this.logger.warn( "'" + failedSqlEntry.getKey() + "' failed to execute due to " + failedSqlEntry.getValue()); } //Generate and execute create table scripts if (configuration.isCreateTables()) { final List<String> createScript = this.createScript(tables.values(), dialect, mapping, defaultCatalog, defaultSchema); if (script == null) { this.logger.info("Creating tables"); for (final String sql : createScript) { this.logger.info(sql); jdbcOperations.update(sql); } } else { script.addAll(createScript); } } } //Perform database population if (script == null && configuration.isPopulateTables()) { this.logger.info("Populating database"); final Map<String, Map<String, Integer>> tableColumnTypes = tableData.getTableColumnTypes(); this.populateTables(configuration, tableColumnTypes); } //Write out the script file if (script != null) { for (final ListIterator<String> iterator = script.listIterator(); iterator.hasNext();) { final String sql = iterator.next(); iterator.set(sql + ";"); } final File outputFile = new File(scriptFile); FileUtils.writeLines(outputFile, script); this.logger.info("Saved DDL to: " + outputFile.getAbsolutePath()); } }
From source file:org.apache.fop.layoutmgr.inline.InlineLayoutManager.java
/** {@inheritDoc} */ @Override // CSOK: MethodLength public List getNextKnuthElements(LayoutContext context, int alignment) { LayoutManager curLM;//from ww w . j ava 2s . c om // the list returned by child LM List<KnuthSequence> returnedList; // the list which will be returned to the parent LM List<KnuthSequence> returnList = new LinkedList<KnuthSequence>(); KnuthSequence lastSequence = null; if (fobj instanceof Title) { alignmentContext = new AlignmentContext(font, lineHeight.getOptimum(this).getLength().getValue(this), context.getWritingMode()); } else { alignmentContext = new AlignmentContext(font, lineHeight.getOptimum(this).getLength().getValue(this), alignmentAdjust, alignmentBaseline, baselineShift, dominantBaseline, context.getAlignmentContext()); } childLC = new LayoutContext(context); childLC.setAlignmentContext(alignmentContext); if (context.startsNewArea()) { // First call to this LM in new parent "area", but this may // not be the first area created by this inline if (getSpaceStart() != null) { context.getLeadingSpace().addSpace(new SpaceVal(getSpaceStart(), this)); } } StringBuffer trace = new StringBuffer("InlineLM:"); // We'll add the border to the first inline sequence created. // This flag makes sure we do it only once. boolean borderAdded = false; if (borderProps != null) { childLC.setLineStartBorderAndPaddingWidth(context.getLineStartBorderAndPaddingWidth() + borderProps.getPaddingStart(true, this) + borderProps.getBorderStartWidth(true)); childLC.setLineEndBorderAndPaddingWidth(context.getLineEndBorderAndPaddingWidth() + borderProps.getPaddingEnd(true, this) + borderProps.getBorderEndWidth(true)); } while ((curLM = getChildLM()) != null) { if (!(curLM instanceof InlineLevelLayoutManager)) { // A block LM // Leave room for start/end border and padding if (borderProps != null) { childLC.setRefIPD(childLC.getRefIPD() - borderProps.getPaddingStart(lastChildLM != null, this) - borderProps.getBorderStartWidth(lastChildLM != null) - borderProps.getPaddingEnd(hasNextChildLM(), this) - borderProps.getBorderEndWidth(hasNextChildLM())); } } // get KnuthElements from curLM returnedList = curLM.getNextKnuthElements(childLC, alignment); if (returnList.isEmpty() && childLC.isKeepWithPreviousPending()) { childLC.clearKeepWithPreviousPending(); } if (returnedList == null || returnedList.isEmpty()) { // curLM returned null or an empty list, because it finished; // just iterate once more to see if there is another child continue; } if (curLM instanceof InlineLevelLayoutManager) { context.clearKeepWithNextPending(); // "wrap" the Position stored in each element of returnedList ListIterator seqIter = returnedList.listIterator(); while (seqIter.hasNext()) { KnuthSequence sequence = (KnuthSequence) seqIter.next(); sequence.wrapPositions(this); } int insertionStartIndex = 0; if (lastSequence != null && lastSequence.appendSequenceOrClose(returnedList.get(0))) { insertionStartIndex = 1; } // add border and padding to the first complete sequence of this LM if (!borderAdded && !returnedList.isEmpty()) { addKnuthElementsForBorderPaddingStart(returnedList.get(0)); borderAdded = true; } for (Iterator<KnuthSequence> iter = returnedList.listIterator(insertionStartIndex); iter .hasNext();) { returnList.add(iter.next()); } } else { // A block LM BlockKnuthSequence sequence = new BlockKnuthSequence(returnedList); sequence.wrapPositions(this); boolean appended = false; if (lastSequence != null) { if (lastSequence.canAppendSequence(sequence)) { BreakElement bk = new BreakElement(new Position(this), 0, context); boolean keepTogether = (mustKeepTogether() || context.isKeepWithNextPending() || childLC.isKeepWithPreviousPending()); appended = lastSequence.appendSequenceOrClose(sequence, keepTogether, bk); } else { lastSequence.endSequence(); } } if (!appended) { // add border and padding to the first complete sequence of this LM if (!borderAdded) { addKnuthElementsForBorderPaddingStart(sequence); borderAdded = true; } returnList.add(sequence); } // propagate and clear context.updateKeepWithNextPending(childLC.getKeepWithNextPending()); childLC.clearKeepsPending(); } lastSequence = ListUtil.getLast(returnList); lastChildLM = curLM; // the context used to create this childLC above was applied a LayoutContext.SUPPRESS_BREAK_BEFORE // in the getNextChildElements() method of the parent BlockLayoutManger; as a consequence all // line breaks in blocks nested inside the inline associated with this ILM are being supressed; // here we revert that supression; we do not need to do that for the first element since that // is handled by the getBreakBefore() method of the wrapping BlockStackingLayoutManager. // Note: this fix seems to work but is far from being the ideal way to do this childLC.setFlags(LayoutContext.SUPPRESS_BREAK_BEFORE, false); } if (lastSequence != null) { addKnuthElementsForBorderPaddingEnd(lastSequence); } setFinished(true); log.trace(trace); if (returnList.isEmpty()) { /* * if the FO itself is empty, but has an id specified * or associated fo:markers, then we still need a dummy * sequence to register its position in the area tree */ if (fobj.hasId() || fobj.hasMarkers()) { InlineKnuthSequence emptySeq = new InlineKnuthSequence(); emptySeq.add(new KnuthInlineBox(0, alignmentContext, notifyPos(getAuxiliaryPosition()), true)); returnList.add(emptySeq); } } return returnList.isEmpty() ? null : returnList; }
From source file:net.sf.jasperreports.engine.util.JRApiWriter.java
/** * Outputs the XML representation of a subdataset run object. * /*ww w.j av a 2 s. co m*/ * @param datasetRun the subdataset run */ public void writeDatasetRun(JRDatasetRun datasetRun, String parentName) { if (datasetRun != null) { String runName = parentName + "Run"; write("JRDesignDatasetRun " + runName + " = new JRDesignDatasetRun();\n"); write(runName + ".setDatasetName(\"{0}\");\n", JRStringUtil.escapeJavaStringLiteral(datasetRun.getDatasetName())); writeExpression(datasetRun.getParametersMapExpression(), runName, "ParametersMapExpression"); JRDatasetParameter[] parameters = datasetRun.getParameters(); if (parameters != null && parameters.length > 0) { for (int i = 0; i < parameters.length; i++) { writeDatasetParameter(parameters[i], runName, runName + "Parameter" + i); } } writeExpression(datasetRun.getConnectionExpression(), runName, "ConnectionExpression"); writeExpression(datasetRun.getDataSourceExpression(), runName, "DataSourceExpression"); List<ReturnValue> returnValues = datasetRun.getReturnValues(); if (returnValues != null && !returnValues.isEmpty()) { for (ListIterator<ReturnValue> it = returnValues.listIterator(); it.hasNext();) { ReturnValue returnValue = it.next(); String returnValueVarName = runName + "ReturnValue" + it.previousIndex(); writeReturnValue(returnValue, returnValueVarName); write(runName + ".addReturnValue(" + returnValueVarName + ");\n"); } } write(parentName + ".setDatasetRun(" + runName + ");\n"); flush(); } }
From source file:net.sf.jasperreports.engine.util.JRApiWriter.java
/** * *//*ww w . j a v a 2s . com*/ private void writeBand(JRBand band, String bandName) { if (band != null) { write("//band name = " + bandName + "\n\n"); write("JRDesignBand " + bandName + " = new JRDesignBand();\n"); write(bandName + ".setHeight({0, number, #});\n", band.getHeight()); write(bandName + ".setSplitType({0});\n", band.getSplitTypeValue()); writeExpression(band.getPrintWhenExpression(), bandName, "PrintWhenExpression"); writeChildElements(band, bandName); List<ExpressionReturnValue> returnValues = band.getReturnValues(); if (returnValues != null && !returnValues.isEmpty()) { for (ListIterator<ExpressionReturnValue> it = returnValues.listIterator(); it.hasNext();) { ExpressionReturnValue returnValue = it.next(); String returnValueVarName = bandName + "ReturnValue" + it.previousIndex(); writeReturnValue(returnValue, returnValueVarName); write(bandName + ".addReturnValue(" + returnValueVarName + ");\n"); } } flush(); } }
From source file:com.ut.healthelink.controller.HealtheWebController.java
/** * The 'setOutboundFormFields' will create and populate the form field object * * @param formfields The list of form fields * @param records The values of the form fields to populate with. * * @return This function will return a list of transactionRecords fields with the correct data * * @throws NoSuchMethodException// ww w .j a v a2s . co m */ public List<transactionRecords> setOutboundFormFields(List<configurationFormFields> formfields, transactionInRecords records, int configId, boolean readOnly, int orgId) throws NoSuchMethodException { List<transactionRecords> fields = new ArrayList<transactionRecords>(); //we can map the process status so we only have to query once List validationTypeList = messagetypemanager.getValidationTypes(); Map<Integer, String> vtMap = new HashMap<Integer, String>(); for (ListIterator iter = validationTypeList.listIterator(); iter.hasNext();) { Object[] row = (Object[]) iter.next(); vtMap.put(Integer.valueOf(String.valueOf(row[0])), String.valueOf(row[1])); } for (configurationFormFields formfield : formfields) { transactionRecords field = new transactionRecords(); field.setfieldNo(formfield.getFieldNo()); field.setrequired(formfield.getRequired()); field.setsaveToTable(formfield.getsaveToTableName()); field.setsaveToTableCol(formfield.getsaveToTableCol()); field.setfieldLabel(formfield.getFieldLabel()); field.setreadOnly(readOnly); field.setfieldValue(null); /* Get the pre-populated values */ String tableName = formfield.getautoPopulateTableName(); String tableCol = formfield.getautoPopulateTableCol(); /* Get the validation */ if (formfield.getValidationType() > 1) { field.setvalidation(vtMap.get(formfield.getValidationType())); } if (records != null) { String colName = new StringBuilder().append("f").append(formfield.getFieldNo()).toString(); try { field.setfieldValue(BeanUtils.getProperty(records, colName)); } catch (IllegalAccessException ex) { Logger.getLogger(HealtheWebController.class.getName()).log(Level.SEVERE, null, ex); } catch (InvocationTargetException ex) { Logger.getLogger(HealtheWebController.class.getName()).log(Level.SEVERE, null, ex); } /* If autopopulate field is set make it read only */ if (!tableName.isEmpty() && !tableCol.isEmpty()) { field.setreadOnly(true); } } else if (orgId > 0) { if (!tableName.isEmpty() && !tableCol.isEmpty()) { field.setfieldValue(transactionInManager.getFieldValue(tableName, tableCol, "id", orgId)); } } if (configId > 0) { /* See if any fields have crosswalks associated to it */ List<fieldSelectOptions> fieldSelectOptions = transactionInManager .getFieldSelectOptions(formfield.getId(), configId); field.setfieldSelectOptions(fieldSelectOptions); } fields.add(field); } return fields; }
From source file:com.ut.healthelink.controller.HealtheWebController.java
/** * The 'setInboxFormFields' will create and populate the form field object * * @param formfields The list of form fields * @param records The values of the form fields to populate with. * * @return This function will return a list of transactionRecords fields with the correct data * * @throws NoSuchMethodException/* ww w .j av a2 s. c o m*/ */ public List<transactionRecords> setInboxFormFields(List<configurationFormFields> formfields, transactionOutRecords records, int configId, boolean readOnly, int transactionInId, int orgId) throws NoSuchMethodException { List<transactionRecords> fields = new ArrayList<transactionRecords>(); //we can map the process status so we only have to query once List validationTypeList = messagetypemanager.getValidationTypes(); Map<Integer, String> vtMap = new HashMap<Integer, String>(); for (ListIterator iter = validationTypeList.listIterator(); iter.hasNext();) { Object[] row = (Object[]) iter.next(); vtMap.put(Integer.valueOf(String.valueOf(row[0])), String.valueOf(row[1])); } for (configurationFormFields formfield : formfields) { transactionRecords field = new transactionRecords(); field.setfieldNo(formfield.getFieldNo()); field.setrequired(formfield.getRequired()); field.setsaveToTable(formfield.getsaveToTableName()); field.setsaveToTableCol(formfield.getsaveToTableCol()); field.setfieldLabel(formfield.getFieldLabel()); field.setreadOnly(readOnly); field.setfieldValue(null); /* Get the validation */ if (formfield.getValidationType() > 1) { field.setvalidation(vtMap.get(formfield.getValidationType())); } if (records != null) { String colName = new StringBuilder().append("f").append(formfield.getFieldNo()).toString(); try { field.setfieldValue(BeanUtils.getProperty(records, colName)); } catch (IllegalAccessException ex) { Logger.getLogger(HealtheWebController.class.getName()).log(Level.SEVERE, null, ex); } catch (InvocationTargetException ex) { Logger.getLogger(HealtheWebController.class.getName()).log(Level.SEVERE, null, ex); } } /* If records == null and an auto populate field is set for the field get the data from the table/col for the transaction */ else if (records == null && formfield.getautoPopulateTableName() != null && transactionInId > 0) { /* Get the pre-populated values */ String tableName = formfield.getautoPopulateTableName(); String tableCol = formfield.getautoPopulateTableCol(); if (!tableName.isEmpty() && !tableCol.isEmpty()) { field.setfieldValue(transactionInManager.getFieldValue(tableName, tableCol, "transactionInId", transactionInId)); field.setreadOnly(true); } } if (orgId > 0) { /* Get the pre-populated values */ String tableName = formfield.getautoPopulateTableName(); String tableCol = formfield.getautoPopulateTableCol(); if (!tableName.isEmpty() && !tableCol.isEmpty()) { field.setfieldValue(transactionInManager.getFieldValue(tableName, tableCol, "id", orgId)); } } if (configId > 0) { /* See if any fields have crosswalks associated to it */ List<fieldSelectOptions> fieldSelectOptions = transactionInManager .getFieldSelectOptions(formfield.getId(), configId); field.setfieldSelectOptions(fieldSelectOptions); } fields.add(field); } return fields; }
From source file:gov.nih.nci.evs.browser.utils.SearchUtils.java
protected float score(String text, List<String> keywords) { List<String> wordsToCompare = toScoreWords(text); float totalWords = wordsToCompare.size(); float matchScore = 0; float position = 0; for (Iterator<String> words = wordsToCompare.listIterator(); words.hasNext(); position++) { String word = words.next(); if (keywords.contains(word)) matchScore += ((position / 10) + 1); }/*from w ww . j a v a 2 s . c o m*/ return Math.max(0, 100 + (matchScore / totalWords * 100) - (totalWords * 2)); // Math.max(0, 100 + (matchScore / totalWords * 100) - (totalWords * 2)) // * (isPreferred ? 2 : 1); }
From source file:gov.nih.nci.evs.browser.utils.SearchUtils.java
/** * Returns a score providing a relative comparison of the given text against * a set of keywords./*from w w w . ja va2 s .c o m*/ * <p> * Currently the score is evaluated as a simple percentage based on number * of words in the first set that are also in the second, with minor * adjustment for order (matching later words given slightly higher weight, * anticipating often the subject of search will follow descriptive text). * Weight is also increased for shorter phrases (measured in # words) If the * text is indicated to be preferred, the score is doubled to promote * 'bubbling to the top'. * <p> * Ranking from the original search is available but not currently used in * the heuristic (tends to throw-off desired alphabetic groupings later). * * @param text * @param keywords * @param isPreferred * @param searchRank * @return The score; a higher value indicates a stronger match. */ protected float score(String text, List<String> keywords, boolean isPreferred, float searchRank) { List<String> wordsToCompare = toScoreWords(text); float totalWords = wordsToCompare.size(); float matchScore = 0; float position = 0; for (Iterator<String> words = wordsToCompare.listIterator(); words.hasNext(); position++) { String word = words.next(); if (keywords.contains(word)) matchScore += ((position / 10) + 1); } return Math.max(0, 100 + (matchScore / totalWords * 100) - (totalWords * 2)); // Math.max(0, 100 + (matchScore / totalWords * 100) - (totalWords * 2)) // * (isPreferred ? 2 : 1); }
From source file:gov.nih.nci.evs.browser.utils.SearchUtils.java
protected float score(String text, List<String> keywords, List<String> keyword_codes, String target, boolean fuzzy_match) { List<String> wordsToCompare = toScoreWords(text); float totalWords = wordsToCompare.size(); float matchScore = 0; float position = 0; //String s = ""; StringBuffer buf = new StringBuffer(); int k = 0;//from w ww . ja v a 2 s. co m for (Iterator<String> words = wordsToCompare.listIterator(); words.hasNext(); position++) { String word = words.next(); if (keywords.contains(word)) { // matchScore += ((position / 10) + 1); // matchScore = matchScore * 2; matchScore = matchScore + (float) 10. * ((position / 10) + 1); word = doubleMetaphoneEncode(word); } else if (fuzzy_match) { word = doubleMetaphoneEncode(word); if (keyword_codes.contains(word)) { matchScore += ((position / 10) + 1); } } //s = s + word; buf.append(word); if (k < wordsToCompare.size() - 1) //s = s + " "; buf.append(" "); k++; } String s = buf.toString(); if (s.indexOf(target) == -1) { return (float) 0.0; } float score = Math.max(0, 100 + (matchScore / totalWords * 100) - (totalWords * 2)); return score; // Math.max(0, 100 + (matchScore / totalWords * 100) - (totalWords * 2)) // * (isPreferred ? 2 : 1); }