List of usage examples for java.lang StringBuffer deleteCharAt
@Override public synchronized StringBuffer deleteCharAt(int index)
From source file:edu.mit.isda.permitws.permit.java
/** * * @param proxyUserName//www . ja v a 2 s. c o m * @param crit_list * @return * @throws edu.mit.isda.permitws.permitException */ @SuppressWarnings("unchecked") public String listAuthorizationsByCriteria(String proxyUserName, String crit_list) throws permitException { Collection auth = null; Iterator iter; String Message; String ApplicationID = ""; StringBuffer xml = new StringBuffer("\r\n{\"authorizations\": ["); String[] criteria = new String[43]; AuthenticateRemoteClient authenticateClient = new AuthenticateRemoteClient(); utils u = new utils(); try { ApplicationID = authenticateClient.authenticateClient("permitws"); if (proxyUserName == null) { Message = "Invalid certificate"; throw new Exception(Message); } if (proxyUserName.length() == 0) { Message = "No certificate user detected"; throw new Exception(Message); } String[] crit_split = crit_list.split("\\|\\|"); criteria[0] = ApplicationID; criteria[1] = proxyUserName; int critNum = crit_split.length / 2; criteria[2] = Integer.toString(critNum); int j = 0; for (int i = 0; i < crit_split.length; i++) { j = i + 3; criteria[j] = crit_split[i]; } //System.out.println("Criteria List = "); for (int i = 0; i < criteria.length; i++) { if (null == criteria[i]) { criteria[i] = ""; } //System.out.println(i + ": " + criteria[i]); } GeneralSelectionManager instance = GeneralSelectionFactory.getManager(); auth = instance.listAuthorizationsByCriteria(criteria); if (null == auth) { xml = new StringBuffer(EMPTY_RESULT_MESSAGE); } else if (auth.isEmpty()) { xml = new StringBuffer(EMPTY_RESULT_MESSAGE); } else { iter = auth.iterator(); while (iter.hasNext()) { AuthorizationRaw a = (AuthorizationRaw) iter.next(); AuthorizationPK apk = a.getAuthorizationPK(); Long aid = apk.getAuthorizationId(); xml = createAuthorizationXML(xml, a.getCategory(), a.getFunction(), a.getFunctionDesc(), a.getQualifierType(), a.getQualifierName(), a.getQualifierCode(), a.getPerson(), a.getFirstName(), a.getLastName(), aid, a.getEffectiveDate(), a.getExpirationDate(), a.getIsActiveNow(), a.getDoFunction(), a.getGrantAuthorization(), a.getModifiedBy(), a.getModifiedDate(), proxyUserName, false); } int lastCharIndex = xml.length(); xml.deleteCharAt(lastCharIndex - 1); xml.append("\r\n]}"); } } catch (Exception e) { Message = "permitws Web Service: " + e.getMessage(); log.error(Message); e.printStackTrace(); //throw new permitException(Message); return e.getMessage(); } try { return (URLEncoder.encode(xml.toString(), "UTF-8")); } catch (Exception e) { throw new permitException(e.getLocalizedMessage()); } }
From source file:edu.mit.isda.permitws.permit.java
/** * * @param UserName//from ww w . jav a 2s . co m * @param category * @param isActive * @param willExpand * @param proxyUserName * @param realOrImplied * @param function_name * @param function_id * @param function_qualifier_type * @param qualifier_code * @param qualifier_id * @param base_qual_code * @param base_qual_id * @param parent_qual_code * @param parent_qual_id * @return * @throws edu.mit.isda.permitws.permitException */ @SuppressWarnings("unchecked") public String listAuthByPersonExtend1XML(String UserName, String category, Boolean isActive, Boolean willExpand, String proxyUserName, String realOrImplied, String function_name, String function_id, String function_qualifier_type, String qualifier_code, String qualifier_id, String base_qual_code, String base_qual_id, String parent_qual_code, String parent_qual_id) throws permitException { Collection auth = null; Iterator iter; String Message; String ApplicationID = ""; StringBuffer xml = new StringBuffer("\r\n{\"authorizations\": ["); AuthenticateRemoteClient AuthenticateClient = new AuthenticateRemoteClient(); utils u = new utils(); try { UserName = u.validateUser(UserName); if (UserName == null) { Message = "invalid user name"; throw new Exception(Message); } if (UserName.length() == 0) { Message = "user name not specified"; throw new Exception(Message); } ApplicationID = AuthenticateClient.authenticateClient("permitws"); if (category == null) { category = ""; } if (proxyUserName == null) { Message = "Invalid certificate"; throw new Exception(Message); } if (proxyUserName.length() == 0) { Message = "No certificate user detected"; throw new Exception(Message); } AuthorizationManager instance = AuthorizationFactory.getManager(); auth = instance.listAuthByPersonExtend1(UserName.trim(), category.trim(), Boolean.valueOf(isActive), Boolean.valueOf(willExpand), ApplicationID.trim(), proxyUserName.trim(), realOrImplied, function_name, function_id, function_qualifier_type, qualifier_code, qualifier_id, base_qual_code, base_qual_id, parent_qual_code, parent_qual_id); if (null == auth) { xml = new StringBuffer(EMPTY_RESULT_MESSAGE); } else if (auth.isEmpty()) { xml = new StringBuffer(EMPTY_RESULT_MESSAGE); } else { iter = auth.iterator(); while (iter.hasNext()) { AuthorizationExt a = (AuthorizationExt) iter.next(); AuthorizationPK apk = a.getAuthorizationPK(); Long aid = apk.getAuthorizationId(); xml = createAuthorizationXML(xml, a.getCategory(), a.getFunction(), /*a.getFunctionDesc()*/ "", a.getQualifierType(), a.getQualifierName(), a.getQualifierCode(), a.getPerson(), /*a.getFirstName(),a.getLastName()*/"", "", aid, a.getEffectiveDate(), a.getExpirationDate(), a.getIsActiveNow(), a.getDoFunction(), a.getGrantAuthorization(), a.getModifiedBy(), a.getModifiedDate(), proxyUserName, false); } int lastCharIndex = xml.length(); xml.deleteCharAt(lastCharIndex - 1); xml.append("\r\n]}"); } } catch (Exception e) { Message = "permitws Web Service: " + e.getMessage(); log.error(Message); e.printStackTrace(); throw new permitException(e); } try { return (URLEncoder.encode(xml.toString(), "UTF-8")); } catch (Exception e) { throw new permitException(e.getLocalizedMessage()); } }
From source file:org.kuali.ole.service.impl.OLEEResourceSearchServiceImpl.java
public void getPOInvoiceForERS(OLEEResourceRecordDocument oleERSDoc) { try {/*from ww w .ja v a 2 s .com*/ Holdings holdings = null; List<OLEEResourcePO> oleeResourcePOs = new ArrayList<>(); List<OLEEResourceInvoices> oleeResourceInvoiceses = new ArrayList<>(); for (OLEEResourceInstance oleeResourceInstance : oleERSDoc.getOleERSInstances()) { holdings = getDocstoreClientLocator().getDocstoreClient() .retrieveHoldings(oleeResourceInstance.getInstanceId()); if (holdings != null) { Map<String, String> criteriaMap = new HashMap<String, String>(); criteriaMap.put(OLEConstants.INSTANCE_ID, holdings.getId()); List<OleCopy> copies = (List<OleCopy>) getBusinessObjectService().findMatching(OleCopy.class, criteriaMap); for (OleCopy copy : copies) { if (copy.getPoItemId() != null) { OLEEResourcePO oleeResourcePO = new OLEEResourcePO(); oleeResourcePO.setTitle(holdings.getBib().getTitle()); Map<String, String> criteriaPOIdMap = new HashMap<String, String>(); criteriaPOIdMap.put(OLEConstants.OLEEResourceRecord.PO_ITEM_ID, copy.getPoItemId().toString()); List<OlePurchaseOrderItem> olePurchaseOrderItems = (List<OlePurchaseOrderItem>) getBusinessObjectService() .findMatching(OlePurchaseOrderItem.class, criteriaPOIdMap); if (olePurchaseOrderItems.size() > 0) { for (OlePurchaseOrderItem olePurchaseOrderItem : olePurchaseOrderItems) { Map map = new HashMap(); map.put(OLEConstants.DOC_NUM, olePurchaseOrderItem.getDocumentNumber()); OlePurchaseOrderDocument olePurchaseOrderDocument = getBusinessObjectService() .findByPrimaryKey(OlePurchaseOrderDocument.class, map); if (olePurchaseOrderDocument != null) { oleeResourcePO.setOlePOItemId( olePurchaseOrderDocument.getPurapDocumentIdentifier()); Integer poCreatedYear = olePurchaseOrderDocument.getPostingYear(); Integer currentYear = Calendar.getInstance().get(Calendar.YEAR); if (currentYear.compareTo(poCreatedYear) == 0) { oleeResourcePO.setPaidAmountCurrentFY( olePurchaseOrderItem.getItemInvoicedTotalAmount().intValue()); } else if (currentYear.compareTo(poCreatedYear) == 1) { oleeResourcePO.setPaidAmountPreviousFY( olePurchaseOrderItem.getItemInvoicedTotalAmount().intValue()); } else if (currentYear.compareTo(poCreatedYear) > 1) { oleeResourcePO.setPaidAmountTwoYearsPreviousFY( olePurchaseOrderItem.getItemInvoicedTotalAmount().intValue()); } } } } oleeResourcePOs.add(oleeResourcePO); Map<String, String> criteriaInvIdMap = new HashMap<String, String>(); criteriaInvIdMap.put(OLEConstants.OLEEResourceRecord.INV_PO_ITEM_ID, copy.getPoItemId().toString()); List<OleInvoiceItem> oleInvoiceItems = (List<OleInvoiceItem>) getBusinessObjectService() .findMatching(OleInvoiceItem.class, criteriaInvIdMap); if (oleInvoiceItems.size() > 0) { for (OleInvoiceItem oleInvoiceItem : oleInvoiceItems) { OLEEResourceInvoices oleEResInvoice = new OLEEResourceInvoices(); oleEResInvoice.setInvoiceId(oleInvoiceItem.getItemIdentifier().toString()); OleInvoiceDocument oleInvoiceDocument = (OleInvoiceDocument) oleInvoiceItem .getInvoiceDocument(); if (oleInvoiceItem.getInvoiceDocument() != null) { oleEResInvoice.setInvoiceNumber( oleInvoiceItem.getInvoiceDocument().getDocumentNumber()); oleEResInvoice.setInvoiceDate( oleInvoiceItem.getInvoiceDocument().getInvoiceDate()); oleEResInvoice .setVendorName(oleInvoiceItem.getInvoiceDocument().getVendorName()); if (SpringContext.getBean(DocumentHeaderService.class) != null) { oleInvoiceDocument.setDocumentHeader(SpringContext .getBean(DocumentHeaderService.class) .getDocumentHeaderById(oleInvoiceDocument.getDocumentNumber())); oleEResInvoice.setInvoiceStatus( oleInvoiceDocument.getApplicationDocumentStatus()); } } oleEResInvoice.setInvoicedAmount(oleInvoiceItem.getExtendedPrice().toString()); Map map = new HashMap(); map.put(OLEConstants.OLEEResourceRecord.INV_PO_ITEM_ID, oleInvoiceItem.getItemIdentifier()); OlePaymentRequestItem olePaymentRequestItem = getBusinessObjectService() .findByPrimaryKey(OlePaymentRequestItem.class, map); if (olePaymentRequestItem != null) { oleEResInvoice.setPaidDate(olePaymentRequestItem.getPaymentRequestDocument() .getPaymentRequestPayDate()); } StringBuffer fundCode = new StringBuffer(); if (oleInvoiceItem.getSourceAccountingLines() != null && oleInvoiceItem.getSourceAccountingLines().size() > 0) { for (PurApAccountingLine accountingLine : oleInvoiceItem .getSourceAccountingLines()) { map.clear(); map.put(OLEConstants.ACCOUNT_NUMBER, accountingLine.getAccountNumber()); map.put(OLEConstants.OBJECT_CODE, accountingLine.getFinancialObjectCode()); OleVendorAccountInfo oleVendorAccountInfo = KRADServiceLocator .getBusinessObjectService() .findByPrimaryKey(OleVendorAccountInfo.class, map); if (oleVendorAccountInfo != null) { fundCode.append(oleVendorAccountInfo.getVendorRefNumber()); fundCode.append(OLEConstants.COMMA); fundCode.append(' '); } } } if (fundCode.length() > 0) { fundCode.deleteCharAt(fundCode.length() - 2); oleEResInvoice.setFundCode(fundCode.toString()); } oleeResourceInvoiceses.add(oleEResInvoice); } } } } } } oleERSDoc.setOleERSPOItems(oleeResourcePOs); oleERSDoc.setOleERSInvoices(oleeResourceInvoiceses); } catch (Exception e) { LOG.error("Exception " + e); } }
From source file:edu.mit.isda.permitws.permit.java
/** * * @param selectionID// www . j a v a2 s .c o m * @param UserName * @return * @throws edu.mit.isda.permitws.permitException */ @SuppressWarnings("unchecked") public String getCriteriaSet(String selectionID, String UserName) throws permitException { Collection crits = null; Iterator iter; String Message; String ApplicationID = ""; StringBuffer xml = new StringBuffer("\r\n{\"criteria\": ["); String value = ""; AuthenticateRemoteClient AuthenticateClient = new AuthenticateRemoteClient(); utils u = new utils(); try { UserName = u.validateUser(UserName); if (UserName == null) { Message = "invalid user name"; throw new Exception(Message); } if (UserName.length() == 0) { Message = "user name not specified"; throw new Exception(Message); } if (selectionID == null || selectionID.equals("")) { Message = "selectionID not specified"; throw new Exception(Message); } ApplicationID = AuthenticateClient.authenticateClient("permitws"); System.out.println("getCriteriaSet for selection id " + selectionID + " User Name " + UserName); GeneralSelectionManager instance = GeneralSelectionFactory.getManager(); crits = instance.getCriteriaSet(selectionID, UserName); if (crits.isEmpty()) { System.out.println("Empty Criteria set in getCriteriaSet"); } iter = crits.iterator(); while (iter.hasNext()) { Criteria c = (Criteria) iter.next(); value = c.getValue().trim().replace("'", "'"); if (value.equals("<me>")) { value = UserName.toUpperCase(); } xml.append("\r\n{\"id\":\"" + c.getId().toString().trim().replace("'", "'") + "\","); xml.append("\"selectionName\":\"" + c.getSelectionName().trim().replace("'", "'") + "\","); xml.append("\"screenId\":\"" + c.getScreenId().toString().trim().replace("'", "'") + "\","); xml.append("\"screenName\":\"" + c.getScreenName().trim().replace("'", "'") + "\","); xml.append("\"criteriaId\":\"" + c.getCriteriaId().trim().replace("'", "'") + "\","); xml.append("\"criteriaName\":\"" + c.getCriteriaName().trim().replace("'", "'") + "\","); xml.append("\"apply\":\"" + c.getApply().trim().replace("'", "'") + "\","); xml.append("\"nextScreen\":\"" + c.getNextScreen().trim().replace("'", "'") + "\","); xml.append("\"widget\":\"" + c.getWidget() + "\","); xml.append("\"value\":\"" + value + "\","); xml.append("\"noChange\":\"" + c.getNoChange().trim().replace("'", "'") + "\","); xml.append("\"sequence\":\"" + c.getSequence().trim().replace("'", "'") + "\"},"); } int lastCharIndex = xml.length(); xml.deleteCharAt(lastCharIndex - 1); xml.append("\r\n]}"); } catch (Exception e) { Message = "permitws Web Service: " + e.getMessage(); log.error(Message); e.printStackTrace(); throw new permitException(e); } log.debug("Criteria Set: " + xml); try { return (URLEncoder.encode(xml.toString(), "UTF-8")); } catch (Exception e) { throw new permitException(e.getLocalizedMessage()); } }
From source file:com.orientechnologies.orient.jdbc.H2.java
public static Collection<String> translate(String sql) throws SQLException { List<String> sections = new ArrayList<String>(); if (StringUtils.isNotEmpty(sql)) { boolean quoted = false; int bracesOpen = 0; boolean create = false; boolean type = false; boolean typeLen = false; boolean not = false; int max = 0; String lastWord = null;//from ww w . ja va 2 s . co m String className = null; String fieldName = null; boolean classNameAppended = false; StringBuffer section = new StringBuffer(); for (final StringTokenizer splitter = new StringTokenizer(sql, " ();,'`\r\n\t", true); splitter .hasMoreTokens();) { String w = splitter.nextToken(); if (w.length() == 0) continue; if (!quoted) { w = w.toUpperCase(); if (stripWords.contains(w) || (SPACE.equals(w))) section.append(SPACE_CHAR); else if (QUOTE.equals(w) || QUOTE_ALT.equals(w)) { section.append(w); if (QUOTE_ALT.equals(w) && !quoted) w = QUOTE; if (QUOTE.equals(w) && !QUOTE.equals(lastWord)) quoted = !quoted; } else if (BRACE_OPEN.equals(w)) { bracesOpen++; if (create) { trim(section); if (!type) { sections.add(section.toString()); section = new StringBuffer("CREATE PROPERTY "); section.append(className).append('.'); } else { sections.add(section.toString()); section = new StringBuffer("ALTER PROPERTY "); section.append(className).append('.'); section.append(fieldName).append(" MAX "); typeLen = true; } } else section.append(w); } else if (BRACE_CLOSED.equals(w)) { bracesOpen--; if (create) { if (typeLen) { trim(section); section.append(SPACE_CHAR).append(max); typeLen = false; max = 0; section.append(SPACE_CHAR); continue; } else if (type) { type = false; classNameAppended = false; } else create = false; } section.append(w); } else if (COMMA.equals(w)) { if (create) { if (type) { if (!typeLen) { trim(section); sections.add(section.toString()); section = new StringBuffer("CREATE PROPERTY "); section.append(className).append('.'); type = false; classNameAppended = true; fieldName = null; } else max++; } else section.append(w); } } else if (create) { if (type) { boolean suppw = supportedWords.contains(w); if (typeLen || suppw) { if (suppw) { if (NOT.equals(w)) { not = true; continue; } else { trim(section); sections.add(section.toString()); section = new StringBuffer("ALTER PROPERTY "); section.append(className).append('.'); section.append(fieldName); if (not) { section.append(" NOT"); not = false; } if (NULL.equals(w)) { if (section.lastIndexOf(NOT) == section.length() - 3) section.append(w).append("=TRUE"); else section.append(SPACE_CHAR).append(NOT).append(w).append("=FALSE"); } else section.append(w); } } else max += Integer.parseInt(w); } else { final String mtype = typeMap.get(w); if (StringUtils.isEmpty(mtype)) throw new SQLException(String .format("Sorry, type %s is not supported by Orient at the moment.", w)); section.append(mtype); } } else if (!classNameAppended) { className = w; section.append(className); classNameAppended = true; } else { if (section.charAt(section.length() - 1) == SPACE_CHAR) section.deleteCharAt(section.length() - 1); section.append(w); fieldName = w; type = true; } } else if (supportedWords.contains(w)) section.append(w); else if (SEMICOLON.equals(w)) { trim(section); sections.add(section.toString()); section = new StringBuffer(); } else if (TABLE.equals(w)) { section.append(CLASS); create = true; } else section.append(w); } else section.append(w); } } return sections; }
From source file:org.eclipse.mdht.uml.cda.core.util.CDAModelUtil.java
private static String computeCustomConformanceMessage(Constraint constraint, boolean markup) { StringBuffer message = new StringBuffer(); String strucTextBody = null;/*from www . j a v a 2 s .c om*/ String analysisBody = null; Map<String, String> langBodyMap = new HashMap<String, String>(); CDAProfileUtil.getLogicalConstraint(constraint); ValueSpecification spec = constraint.getSpecification(); if (spec instanceof OpaqueExpression) { for (int i = 0; i < ((OpaqueExpression) spec).getLanguages().size(); i++) { String lang = ((OpaqueExpression) spec).getLanguages().get(i); String body = ((OpaqueExpression) spec).getBodies().get(i); if ("StrucText".equals(lang)) { strucTextBody = body; } else if ("Analysis".equals(lang)) { analysisBody = body; } else { langBodyMap.put(lang, body); } } } String displayBody = null; if (strucTextBody != null && strucTextBody.trim().length() > 0) { // TODO if markup, parse strucTextBody and insert DITA markup displayBody = strucTextBody; } else if (analysisBody != null && analysisBody.trim().length() > 0) { Boolean ditaEnabled = false; try { Stereotype stereotype = CDAProfileUtil.getAppliedCDAStereotype(constraint, ICDAProfileConstants.CONSTRAINT_VALIDATION); ditaEnabled = (Boolean) constraint.getValue(stereotype, ICDAProfileConstants.CONSTRAINT_DITA_ENABLED); } catch (IllegalArgumentException e) { /* Swallow this */ } if (markup && !ditaEnabled) { // escape non-dita markup in analysis text displayBody = escapeMarkupCharacters(analysisBody); // change severity words to bold text displayBody = replaceSeverityWithBold(displayBody); } else { displayBody = analysisBody; } } if (displayBody == null) { List<Stereotype> stereotypes = constraint.getAppliedStereotypes(); if (stereotypes.isEmpty()) { // This should never happen but in case it does we deal with it appropriately // by bypassing custom constraint message additions return ""; } } if (!markup) { message.append(getPrefixedSplitName(constraint.getContext())).append(" "); } if (displayBody == null || !containsSeverityWord(displayBody)) { String keyword = getValidationKeyword(constraint); if (keyword == null) { keyword = "SHALL"; } message.append(markup ? "<b>" : ""); message.append(keyword); message.append(markup ? "</b>" : ""); message.append(" satisfy: "); } if (displayBody == null) { message.append(constraint.getName()); } else { message.append(displayBody); } appendConformanceRuleIds(constraint, message, markup); if (!markup) { // remove line feeds int index; while ((index = message.indexOf("\r")) >= 0) { message.deleteCharAt(index); } while ((index = message.indexOf("\n")) >= 0) { message.deleteCharAt(index); if (message.charAt(index) != ' ') { message.insert(index, " "); } } } return message.toString(); }
From source file:stg.pr.engine.CProcessRequestEngine.java
/** * Constructor of the class./*from w ww. j av a 2 s . c om*/ * <p> * This constructor accepts a String variable that has the path of the init * file that has the path of all the property files that have to be loaded. * The engine only accesses properties from the pr.properties file. However * if the processes, that have to be executed, require any more property * files, then the path of these files can also be mentioned in this init * file * </p> * * <p> * <ul> * <li> * Once the property file is loaded using the CSettings class, all the * attributes that the engine might access are retrieved and initialized to * the corresponding private member variables</li> * * <li> * The max size defined for both the log files are checked, against the * respective buffer sizes, to see that max size's specified are greater * than the buffer sizes</li> * * <li> * Engine log file is initialized and a database connection pool is created</li> * * <li> * A Shutdown hook is added that listens for a termination event for eg: * CTRL-C Once the event occurs appropriate action is taken to release * resources.</li> * </ul> * </p> * * @param pstrInitFile * String path of the init file that has the path of all the * property files that have to be loaded * @param pstrLoggerFile * Log4J.properties file. * @throws Exception * */ private CProcessRequestEngine(String pstrInitFile, String pstrLoggerFile, int iRebootCntr) throws Exception { try { PropertyConfigurator.configure(pstrLoggerFile); CSettings.getInstance().load(pstrInitFile); objEngineLogger_.log(LogLevel.NOTICE, info.toString()); context_ = new PREContextImpl(); context_.setPREinfo(info); if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Initializing Engine"); } setRebootCounter(iRebootCntr); // System.setProperty("java.util.prefs.PreferencesFactory", // "stg.utils.prefs.PREPreferencesFactoryImpl"); // System.setProperty("java.util.prefs.PreferencesFactory.file", // CSettings.get("pr.java.util.prefs.PreferencesFactory.file", // null)); // try { // installLic(); // always install the license so that if the // // license is changed in between it will get // // reflected. // licContent_ = readLicense(); // LicenseVerifier.verify(licContent_); // objEngineLogger_.log(LogLevel.NOTICE, "Licensed to " // + licContent_.getHolder().getName() + " for usage of " // + licContent_.getConsumerAmount() + " threads."); // objEngineLogger_.log(LogLevel.NOTICE, "Valid up to " // + licContent_.getNotAfter()); // Day now = new Day(); // objEngineLogger_.log(LogLevel.NOTICE, "Days remaining " // + Math.abs(now.daysBetween(licContent_.getNotAfter()))); // } catch (LicenseContentException lce) { // generateLicenseRequest(); // objEngineLogger_.log(LogLevel.FATAL, "Invalid license."); //// System.err.println(lce.getLocalizedMessage()); // throw new Exception(lce.getLocalizedMessage()); // } catch (Exception e2) { // objEngineLogger_.log(LogLevel.FATAL, "Invalid license."); // generateLicenseRequest(); //// System.err.println(e2.getLocalizedMessage()); // throw new Exception(e2.getLocalizedMessage()); // } lStuckThreadMonitorInterval_ = Math .abs(Long.parseLong(CSettings.get("pr.stuckthreadmonitorinterval", "0"))); if (lStuckThreadMonitorInterval_ <= 0) { throw new IllegalArgumentException( "Property stuckthreadmonitorinterval should be greater than zero"); } if (objEngineLogger_.isEnabledFor(LogLevel.FINEST)) { objEngineLogger_.log(LogLevel.FINEST, "Redirecting System.out and System.err to log4j"); } System.setErr( new PrintStream(new LoggingOutputStream(Logger.getLogger("System.err"), Level.WARN), true)); System.setOut( new PrintStream(new LoggingOutputStream(Logger.getLogger("System.out"), Level.INFO), true)); } catch (Exception e) { throw e; } if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("CLASSPATH=" + System.getProperty("java.class.path")); } strReqLogFilePath_ = CSettings.get("pr.requestlogfilepath"); strReqLogFileUrl_ = CSettings.get("pr.requestlogfileurl"); strReqLogFileExtension_ = CSettings.get("pr.requestlogfileextension"); paramSimpleDateFormat_ = new SimpleDateFormat(CSettings.get("pr.paramdateformat")); paramSimpleTimeFormat_ = new SimpleDateFormat(CSettings.get("pr.paramtimeformat")); paramSimpleDateTimeFormat_ = new SimpleDateFormat(CSettings.get("pr.paramdatetimeformat")); strParamArrValueDelim_ = CSettings.get("pr.paramarrvaluedelim"); FILTER_CONDITION = CSettings.get("pr.requesttypefilter", "XYZ"); if (!FILTER_CONDITION.equals("INCLUDE") && !FILTER_CONDITION.equals("EXCLUDE")) { throw new CProcessRequestEngineException( "Invalid FILTER type specified for property requesttypefilter."); } iStandAloneMaximumThread_ = CSettings.getInteger("pr.standalonemaxiumthreads"); iGroupMaximumThread_ = CSettings.getInteger("pr.groupmaxiumthreads"); if (iStandAloneMaximumThread_ <= 0) { throw new CProcessRequestEngineException("Invalid maximum threads for StandAlone engine configured."); } if (iGroupMaximumThread_ <= 0) { throw new CProcessRequestEngineException("Invalid maximum threads for Group engine configured."); } String strRequestTypes = CSettings.get("pr.processrequesttype", null); if (strRequestTypes == null) { throw new CProcessRequestEngineException( "Invalid processrequesttype defined. There must be a default value."); } StringTokenizer tokenizer = new StringTokenizer(strRequestTypes, ","); StringBuffer buffer = new StringBuffer(); while (tokenizer.hasMoreTokens()) { buffer.append("'"); buffer.append(tokenizer.nextElement()); buffer.append("'"); buffer.append(","); } buffer.deleteCharAt(buffer.length() - 1); if (FILTER_CONDITION.equals("INCLUDE")) { FILTER_CONDITION = "req_type IN (" + buffer.toString() + ")"; } else { FILTER_CONDITION = "req_type NOT IN (" + buffer.toString() + ")"; } try { (CCustomClassLoaderFactory.getInstance()).getClassLoader(this); // dummy call As this is a SingleTon Factory Pattern } catch (Exception e) { throw e; // throw new CProcessRequestEngineException("ClassLoader: " + // e.getMessage()); } iMaximumFetchSizeAtATime_ = Math.abs( Integer.parseInt(CSettings.get("pr.maximumfetchsizeinsinglefetch", CSettings.get("pr.dbcon")))); iThreadCounter_ = new AtomicInteger(1); iGrpThreadCounter_ = new AtomicInteger(1); setRebootMaxCounter(Integer.parseInt(CSettings.get("pr.rebootmaxcounter", "-1"))); setRebootSleepTime(Long.parseLong(CSettings.get("pr.sleepbeforereboottime", "5"))); hmWhereCondition_ = new HashMap<String, String>(); hmWhereCondition_.put("getScheduledTime", " <= "); bGroupEngineToBeStarted_ = ((CSettings.get("pr.groupengine", "OFF").equals("OFF")) ? false : true); httpserver_ = new CHttpServer(); // instantiate http server // bEngineTerminationConfirmed_ = false; vectorThreads_ = new Vector<Thread>(); // Inital size will be equal to // the total threads vectorThreadsGroup_ = new Vector<Thread>(); // =================== "" // ======================= // These NET properties are available only in JDK1.4.x and above. // Added by Kedar on July 31, 2004 .....SouthField Detroit USA System.setProperty("http.keepAlive", CSettings.get("pr.http.keepAlive", "true")); System.setProperty("http.maxConnections", CSettings.get("pr.http.maxConnections", "5")); System.setProperty("sun.net.client.defaultConnectTimeout", CSettings.get("pr.sun.net.client.defaultConnectTimeout", "10000")); System.setProperty("sun.net.client.defaultReadTimeout", CSettings.get("pr.sun.net.client.defaultReadTimeout", "10000")); try { jobMonitorEscalationTimeInterval_ = Math .abs(Integer.parseInt(CSettings.get("pr.jobmonitorescalationtimeinterval", "30"))); } catch (NumberFormatException e) { objEngineLogger_.error("Invalid value specified for jobmonitorescalationtimeinterval in properties."); if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Defaulting jobmonitorescalationtimeinterval to 30 minutes."); } jobMonitorEscalationTimeInterval_ = 30; } /* * Anonymous inner class passed as a parameter to addShutdownHook This * thread is registered with the JVM, and the JVM starts this just * before shutting down. For eg: when u try to abort by pressing Ctrl-C. * Hence run method is called and in turn terminateEngine method is * called where resources are released. */ if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Add ShutDown Hook ...."); } if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("ShutDown Hook Added...."); objEngineLogger_.info("Initializing Connection Pool ...."); } Class<?> c = Class.forName( CSettings.get("pr.dataSourceFactory", "stg.pr.engine.datasource.defaultimpl.PREDataSourceFactory")); Object obj = c.newInstance(); if (obj instanceof IDataSourceFactory) { dataSourceFactory_ = (IDataSourceFactory) obj; if (!dataSourceFactory_.initialize(new File(CSettings.get("pr.dataSourceFactoryConfigFile")))) { throw new CProcessRequestEngineException("Could not initialize the data source factory."); } } else { throw new CProcessRequestEngineException("Class does not implement IDataSource"); } if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Initiating the cluster using the configuration from file " + System.getProperty("hazelcast.config")); } Config config = ConfigLoader.load(System.getProperty("hazelcast.config")); Hazelcast.init(config); loadStartupClasses(); for (Entry<String, Service> entry : services_.entrySet()) { Service service = entry.getValue(); if (service instanceof Singleton<?>) { Singleton<?> singleton = (Singleton<?>) service; context_.addSingletonIfAbsent(entry.getKey(), singleton); if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Service " + entry.getKey() + ":" + entry.getValue().getClass().getName() + "made available to the context.. "); } } else { if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Service " + entry.getKey() + ":" + entry.getValue().getClass().getName() + "is unavailable to the context.. "); } } } startWebServer(); // if (CSettings.get("pr.reportService", "OFF").equalsIgnoreCase("ON")) { // if (objEngineLogger_.isInfoEnabled()) { // objEngineLogger_.info("Starting the Report Services."); // } // try { // EngineConfig reportConfig = new EngineConfig(); // reportConfig.setBIRTHome(CSettings.get("pr.birt.home")); // reportConfig.setLogConfig(CSettings.get("pr.birt.log.dir"), // java.util.logging.Level.parse(CSettings // .get("pr.birt.log.level"))); // reportConfig.setProperty("ThreadPoolServiceSize", CSettings // .getInt("pr.birt.threadpoolsize", 3)); // reportService = ReportService.getService(reportConfig); // if (objEngineLogger_.isEnabledFor(LogLevel.NOTICE)) { // objEngineLogger_.log(LogLevel.NOTICE, // "Report Services started"); // } // } catch (ReportServiceException e) { // objEngineLogger_.fatal("Report Service exception encountered", // e); // if (objEngineLogger_.isEnabledFor(LogLevel.NOTICE)) { // objEngineLogger_.log(LogLevel.NOTICE, // "Unable to start the report services."); // } // } // } if (objEngineLogger_.isInfoEnabled()) { objEngineLogger_.info("Engine Initialized"); } // This thread is now assigned upfront as in the Terminate engine if // called from Reboot Sequence then // the shutdown hook has to be removed from the Runtime instance. tInterrupt_ = new Thread("shutdown") { public void run() { objEngineLogger_.log(LogLevel.NOTICE, "ShutDown Hook In Running mode."); terminateEngine(); } }; Runtime.getRuntime().addShutdownHook(tInterrupt_); }
From source file:com.clustercontrol.collect.util.CollectGraphUtil.java
/** * ??????/* www . j a v a 2s. c o m*/ * * @param startDate DB???? * @param endDate DB???? * @param selectStartDate ? * @param selectEndDate ? * @return * @throws InvalidRole_Exception * @throws HinemosUnknown_Exception * @throws InvalidUserPass_Exception */ public static StringBuffer getAddGraphPlotJson(Long startDate, Long endDate, Long selectStartDate, Long selectEndDate) throws InvalidUserPass_Exception, HinemosUnknown_Exception, InvalidRole_Exception { m_log.debug("getAddGraphPlotJson() start"); StringBuffer sb = new StringBuffer(); int count = 0; boolean allbreak = false; for (CollectKeyInfoPK collectKeyInfo : getInstance().m_collectKeyInfoList) { String itemName = HinemosMessage.replace(collectKeyInfo.getItemName()); String monitorId = collectKeyInfo.getMonitorId(); String displayName = collectKeyInfo.getDisplayName(); for (Map.Entry<String, TreeMap<String, List<Integer>>> entry : getInstance().m_targetManagerFacilityCollectMap .entrySet()) { String managerName = entry.getKey(); Map<Integer, List<CollectData>> graphMap = getGraphDetailDataMap(managerName, monitorId, displayName, itemName, startDate, endDate); String itemNameDisplayNameMonitorId = itemName + displayName + monitorId; Map<String, Integer> collectIdMap = getFacilityCollectMap(itemNameDisplayNameMonitorId, managerName); // plot? List<String> plotList = parseGraphData(collectIdMap, graphMap); if (plotList == null || plotList.isEmpty()) { m_log.debug("getAddGraphPlotJson() plotDataList is Empty."); break; } // ?????? String thresholdStr = getThresholdData(managerName, monitorId); String thresholdInfoMin = "0"; String thresholdInfoMax = "0"; String thresholdWarnMin = "0"; String thresholdWarnMax = "0"; String measure = ""; String pluginId = ""; String graphRange = Boolean.FALSE.toString(); // graphrange???json????? String isHttpSce = Boolean.FALSE.toString(); if (thresholdStr != null) { thresholdInfoMin = thresholdStr.split(",")[0]; thresholdInfoMax = thresholdStr.split(",")[1]; thresholdWarnMin = thresholdStr.split(",")[2]; thresholdWarnMax = thresholdStr.split(",")[3]; measure = thresholdStr.split(",")[4]; pluginId = thresholdStr.split(",")[5]; graphRange = thresholdStr.split(",")[6]; isHttpSce = thresholdStr.split(",")[7]; } // #?split??addPoints for (String plotStr : plotList) { String split_plot[] = plotStr.split(SQUARE_SEPARATOR); String facilityId = split_plot[0]; String collectId = split_plot[1]; String plot = split_plot[2]; String facilityName = getInstance().m_managerFacilityIdNameMap .get(managerName + SQUARE_SEPARATOR + facilityId); String facilityDummyId = getInstance().m_managerFacilityIdDummyNameMap .get(managerName + SQUARE_SEPARATOR + facilityId); String managerDummyName = getInstance().m_managerDummyNameMap.get(managerName); String itemName2 = itemName; if (!displayName.equals("") && !itemName2.endsWith("[" + displayName + "]")) { itemName2 += "[" + displayName + "]"; } // groupIdexecuteJavascriptForFirstDrawGraphs?????(id)????????????? String groupId = itemName2 + "_" + monitorId; if (!getInstance().totalFlg) { groupId = facilityDummyId + "_" + managerDummyName + "_" + itemName2 + "_" + monitorId; } String param = "{" + "\'data\':" + plot + ", " + "\'realfacilityid\':\'" + facilityId + "\', " + "\'facilityid\':\'" + facilityDummyId + "\', " // DUMMY + "\'facilityname\':\'" + facilityName + "\', " + "\'monitorid\':\'" + monitorId + "\', " + "\'displayname\':\'" + displayName + "\', " + "\'collectid\':\'" + collectId + "\', " + "\'realmanagername\':\'" + managerName + "\', " + "\'managername\':\'" + managerDummyName + "\', " // DUMMY + "\'itemname\':\'" + itemName2 + "\', " + "\'groupid\':\'" + groupId + "\', " // ?????????? + "\'measure\':\'" + measure + "\', " + "\'pluginid\':\'" + pluginId + "\', " + "\'graphrange\':" + graphRange + ", " + "\'ishttpsce\':" + isHttpSce + ", " + "\'summarytype\':" + getInstance().m_summaryType + ", " + "\'startdate\':\'" + selectStartDate + "\', " + "\'enddate\':\'" + selectEndDate + "\', " + "\'sliderstartdate\':\'" + getInstance().m_sliderStart + "\', " + "\'sliderenddate\':\'" + getInstance().m_sliderEnd + "\', " + "\'thresholdinfomin\':\'" + thresholdInfoMin + "\', " + "\'thresholdinfomax\':\'" + thresholdInfoMax + "\', " + "\'thresholdwarnmin\':\'" + thresholdWarnMin + "\', " + "\'thresholdwarnmax\':\'" + thresholdWarnMax + "\' " + "}"; sb.append(param); sb.append(","); count++; if (count == ClusterControlPlugin.getDefault().getPreferenceStore() .getInt(PerformancePreferencePage.P_GRAPH_MAX)) { allbreak = true; break; } } if (allbreak) { break; } } if (allbreak) { break; } } if (sb.length() == 0) { m_log.debug("getAddGraphPlotJson() plot data 0."); return null; } String appendfirst = "{\'all\':["; sb.insert(0, appendfirst); sb.deleteCharAt(sb.length() - 1); sb.append("],"); sb.append("\'eventflaginfo\':[" + getEventFlagInfo() + "], "); sb.append(orderItemInfoSelection()); sb.append("}"); return sb; }
From source file:com.jd.survey.service.util.SPSSHelperService.java
/** * Returns the SPSS type definition for a survey * @param question/*from w ww . j av a 2 s.co m*/ * @return */ private StringBuffer getSurveySPSSTypeDefinitions(SurveyDefinition surveyDefinition) { try { StringBuffer sb = new StringBuffer(); for (SurveyDefinitionPage page : surveyDefinition.getPages()) { for (Question question : page.getQuestions()) { Policy policy = Policy.getInstance(this.getClass().getResource(POLICY_FILE_LOCATION)); AntiSamy as = new AntiSamy(); CleanResults cr = as.scan(question.getQuestionText(), policy); question.setQuestionText(cr.getCleanHTML()); switch (question.getType()) { case YES_NO_DROPDOWN: //Yes No DropDown sb.append(getSPSSVariableName(question)).append(" F1\n"); break; case SHORT_TEXT_INPUT: //Short Text Input sb.append(getSPSSVariableName(question)).append(" A75\n"); break; case LONG_TEXT_INPUT: //Long Text Input sb.append(getSPSSVariableName(question)).append(" A250\n"); break; case HUGE_TEXT_INPUT: //Huge Text Input sb.append(getSPSSVariableName(question)).append(" A2000\n"); break; case INTEGER_INPUT: //Integer Input sb.append(getSPSSVariableName(question)).append(" F11\n"); break; case CURRENCY_INPUT: //Currency Input sb.append(getSPSSVariableName(question)).append(" DOLLAR\n"); break; case DECIMAL_INPUT: //Decimal Input sb.append(getSPSSVariableName(question)).append(" F\n"); break; case DATE_INPUT: //Date Input sb.append(getSPSSVariableName(question)).append(" SDATE10\n"); //Format of export should be YYYY/MM/DD break; case SINGLE_CHOICE_DROP_DOWN: //Single choice Drop Down sb.append(getSPSSVariableName(question)).append(" A5\n"); break; case MULTIPLE_CHOICE_CHECKBOXES: //Multiple Choice Checkboxes for (QuestionOption option : question.getOptions()) { sb.append(getSPSSVariableName(option)).append(" F1\n"); } break; case DATASET_DROP_DOWN: //DataSet Drop Down sb.append(getSPSSVariableName(question)).append(" A5\n"); break; case SINGLE_CHOICE_RADIO_BUTTONS: //Single Choice Radio Buttons sb.append(getSPSSVariableName(question)).append(" A5\n"); break; case YES_NO_DROPDOWN_MATRIX: for (QuestionRowLabel questionRowLabel : question.getRowLabels()) { for (QuestionColumnLabel questionColumnLabel : question.getColumnLabels()) { sb.append(getSPSSVariableName(question, questionRowLabel, questionColumnLabel)) .append(" F1\n"); } } break; case SHORT_TEXT_INPUT_MATRIX: for (QuestionRowLabel questionRowLabel : question.getRowLabels()) { for (QuestionColumnLabel questionColumnLabel : question.getColumnLabels()) { sb.append(getSPSSVariableName(question, questionRowLabel, questionColumnLabel)) .append(" A75\n"); } } break; case INTEGER_INPUT_MATRIX: for (QuestionRowLabel questionRowLabel : question.getRowLabels()) { for (QuestionColumnLabel questionColumnLabel : question.getColumnLabels()) { sb.append(getSPSSVariableName(question, questionRowLabel, questionColumnLabel)) .append(" F11\n"); } } break; case CURRENCY_INPUT_MATRIX: for (QuestionRowLabel questionRowLabel : question.getRowLabels()) { for (QuestionColumnLabel questionColumnLabel : question.getColumnLabels()) { sb.append(getSPSSVariableName(question, questionRowLabel, questionColumnLabel)) .append(" DOLLAR\n"); } } break; case DECIMAL_INPUT_MATRIX: for (QuestionRowLabel questionRowLabel : question.getRowLabels()) { for (QuestionColumnLabel questionColumnLabel : question.getColumnLabels()) { sb.append(getSPSSVariableName(question, questionRowLabel, questionColumnLabel)) .append(" F\n"); } } break; case DATE_INPUT_MATRIX: for (QuestionRowLabel questionRowLabel : question.getRowLabels()) { for (QuestionColumnLabel questionColumnLabel : question.getColumnLabels()) { sb.append(getSPSSVariableName(question, questionRowLabel, questionColumnLabel)) .append(" SDATE10\n"); } } break; case IMAGE_DISPLAY: break; case VIDEO_DISPLAY: break; case FILE_UPLOAD: break; case STAR_RATING: sb.append(getSPSSVariableName(question)).append(" F11\n"); break; case SMILEY_FACES_RATING: sb.append(getSPSSVariableName(question)).append(" F11\n"); break; } } } //Remove the extra line break and append a dot sb.deleteCharAt(sb.length() - 1); sb.append(".\n"); return sb; } catch (Exception e) { log.error(e.getMessage(), e); throw new RuntimeException(e); } }
From source file:org.talend.designer.core.ui.editor.nodes.Node.java
@SuppressWarnings("unchecked") private void checkParameters() { // Check whether or not we need check column existence. // We just check the condition which just have one MetadataTable or Pre-MetadataTable. boolean checkColumnExist = false; IMetadataTable metadataTable = null; List<IMetadataTable> tables = getMetadataList(); if (tables != null && tables.size() == 1) { metadataTable = tables.get(0);/*from w w w .j a v a2s .c o m*/ checkColumnExist = true; } boolean checkPreColumnExist = false; IMetadataTable preMetadataTable = null; int preTableCount = 0; List<? extends IConnection> incomingConnections = getIncomingConnections(); if (incomingConnections != null && incomingConnections.size() > 0) { for (IConnection incomingConnection : incomingConnections) { if (incomingConnection.getLineStyle().hasConnectionCategory(IConnectionCategory.DATA)) { IMetadataTable schemaTable = incomingConnection.getMetadataTable(); if (schemaTable != null) { ++preTableCount; if (preTableCount > 1) { break; } preMetadataTable = schemaTable; } } } } if (preTableCount == 1) { checkPreColumnExist = true; } List<String> currentColumns = new ArrayList<String>(); if (checkColumnExist) { currentColumns = getColumnLabels(metadataTable); } List<String> preColumns = new ArrayList<String>(); if (checkPreColumnExist) { preColumns = getColumnLabels(preMetadataTable); } for (IElementParameter param : this.getElementParametersWithChildrens()) { if (param.getMaxlength() > 0) { String paramValue = param.getValue().toString(); paramValue.length(); String tmpValue; if (paramValue.startsWith("\"") && paramValue.endsWith("\"")) { //$NON-NLS-1$ //$NON-NLS-2$ tmpValue = paramValue.replaceAll("\"", ""); //$NON-NLS-1$ //$NON-NLS-2$ } else { // tmpValue = paramValue; // don't count if don't start with " continue; } String factor = "\\\\\\\\"; //$NON-NLS-1$ Pattern pattern = Pattern.compile(factor); Matcher matcher = pattern.matcher(tmpValue); int lenth = 0; matcher.groupCount(); while (matcher.find()) { lenth++; } String last = tmpValue.replaceAll(factor, ""); //$NON-NLS-1$ last = last.replaceAll("\\\\", ""); //$NON-NLS-1$ //$NON-NLS-2$ int realLength = last.length() + lenth; if (realLength > param.getMaxlength()) { String errorMessage = Messages.getString("Node.overLength", param.getDisplayName(), //$NON-NLS-1$ param.getMaxlength()); Problems.add(ProblemStatus.ERROR, this, errorMessage); } } if (param.getFieldType() == EParameterFieldType.CLOSED_LIST) { String showIf = param.getShowIf(); String notShowIf = param.getNotShowIf(); IElementParameter dbTypeEle = this.getElementParameter("DBTYPE");//$NON-NLS-1$ if (dbTypeEle != null && showIf != null && notShowIf == null) { String dbType = (String) dbTypeEle.getValue(); boolean show = false; if (showIf.contains(dbType)) { show = true; } if (show && !ArrayUtils.contains(param.getListItemsValue(), param.getValue())) { Problems.add(ProblemStatus.ERROR, this, "Unknown value in the list / Value set not supported by the component"); //$NON-NLS-1$ } } else if ("DQRULES_LIST".equals(param.getName()) || "PATTERN_LIST".equals(param.getName())) { //$NON-NLS-1$ //$NON-NLS-2$ // MOD for TDI-19063 Do not check value for these 2 parameters. } else { if (!ArrayUtils.contains(param.getListItemsValue(), param.getValue()) && !param.isDynamicSettings()) { Problems.add(ProblemStatus.ERROR, this, "Unknown value in the list [" + param.getDisplayName() //$NON-NLS-1$ + "] / Value set not supported by the component"); //$NON-NLS-1$ } } } if (param.getFieldType() == EParameterFieldType.TABLE) { // Check columns which not existing. Note: just check string type of parameter value. Object[] tableItemsValue = param.getListItemsValue(); List<String> columnListParamNames = new ArrayList<String>(); List<String> preColumnListParamNames = new ArrayList<String>(); if (tableItemsValue != null && tableItemsValue.length > 0) { for (Object tabItemValue : tableItemsValue) { if (tabItemValue instanceof IElementParameter) { IElementParameter itemParameter = (IElementParameter) tabItemValue; if (itemParameter.getFieldType() == EParameterFieldType.COLUMN_LIST) { columnListParamNames.add(itemParameter.getName()); } if (itemParameter.getFieldType() == EParameterFieldType.PREV_COLUMN_LIST) { preColumnListParamNames.add(itemParameter.getName()); } } } } StringBuffer inexistentColumns = new StringBuffer(); List<Map<String, Object>> tableValues = (List<Map<String, Object>>) param.getValue(); if (tableValues != null) { for (Map<String, Object> tabMap : tableValues) { int row = tableValues.indexOf(tabMap) + 1; if (checkColumnExist) { for (String paramName : columnListParamNames) { Object columnLineValue = tabMap.get(paramName); if (columnLineValue instanceof String && !currentColumns.contains(columnLineValue)) { inexistentColumns.append(columnLineValue).append("[Line:" + row + "]") //$NON-NLS-1$//$NON-NLS-2$ .append(","); //$NON-NLS-1$ } } } if (checkPreColumnExist) { for (String paramName : preColumnListParamNames) { Object columnLineValue = tabMap.get(paramName); if (columnLineValue instanceof String && !preColumns.contains(columnLineValue)) { inexistentColumns.append(columnLineValue).append("[Line:" + row + "]") //$NON-NLS-1$//$NON-NLS-2$ .append(","); //$NON-NLS-1$ } } } Object type = tabMap.get("TYPE"); //$NON-NLS-1$ if (type != null && type.toString().equals("SINGLE")) { //$NON-NLS-1$ Object code = tabMap.get("SCHEMA"); //$NON-NLS-1$ IMetadataTable metaTable = this.getMetadataTable(code.toString()); if (metaTable != null) { if (metaTable.getListColumns(true).size() > 1) { String warnMessage = Messages.getString("Node.hasMoreThenOneColumn", //$NON-NLS-1$ metaTable.getLabel()); Problems.add(ProblemStatus.WARNING, this, warnMessage); } } } } } if (inexistentColumns.length() > 0) { inexistentColumns.deleteCharAt(inexistentColumns.length() - 1); String warnMessage = Messages.getString("Node.hasInexistentColumn", //$NON-NLS-1$ inexistentColumns.toString(), param.getDisplayName()); Problems.add(ProblemStatus.WARNING, this, warnMessage); } } if (param.getName().equals(EParameterName.COMMENT.getName())) { String infoValue = (String) param.getValue(); if (infoValue != null && !infoValue.equals("")) { //$NON-NLS-1$ Problems.add(ProblemStatus.INFO, this, infoValue); } } List<IElementParameter> emptyParamList = Collections.emptyList(); Boolean noConditionOnShow = StringUtils.isEmpty(param.getShowIf()) && StringUtils.isEmpty(param.getNotShowIf()); // no condition on show means if the field is displayed or hidden all the time /** * ***Some explain for the following check*** * * "if (param.isRequired(getElementParameters()) && !param.isShow(emptyParamList)" <br> * * 1. in fact it's simply for components who have a table never displayed<br> * like tAdvancedOutput / tRowGenerator etc<br> * 2. as long as there is any show_if / not_show_if.... means there is no point to check any error here, * since the table is not displayed with the current config of the component<br> * 3. if table is always hidden, then we should force some checks */ // if the parameter is required but empty, an error will be added if (param.isRequired(getElementParameters()) && !param.isShow(emptyParamList) && noConditionOnShow && this.externalNode != null) { if (param.getFieldType().equals(EParameterFieldType.TABLE)) { List<Map<String, String>> tableValues = (List<Map<String, String>>) param.getValue(); // add by wzhang. all schemas need loop element. if (tableValues != null && "tFileOutputMSXML".equalsIgnoreCase(component.getName()) //$NON-NLS-1$ && param.getName().equals("LOOP")) { //$NON-NLS-1$ checkFileOutputMSXML(param, tableValues); } else if (tableValues != null && "tAdvancedFileOutputXML".equalsIgnoreCase(component.getName()) //$NON-NLS-1$ && param.getName().equals("LOOP") && tableValues.size() != 0) { //$NON-NLS-1$ // for bug 10108 if (((Boolean) this.getElementParameter("MERGE").getValue()) == true) { //$NON-NLS-1$ List<Map<String, String>> listGroup = (List<Map<String, String>>) externalNode .getElementParameter("GROUP").getValue(); //$NON-NLS-1$ List<Map<String, String>> listLoop = (List<Map<String, String>>) externalNode .getElementParameter("LOOP").getValue(); //$NON-NLS-1$ if (listGroup.size() == 0 || listLoop.size() == 0) { String errorMessage = Messages.getString("Node.needLoopAndGroup", //$NON-NLS-1$ param.getDisplayName()); Problems.add(ProblemStatus.ERROR, this, errorMessage); } } } else { if (tableValues == null || tableValues.size() == 0) { String errorMessage = Messages.getString("Node.needOneValue", param.getDisplayName()); //$NON-NLS-1$ Problems.add(ProblemStatus.ERROR, this, errorMessage); } } } } for (IConnection connection : getOutgoingConnections()) { if (connection.getSourceNodeConnector() != null && !connection.getSourceNodeConnector().isShow()) { Problems.add(ProblemStatus.ERROR, this, "Please remove the " //$NON-NLS-1$ + connection.getSourceNodeConnector().getLinkName() + " connections"); //$NON-NLS-1$ } } if (param.isRequired() && param.isShow(getElementParameters())) { EParameterFieldType fieldType = param.getFieldType(); String value; List multiSchemaDelimetedSeparaor = new ArrayList(); switch (fieldType) { case TABLE: List<Map<String, String>> tableValues = (List<Map<String, String>>) param.getValue(); // add by wzhang. all schemas need loop element. if (tableValues != null && "tFileOutputMSXML".equalsIgnoreCase(component.getName()) //$NON-NLS-1$ && param.getName().equals("LOOP")) { //$NON-NLS-1$ checkFileOutputMSXML(param, tableValues); } else { if (tableValues == null || tableValues.size() == 0) { String errorMessage = Messages.getString("Node.needOneValue", param.getDisplayName()); //$NON-NLS-1$ Problems.add(ProblemStatus.ERROR, this, errorMessage); } else if (this.getComponent().getName().equals("tFileInputXML")) {//$NON-NLS-1$ for (Map<String, String> map : tableValues) { if (map != null) { if ("".equals(map.get("QUERY")) || map.get("QUERY") == null) {//$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$ Problems.add(ProblemStatus.ERROR, this, Messages.getString("Node.QueryLosed")); //$NON-NLS-1$ } } } } } break; case CHECK: break; case RADIO: break; case SCHEMA_TYPE: break; case DCSCHEMA: // IMetadataTable metadataTable = getMetadataTable(getUniqueName()); // if(metadataTable == null || !(metadataTable.getListColumns().size() > 0)) { // String errorMessage = Messages.getString("Node.parameterEmpty", param.getDisplayName()); //$NON-NLS-1$ // Problems.add(ProblemStatus.ERROR, this, errorMessage); // } break; case MEMO_SQL: String errMessage = Messages.getString("Node.schemaDifferent", param.getDisplayName()); //$NON-NLS-1$ Object value2 = param.getValue(); if (value2 == null) { break; } String currentQuery = value2.toString(); // Checks if current query is empty. // if (currentQuery.equals("")) { // Problems.add(ProblemStatus.WARNING, this, errMessage); // break; // } // Checks current query was generated by clicking "Guess // Query" button. if (CorePlugin.getDefault().getPreferenceStore() .getBoolean(ITalendCorePrefConstants.SQL_ADD_WARNING)) { if (currentQuery.indexOf(COMPARE_STR1) != -1 || currentQuery.indexOf(COMPARE_STR2) != -1) { Problems.add(ProblemStatus.WARNING, this, errMessage); break; } if (!NodeQueryCheckUtil.checkQueryOK(this, currentQuery)) { Problems.add(ProblemStatus.WARNING, this, errMessage); break; } } break; case CLOSED_LIST: value = (String) param.getValue(); if (value == null || value.equals("")) { //$NON-NLS-1$ String errorMessage = Messages.getString("Node.parameterEmpty", param.getDisplayName()); //$NON-NLS-1$ Problems.add(ProblemStatus.ERROR, this, errorMessage); } else { if (param.getListItemsValue().length != 0) { boolean found = false; for (int i = 0; i < param.getListItemsValue().length && !found; i++) { if (param.getListItemsValue()[i].equals(value)) { found = true; } } if (!found) { String errorMessage = Messages.getString("Node.parameterNotExist", //$NON-NLS-1$ param.getDisplayName(), value); Problems.add(ProblemStatus.ERROR, this, errorMessage); } } } break; case COMPONENT_LIST: if (param != null) { String errorMessage; if (param.getValue() == null || "".equals(param.getValue())) { //$NON-NLS-1$ errorMessage = Messages.getString("Node.parameterEmpty", param.getDisplayName()); //$NON-NLS-1$ } else { errorMessage = Messages.getString("Node.parameterNotExist", param.getDisplayName(), //$NON-NLS-1$ param.getValue()); } if ((!hasUseExistingConnection(this)) || (isUseExistedConnetion(this))) { List<INode> list = (List<INode>) this.getProcess().getNodesOfType(param.getFilter()); if (list == null || list.size() == 0 || list.isEmpty()) { Problems.add(ProblemStatus.ERROR, this, errorMessage); } else { List<INode> nodeList = new ArrayList<INode>(); for (INode datanode : list) { if (!datanode.isVirtualGenerateNode()) { nodeList.add(datanode); } } if (nodeList.size() == 0 || nodeList.isEmpty()) { Problems.add(ProblemStatus.ERROR, this, errorMessage); break; } boolean foundValue = false; for (INode datanode : nodeList) { if (datanode.getUniqueName().equals(param.getValue())) { foundValue = true; break; } } errorMessage = Messages.getString("Node.parameterWrong", param.getDisplayName()); //$NON-NLS-1$ if (!foundValue) { Problems.add(ProblemStatus.ERROR, this, errorMessage); PropertyChangeCommand changeCommand = new PropertyChangeCommand(this, param.getName(), nodeList.get(0).getUniqueName()); if (this.getCommandStack() != null) { this.getCommandStack().execute(changeCommand); } } } } } break; default: if (param.getValue() != null && !(param.getValue() instanceof String)) { break; } value = (String) param.getValue(); if (value == null || value.equals("")) { //$NON-NLS-1$ if (this.getComponent() != null && "tFileInputMSDelimited".equals(this.getComponent().getName())) { //$NON-NLS-1$ multiSchemaDelimetedSeparaor.add(param); if (multiSchemaDelimetedSeparaor.size() == 2) { String errorMessage = Messages.getString("Node.parameterEmpty", //$NON-NLS-1$ param.getDisplayName()); Problems.add(ProblemStatus.ERROR, this, errorMessage); } } else { // TESB-6191 if (getComponent() != null && "cTalendJob".equals(getComponent().getName())) { //$NON-NLS-1$ IElementParameter fromRepository = getElementParameter("FROM_REPOSITORY_JOB"); //$NON-NLS-1$ Object isFromRepository = fromRepository.getValue(); if (isFromRepository != null && "true".equals(isFromRepository.toString())) { //$NON-NLS-1$ String errorMessage = Messages.getString("Node.parameterEmpty", //$NON-NLS-1$ param.getDisplayName()); Problems.add(ProblemStatus.ERROR, this, errorMessage); } else { // ignore the cTalendJob validation if it's not use the "FROM_REPOSITORY_JOB" // DO nothing } } else { String errorMessage = Messages.getString("Node.parameterEmpty", //$NON-NLS-1$ param.getDisplayName()); Problems.add(ProblemStatus.ERROR, this, errorMessage); } } } checkDataprepRun(param); } } checkValidationRule(param); checktAggregateRow(param); } checkJobletConnections(); IElementParameter enableParallelizeParameter = getElementParameter(EParameterName.PARALLELIZE.getName()); if (enableParallelizeParameter != null && enableParallelizeParameter.getValue() != null) { boolean x = (Boolean) enableParallelizeParameter.getValue(); if (x) { addStatus(Process.PARALLEL_STATUS); } } }