List of usage examples for java.util StringTokenizer hasMoreElements
public boolean hasMoreElements()
From source file:org.trafodion.dtm.TmAuditTlog.java
public void getTransactionState(TransactionState ts) throws IOException { if (LOG.isTraceEnabled()) LOG.trace("getTransactionState start; transid: " + ts.getTransactionId()); // This request might be for a transaction not originating on this node, so we need to open // the appropriate Tlog HTableInterface unknownTransactionTable; long lvTransid = ts.getTransactionId(); int lv_ownerNid = (int) (lvTransid >> 32); int lv_lockIndex = (int) (lvTransid & tLogHashKey); String lv_tLogName = new String( "TRAFODION._DTM_.TLOG" + String.valueOf(lv_ownerNid) + "_LOG_" + Integer.toHexString(lv_lockIndex)); HConnection unknownTableConnection = HConnectionManager.createConnection(this.config); unknownTransactionTable = unknownTableConnection.getTable(TableName.valueOf(lv_tLogName)); try {/* www . j av a 2s. c o m*/ String transidString = new String(String.valueOf(lvTransid)); Get g; long key = (((lvTransid & tLogHashKey) << tLogHashShiftFactor) + (lvTransid & 0xFFFFFFFF)); if (LOG.isTraceEnabled()) LOG.trace("key: " + key + ", hexkey: " + Long.toHexString(key) + ", transid: " + lvTransid); g = new Get(Bytes.toBytes(key)); TransState lvTxState = TransState.STATE_NOTX; String stateString = ""; String transidToken = ""; try { Result r = unknownTransactionTable.get(g); if (r == null) { if (LOG.isTraceEnabled()) LOG.trace("getTransactionState: tLog result is null: " + transidString); } if (r.isEmpty()) { if (LOG.isTraceEnabled()) LOG.trace("getTransactionState: tLog empty result: " + transidString); } byte[] value = r.getValue(TLOG_FAMILY, ASN_STATE); if (value == null) { ts.setStatus(TransState.STATE_NOTX); if (LOG.isTraceEnabled()) LOG.trace("getTransactionState: tLog value is null: " + transidString); return; } if (value.length == 0) { ts.setStatus(TransState.STATE_NOTX); if (LOG.isTraceEnabled()) LOG.trace("getTransactionState: tLog transaction not found: " + transidString); return; } ts.clearParticipatingRegions(); String recordString = new String(Bytes.toString(value)); StringTokenizer st = new StringTokenizer(recordString, ","); if (st.hasMoreElements()) { String asnToken = st.nextElement().toString(); transidToken = st.nextElement().toString(); stateString = st.nextElement().toString(); if (LOG.isTraceEnabled()) LOG.trace("getTransactionState: transaction: " + transidToken + " stateString is: " + stateString); } if (stateString.compareTo("COMMITTED") == 0) { lvTxState = TransState.STATE_COMMITTED; } else if (stateString.compareTo("ABORTED") == 0) { lvTxState = TransState.STATE_ABORTED; } else if (stateString.compareTo("ACTIVE") == 0) { lvTxState = TransState.STATE_ACTIVE; } else if (stateString.compareTo("PREPARED") == 0) { lvTxState = TransState.STATE_PREPARED; } else if (stateString.compareTo("NOTX") == 0) { lvTxState = TransState.STATE_NOTX; } else if (stateString.compareTo("FORGOTTEN") == 0) { // Need to get the previous state record so we know how to drive the regions String keyS = new String(r.getRow()); Get get = new Get(r.getRow()); get.setMaxVersions(versions); // will return last n versions of row Result lvResult = unknownTransactionTable.get(get); // byte[] b = lvResult.getValue(TLOG_FAMILY, ASN_STATE); // returns current version of value List<Cell> list = lvResult.getColumnCells(TLOG_FAMILY, ASN_STATE); // returns all versions of this column for (Cell element : list) { String stringValue = new String(CellUtil.cloneValue(element)); st = new StringTokenizer(stringValue, ","); if (st.hasMoreElements()) { if (LOG.isTraceEnabled()) LOG.trace("Performing secondary search on (" + transidToken + ")"); String asnToken = st.nextElement().toString(); transidToken = st.nextElement().toString(); String stateToken = st.nextElement().toString(); if ((stateToken.compareTo("COMMITTED") == 0) || (stateToken.compareTo("ABORTED") == 0)) { String rowKey = new String(r.getRow()); if (LOG.isTraceEnabled()) LOG.trace("Secondary search found record for (" + transidToken + ") with state: " + stateToken); lvTxState = (stateToken.compareTo("COMMITTED") == 0) ? TransState.STATE_COMMITTED : TransState.STATE_ABORTED; break; } else { if (LOG.isTraceEnabled()) LOG.trace("Secondary search skipping entry for (" + transidToken + ") with state: " + stateToken); } } } } else if (stateString.compareTo("ABORTING") == 0) { lvTxState = TransState.STATE_ABORTING; } else if (stateString.compareTo("COMMITTING") == 0) { lvTxState = TransState.STATE_COMMITTING; } else if (stateString.compareTo("PREPARING") == 0) { lvTxState = TransState.STATE_PREPARING; } else if (stateString.compareTo("FORGETTING") == 0) { lvTxState = TransState.STATE_FORGETTING; } else if (stateString.compareTo("FORGETTING_HEUR") == 0) { lvTxState = TransState.STATE_FORGETTING_HEUR; } else if (stateString.compareTo("BEGINNING") == 0) { lvTxState = TransState.STATE_BEGINNING; } else if (stateString.compareTo("HUNGCOMMITTED") == 0) { lvTxState = TransState.STATE_HUNGCOMMITTED; } else if (stateString.compareTo("HUNGABORTED") == 0) { lvTxState = TransState.STATE_HUNGABORTED; } else if (stateString.compareTo("IDLE") == 0) { lvTxState = TransState.STATE_IDLE; } else if (stateString.compareTo("FORGOTTEN_HEUR") == 0) { lvTxState = TransState.STATE_FORGOTTEN_HEUR; } else if (stateString.compareTo("ABORTING_PART2") == 0) { lvTxState = TransState.STATE_ABORTING_PART2; } else if (stateString.compareTo("TERMINATING") == 0) { lvTxState = TransState.STATE_TERMINATING; } else { lvTxState = TransState.STATE_BAD; } // get past the filler st.nextElement(); // Load the TransactionState object up with regions while (st.hasMoreElements()) { String tableNameToken = st.nextToken(); HTable table = new HTable(config, tableNameToken); NavigableMap<HRegionInfo, ServerName> regions = table.getRegionLocations(); Iterator<Map.Entry<HRegionInfo, ServerName>> it = regions.entrySet().iterator(); while (it.hasNext()) { // iterate entries. NavigableMap.Entry<HRegionInfo, ServerName> pairs = it.next(); HRegionInfo regionKey = pairs.getKey(); if (LOG.isTraceEnabled()) LOG.trace("getTransactionState: transaction: " + transidToken + " adding region: " + regionKey.getRegionNameAsString()); ServerName serverValue = regions.get(regionKey); String hostAndPort = new String(serverValue.getHostAndPort()); StringTokenizer tok = new StringTokenizer(hostAndPort, ":"); String hostName = new String(tok.nextElement().toString()); int portNumber = Integer.parseInt(tok.nextElement().toString()); TransactionRegionLocation loc = new TransactionRegionLocation(regionKey, serverValue); ts.addRegion(loc); } } ts.setStatus(lvTxState); if (LOG.isTraceEnabled()) LOG.trace("getTransactionState: returning transid: " + ts.getTransactionId() + " state: " + lvTxState); } catch (Exception e) { LOG.error("getTransactionState Exception " + Arrays.toString(e.getStackTrace())); throw e; } } catch (Exception e2) { LOG.error("getTransactionState Exception2 " + e2); e2.printStackTrace(); } if (LOG.isTraceEnabled()) LOG.trace("getTransactionState end transid: " + ts.getTransactionId()); return; }
From source file:com.inbravo.scribe.rest.service.crm.ms.MSCRMMessageFormatUtils.java
/** * /*from ww w.j a v a 2 s. c om*/ * @param query * @param order * @param queryExpression * @param crmFieldsSeparator * @param orderFieldsSeparator * @return * @throws Exception */ public static final com.microsoft.schemas.xrm._2011.contracts.QueryExpression createV5FilterInQuery( final String query, final String order, final com.microsoft.schemas.xrm._2011.contracts.QueryExpression queryExpression, final String crmFieldsSeparator, final String orderFieldsSeparator) throws Exception { if (query != null) { /* Tokenize the where clause */ final StringTokenizer stringTokenizer = new StringTokenizer(query, HTTPConstants.andClause + HTTPConstants.orClause, true); /* Create filter expression */ final com.microsoft.schemas.xrm._2011.contracts.FilterExpression filterExpression = queryExpression .addNewCriteria(); /* Create array of condition expression object */ final com.microsoft.schemas.xrm._2011.contracts.ArrayOfConditionExpression arrayOfConditionExpression = filterExpression .addNewConditions(); /* Iterate over tokenizer */ while (stringTokenizer.hasMoreElements()) { String tempElement = stringTokenizer.nextToken(); if (logger.isDebugEnabled()) { logger.debug("----Inside createFilterExpression: tempElement: " + tempElement); } /* Replace 'like' operator case */ tempElement = replaceLikeOpCase(tempElement); /* Check for '!=' operator */ if (tempElement.contains(notEqualOperator)) { /* Validate the element */ if (tempElement.split(notEqualOperator).length < 2) { throw new ScribeException( ScribeResponseCodes._1008 + "Query criteria is invalid: '" + tempElement + "'"); } /* Create condition expression */ final com.microsoft.schemas.xrm._2011.contracts.ConditionExpression conditionExpression = arrayOfConditionExpression .addNewConditionExpression(); /* Set attribute name */ conditionExpression.setAttributeName(tempElement.split(notEqualOperator)[0].trim()); /* Check for 'NULL' values */ if (tempElement.split(notEqualOperator)[1].trim().equalsIgnoreCase(nullConstant)) { /* Set Nill value */ conditionExpression .setOperator(com.microsoft.schemas.xrm._2011.contracts.ConditionOperator.NOT_NULL); } else { /* Set operator as 'NOT_EQUAL' */ conditionExpression .setOperator(com.microsoft.schemas.xrm._2011.contracts.ConditionOperator.NOT_EQUAL); /* Set value */ final com.microsoft.schemas._2003._10.serialization.arrays.ArrayOfanyType arrayOfAnyType = com.microsoft.schemas._2003._10.serialization.arrays.ArrayOfanyType.Factory .newInstance(); arrayOfAnyType.addNewAnyType(); arrayOfAnyType.setAnyTypeArray(0, XmlString.Factory.newValue(tempElement.split(notEqualOperator)[1].trim())); /* Add type information to avoid MS error */ addMSSpecificNS(arrayOfAnyType); conditionExpression.setValues(arrayOfAnyType); } } else /* Check for '=' operator */ if (tempElement.contains(equalOperator)) { /* Validate the element */ if (tempElement.split(equalOperator).length < 2) { throw new ScribeException( ScribeResponseCodes._1008 + "Query criteria is invalid: '" + tempElement + "'"); } /* Create condition expression */ final com.microsoft.schemas.xrm._2011.contracts.ConditionExpression conditionExpression = arrayOfConditionExpression .addNewConditionExpression(); /* Set attribute name */ conditionExpression.setAttributeName(tempElement.split(equalOperator)[0].trim()); /* Check for 'NULL' values */ if (tempElement.split(equalOperator)[1].trim().toUpperCase().equalsIgnoreCase(nullConstant)) { /* Set Nill value */ conditionExpression .setOperator(com.microsoft.schemas.xrm._2011.contracts.ConditionOperator.NULL); } else { /* Set operator as 'EQUAL' */ conditionExpression .setOperator(com.microsoft.schemas.xrm._2011.contracts.ConditionOperator.EQUAL); /* Set value */ final com.microsoft.schemas._2003._10.serialization.arrays.ArrayOfanyType aoat = com.microsoft.schemas._2003._10.serialization.arrays.ArrayOfanyType.Factory .newInstance(); aoat.addNewAnyType(); aoat.setAnyTypeArray(0, XmlString.Factory.newValue(tempElement.split(equalOperator)[1].trim())); /* Add type information to avoid MS error */ addMSSpecificNS(aoat); /* Set values in condition */ conditionExpression.setValues(aoat); } } else /* Check for 'LIKE' operator */ if (tempElement.contains(likeOperator)) { logger.debug("----Inside createFilterExpression: tempElement length: " + tempElement.split(likeOperator).length); /* Validate the element */ if (tempElement.split(likeOperator).length < 2) { throw new ScribeException( ScribeResponseCodes._1008 + "Query criteria is invalid: '" + tempElement + "'"); } /* Create condition expression */ final com.microsoft.schemas.xrm._2011.contracts.ConditionExpression conditionExpression = arrayOfConditionExpression .addNewConditionExpression(); /* Set attribute name */ conditionExpression.setAttributeName(tempElement.split(likeOperator)[0].trim()); /* Check for 'NULL' values */ if (tempElement.split(likeOperator)[1].trim().toUpperCase().equalsIgnoreCase(nullConstant)) { /* Set Nill value */ conditionExpression .setOperator(com.microsoft.schemas.xrm._2011.contracts.ConditionOperator.NULL); } else { /* Set operator as 'EQUAL' */ conditionExpression .setOperator(com.microsoft.schemas.xrm._2011.contracts.ConditionOperator.LIKE); /* Set value */ final com.microsoft.schemas._2003._10.serialization.arrays.ArrayOfanyType arrayOfAnyType = com.microsoft.schemas._2003._10.serialization.arrays.ArrayOfanyType.Factory .newInstance(); arrayOfAnyType.addNewAnyType(); arrayOfAnyType.setAnyTypeArray(0, XmlString.Factory.newValue(tempElement.split(likeOperator)[1].trim())); /* Add type information to avoid MS error */ addMSSpecificNS(arrayOfAnyType); conditionExpression.setValues(arrayOfAnyType); } } else { throw new ScribeException( ScribeResponseCodes._1008 + "Query criteria is invalid: '" + tempElement + "'"); } } } /* If a valid order */ if (order != null && !"".equals(order)) { /* Create order expression */ final com.microsoft.schemas.xrm._2011.contracts.ArrayOfOrderExpression arrayOfOrderExpression = queryExpression .addNewOrders(); /* Tokenize the order clause */ final StringTokenizer stringTokenizer = new StringTokenizer(order, crmFieldsSeparator); /* Iterate over tokenizer */ while (stringTokenizer.hasMoreElements()) { /* Create new order expression */ final com.microsoft.schemas.xrm._2011.contracts.OrderExpression oe = arrayOfOrderExpression .addNewOrderExpression(); /* Validate order clause */ final String[] updatedOrderArray = parseAndValidateOrderClauseForMSCRM(stringTokenizer.nextToken(), orderFieldsSeparator); /* Set attribute name */ oe.setAttributeName(updatedOrderArray[0]); /* Set order type */ if ("ASC".equalsIgnoreCase(updatedOrderArray[1])) { oe.setOrderType(com.microsoft.schemas.xrm._2011.contracts.OrderType.ASCENDING); } else if ("DESC".equalsIgnoreCase(updatedOrderArray[1])) { oe.setOrderType(com.microsoft.schemas.xrm._2011.contracts.OrderType.DESCENDING); } } } return queryExpression; }
From source file:org.apache.jmeter.JMeter.java
private void runNonGui(String testFile, String logFile, boolean remoteStart, String remote_hosts_string, boolean generateReportDashboard) { try {// www . j a v a 2s. com File f = new File(testFile); if (!f.exists() || !f.isFile()) { println("Could not open " + testFile); return; } FileServer.getFileServer().setBaseForScript(f); HashTree tree = SaveService.loadTree(f); @SuppressWarnings("deprecation") // Deliberate use of deprecated ctor JMeterTreeModel treeModel = new JMeterTreeModel(new Object());// Create non-GUI version to avoid headless problems JMeterTreeNode root = (JMeterTreeNode) treeModel.getRoot(); treeModel.addSubTree(tree, root); // Hack to resolve ModuleControllers in non GUI mode SearchByClass<ReplaceableController> replaceableControllers = new SearchByClass<>( ReplaceableController.class); tree.traverse(replaceableControllers); Collection<ReplaceableController> replaceableControllersRes = replaceableControllers.getSearchResults(); for (ReplaceableController replaceableController : replaceableControllersRes) { replaceableController.resolveReplacementSubTree(root); } // Remove the disabled items // For GUI runs this is done in Start.java convertSubTree(tree); Summariser summer = null; String summariserName = JMeterUtils.getPropDefault("summariser.name", "");//$NON-NLS-1$ if (summariserName.length() > 0) { log.info("Creating summariser <" + summariserName + ">"); println("Creating summariser <" + summariserName + ">"); summer = new Summariser(summariserName); } ReportGenerator reportGenerator = null; if (logFile != null) { ResultCollector logger = new ResultCollector(summer); logger.setFilename(logFile); tree.add(tree.getArray()[0], logger); if (generateReportDashboard) { reportGenerator = new ReportGenerator(logFile, logger); } } else { // only add Summariser if it can not be shared with the ResultCollector if (summer != null) { tree.add(tree.getArray()[0], summer); } } // Used for remote notification of threads start/stop,see BUG 54152 // Summariser uses this feature to compute correctly number of threads // when NON GUI mode is used tree.add(tree.getArray()[0], new RemoteThreadsListenerTestElement()); List<JMeterEngine> engines = new LinkedList<>(); tree.add(tree.getArray()[0], new ListenToTest(parent, (remoteStart && remoteStop) ? engines : null, reportGenerator)); println("Created the tree successfully using " + testFile); if (!remoteStart) { JMeterEngine engine = new StandardJMeterEngine(); engine.configure(tree); long now = System.currentTimeMillis(); println("Starting the test @ " + new Date(now) + " (" + now + ")"); engine.runTest(); engines.add(engine); } else { java.util.StringTokenizer st = new java.util.StringTokenizer(remote_hosts_string, ",");//$NON-NLS-1$ List<String> hosts = new LinkedList<>(); while (st.hasMoreElements()) { hosts.add((String) st.nextElement()); } DistributedRunner distributedRunner = new DistributedRunner(this.remoteProps); distributedRunner.setStdout(System.out); distributedRunner.setStdErr(System.err); distributedRunner.init(hosts, tree); engines.addAll(distributedRunner.getEngines()); distributedRunner.start(); } startUdpDdaemon(engines); } catch (Exception e) { System.out.println("Error in NonGUIDriver " + e.toString()); log.error("Error in NonGUIDriver", e); } }
From source file:org.jabsorb.ng.JSONRPCBridge.java
/** * Call a method using a JSON-RPC request object. * /*from w ww .j a v a 2 s . c o m*/ * @param context * The transport context (the HttpServletRequest and * HttpServletResponse objects in the case of the HTTP * transport). * * @param jsonReq * The JSON-RPC request structured as a JSON object tree. * * @return a JSONRPCResult object with the result of the invocation or an * error. */ public JSONRPCResult call(final Object context[], final JSONObject jsonReq) { // #1: Parse the request final String encodedMethod; final Object requestId; JSONArray arguments; final JSONArray fixups; try { encodedMethod = jsonReq.getString("method"); arguments = jsonReq.optJSONArray("params"); requestId = jsonReq.opt("id"); fixups = jsonReq.optJSONArray("fixups"); if (arguments == null) { // T. Calmant: Use an empty array if necessary arguments = new JSONArray(); } } catch (final JSONException e) { log.error("call", "no method or parameters in request"); return new JSONRPCResult(JSONRPCResult.CODE_ERR_NOMETHOD, null, JSONRPCResult.MSG_ERR_NOMETHOD); } if (log.isDebugEnabled()) { if (fixups != null) { log.debug("call", "call " + encodedMethod + "(" + arguments + ")" + ", requestId=" + requestId); } else { log.debug("call", "call " + encodedMethod + "(" + arguments + ")" + ", fixups=" + fixups + ", requestId=" + requestId); } } // apply the fixups (if any) to the parameters. This will result // in a JSONArray that might have circular references-- so // the toString method (or anything that internally tries to traverse // the JSON (without being aware of this) should not be called after // this // point if (fixups != null) { try { for (int i = 0; i < fixups.length(); i++) { final JSONArray assignment = fixups.getJSONArray(i); final JSONArray fixup = assignment.getJSONArray(0); final JSONArray original = assignment.getJSONArray(1); applyFixup(arguments, fixup, original); } } catch (final JSONException e) { log.error("call", "error applying fixups", e); return new JSONRPCResult(JSONRPCResult.CODE_ERR_FIXUP, requestId, JSONRPCResult.MSG_ERR_FIXUP + ": " + e.getMessage()); } } // #2: Get the name of the class and method from the encodedMethod final String className; final String methodName; { final StringTokenizer t = new StringTokenizer(encodedMethod, "."); if (t.hasMoreElements()) { className = t.nextToken(); } else { className = null; } if (t.hasMoreElements()) { methodName = t.nextToken(); } else { methodName = null; } } // #3: Get the id of the object (if it exists) from the className // (in the format: ".obj#<objectID>") final int objectID; { final int objectStartIndex = encodedMethod.indexOf('['); final int objectEndIndex = encodedMethod.indexOf(']'); if (encodedMethod.startsWith(OBJECT_METHOD_PREFIX) && (objectStartIndex != -1) && (objectEndIndex != -1) && (objectStartIndex < objectEndIndex)) { objectID = Integer.parseInt(encodedMethod.substring(objectStartIndex + 1, objectEndIndex)); } else { objectID = 0; } } // #4: Handle list method calls if ((objectID == 0) && (encodedMethod.equals("system.listMethods"))) { return new JSONRPCResult(JSONRPCResult.CODE_SUCCESS, requestId, systemListMethods()); } // #5: Get the object to act upon and the possible method that could be // called on it final Map<AccessibleObjectKey, List<? extends AccessibleObject>> methodMap; final Object javascriptObject; final AccessibleObject ao; try { javascriptObject = getObjectContext(objectID, className); methodMap = getAccessibleObjectMap(objectID, className, methodName); // #6: Resolve the method ao = AccessibleObjectResolver.resolveMethod(methodMap, methodName, arguments, ser); if (ao == null) { throw new NoSuchMethodException(JSONRPCResult.MSG_ERR_NOMETHOD); } } catch (final NoSuchMethodException e) { if (e.getMessage().equals(JSONRPCResult.MSG_ERR_NOCONSTRUCTOR)) { return new JSONRPCResult(JSONRPCResult.CODE_ERR_NOCONSTRUCTOR, requestId, JSONRPCResult.MSG_ERR_NOCONSTRUCTOR); } return new JSONRPCResult(JSONRPCResult.CODE_ERR_NOMETHOD, requestId, JSONRPCResult.MSG_ERR_NOMETHOD); } // #7: Call the method final JSONRPCResult r = AccessibleObjectResolver.invokeAccessibleObject(ao, context, arguments, javascriptObject, requestId, ser, cbc, exceptionTransformer); return r; }
From source file:org.geppetto.solver.sph.SPHSolverService.java
@Override public void populateSimulationTree(AspectSubTreeNode watchTree) { // map watchable buffers that are not already mapped // NOTE: position is mapped for scene generation - improving performance // by not mapping it again _velocityPtr = _velocity.map(_queue, CLMem.MapFlags.Read); // check which watchable variables are being watched for (AVariable var : getWatchableVariables().getVariables()) { for (String varName : watchListVarNames) { // get watchable variables path List<String> watchableVarsPaths = new ArrayList<String>(); VariablePathSerializer.GetFullVariablePath(var, "", watchableVarsPaths); varName = varName.replace(watchTree.getInstancePath() + ".", ""); // remove array bracket arguments from variable paths String varNameNoBrackets = varName; String particleID = null; if (varName.indexOf("[") != -1) { varNameNoBrackets = varName.substring(0, varName.indexOf("[")) + varName.substring(varName.indexOf("]") + 1, varName.length()); particleID = varName.substring(varName.indexOf("[") + 1, varName.indexOf("]")); }//ww w.ja va2 s . c o m // loop through paths and look for matching paths for (String s : watchableVarsPaths) { if (s.equals(varNameNoBrackets)) { // we have a match Integer ID = null; if (particleID != null) { // check that paticleID is valid ID = Integer.parseInt(particleID); if (!(ID < _particleCount)) { throw new IllegalArgumentException( "SPHSolverService:updateStateTreeForWatch - particle index is out of boundaries"); } } // tokenize variable path in watch list via dot // separator (handle array brackets) StringTokenizer tokenizer = new StringTokenizer(s, "."); ACompositeNode node = watchTree; while (tokenizer.hasMoreElements()) { // loop through tokens and build tree String current = tokenizer.nextToken(); boolean found = false; for (ANode child : node.getChildren()) { if (child.getId().equals(current)) { if (child instanceof ACompositeNode) { node = (ACompositeNode) child; } found = true; break; } } if (found) { continue; } else { if (tokenizer.hasMoreElements()) { // not a leaf, create a composite statenode String nodeName = current; if (current.equals("particle")) { nodeName = current + "[" + particleID + "]"; } CompositeNode newNode = new CompositeNode(nodeName); newNode.setId(nodeName); boolean addNewNode = containsNode(node, newNode.getId()); if (addNewNode) { node.addChild(newNode); node = newNode; } else { node = getNode(node, newNode.getId()); } } else { // it's a leaf node VariableNode newNode = new VariableNode(current); newNode.setId(current); FloatValue val = null; // get value switch (current) { case "x": val = ValuesFactory.getFloatValue(_positionPtr.get(ID)); break; case "y": val = ValuesFactory.getFloatValue(_positionPtr.get(ID + 1)); break; case "z": val = ValuesFactory.getFloatValue(_positionPtr.get(ID + 2)); break; } PhysicalQuantity q = new PhysicalQuantity(); q.setValue(val); newNode.addPhysicalQuantity(q); node.addChild(newNode); } } } } } } } watchTree.setModified(true); // unmap watchable buffers _velocity.unmap(_queue, _positionPtr); }
From source file:us.mn.state.health.lims.result.action.ResultsEntryUpdateAction.java
protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // this is used if user has clicked notes icon and decides to update // (all results get updated, but we need to know which results to // display notes for) String notesAnalyteId = (String) request.getParameter("analyteId"); String notesRefId = null;/* w ww .j a v a 2 s . com*/ String forward = FWD_SUCCESS; request.setAttribute(ALLOW_EDITS_KEY, "true"); request.setAttribute(PREVIOUS_DISABLED, "true"); request.setAttribute(NEXT_DISABLED, "true"); String refId = null; if (request.getAttribute(NOTES_REFID) != null) { refId = (String) request.getAttribute(NOTES_REFID); } //bugzilla 2227 String amendedAnalysisId = null; if (request.getParameter(ANALYSIS_ID) != null) { amendedAnalysisId = (String) request.getParameter(ANALYSIS_ID); } BaseActionForm dynaForm = (BaseActionForm) form; String accessionNumber = (String) dynaForm.get("accessionNumber"); String[] selectedTestResultIds = (String[]) dynaForm.get("selectedTestResultIds"); String[] resultValueN = (String[]) dynaForm.get("resultValueN"); String[] selectedResultIsReportableFlags = (String[]) dynaForm.get("selectedResultIsReportableFlags"); List testTestAnalytes = (List) dynaForm.get("testTestAnalytes"); String addedReflexTestIds = (String) dynaForm.get("addedReflexTestIds"); String addedReflexTestParentResultIds = (String) dynaForm.get("addedReflexTestParentResultIds"); // bugzilla 1882 String addedReflexTestParentAnalyteIds = (String) dynaForm.get("addedReflexTestParentAnalyteIds"); String addedReflexTestParentAnalysisIds = (String) dynaForm.get("addedReflexTestParentAnalysisIds"); String[] selectedTestIsReportableFlags = (String[]) dynaForm.get("selectedTestIsReportableFlags"); String domain = (String) dynaForm.get("domain"); //bugzilla 2254 String hasNewUnsatisfactoryResult = (String) dynaForm.get("hasNewUnsatisfactoryResult"); //bugzilla 1798: if coming from popup to link a parent test - this will have information String linkedParentInformationString = (String) dynaForm.get("linkedParentInformationString"); //bugzilla 1798: if User has clicked UNLINK FROM PARENT this string will have information String unlinkedParentInformationString = (String) dynaForm.get("unlinkedParentInformationString"); int pageResultCounter = 0; for (int j = 0; j < testTestAnalytes.size(); j++) { Test_TestAnalyte testTestAnalyte = (Test_TestAnalyte) testTestAnalytes.get(j); TestAnalyte_TestResults[] testAnalyteTestResults = (TestAnalyte_TestResults[]) testTestAnalyte .getTestAnalyteTestResults(); // remove the testresultid added by default for those numeric types for (int i = 0; i < testAnalyteTestResults.length; i++) { TestAnalyte_TestResults taTr = (TestAnalyte_TestResults) testAnalyteTestResults[i]; List testResults = taTr.getTestResults(); //bugzila 1908 fixing a bug where null and size not checked (this was found while testing 1908) if (testResults != null && testResults.size() > 0) { TestResult testresult = (TestResult) testResults.get(0); //bugzilla 2220 - Added titer type results to this logic (numeric and titer are in one category) if (testresult.getTestResultType() .equalsIgnoreCase(SystemConfiguration.getInstance().getNumericType()) || testresult.getTestResultType() .equalsIgnoreCase(SystemConfiguration.getInstance().getTiterType())) { if (StringUtil.isNullorNill(resultValueN[pageResultCounter])) { selectedTestResultIds[pageResultCounter] = ""; } } } pageResultCounter++; } } // server side validation of accessionNumber // validate on server-side sample accession number ActionMessages errors = null; try { errors = new ActionMessages(); errors = validateAll(request, errors, dynaForm); // System.out.println("Just validated accessionNumber"); } catch (Exception e) { //bugzilla 2154 LogEvent.logError("ResultsEntryUpdateAction", "performAction()", e.toString()); ActionError error = new ActionError("errors.ValidationException", null, null); errors.add(ActionMessages.GLOBAL_MESSAGE, error); } if (errors != null && errors.size() > 0) { saveErrors(request, errors); //bugzilla 2361 if (domain.equals(SystemConfiguration.getInstance().getHumanDomain())) { return mapping.findForward(FWD_FAIL_HUMAN); } else { return mapping.findForward(FWD_FAIL); } } // initialize the form dynaForm.initialize(mapping); // 1926 get sysUserId from login module UserSessionData usd = (UserSessionData) request.getSession().getAttribute(USER_SESSION_DATA); String sysUserId = String.valueOf(usd.getSystemUserId()); Date today = Calendar.getInstance().getTime(); Locale locale = (Locale) request.getSession().getAttribute("org.apache.struts.action.LOCALE"); String dateAsText = DateUtil.formatDateAsText(today, locale); org.hibernate.Transaction tx = HibernateUtil.getSession().beginTransaction(); if (!StringUtil.isNullorNill(accessionNumber)) { ResultDAO resultDAO = new ResultDAOImpl(); TestResultDAO testResultDAO = new TestResultDAOImpl(); AnalysisDAO analysisDAO = new AnalysisDAOImpl(); TestDAO testDAO = new TestDAOImpl(); NoteDAO noteDAO = new NoteDAOImpl(); TestAnalyteDAO testAnalyteDAO = new TestAnalyteDAOImpl(); SampleDAO sampleDAO = new SampleDAOImpl(); DictionaryDAO dictDAO = new DictionaryDAOImpl(); try { //bugzilla 1798 (added functionality to link a parent test to child test) //parse data from popup (link test) for subsequent update of child analysis String childAnalysisId = ""; Analysis linkedParentAnalysis = new Analysis(); Result linkedParentResult = new Result(); if (!StringUtil.isNullorNill(linkedParentInformationString)) { String idSeparator = SystemConfiguration.getInstance().getDefaultIdSeparator(); StringTokenizer st = new StringTokenizer(linkedParentInformationString, idSeparator); String parentAnalysisId = ""; String parentResultId = ""; List listOfIds = new ArrayList(); while (st.hasMoreElements()) { String id = (String) st.nextElement(); listOfIds.add(id); } //see resultsEntryLinkChildTestToParentTestResultPopup.jsp childAnalysisId = (String) listOfIds.get(0); parentAnalysisId = (String) listOfIds.get(1); parentResultId = (String) listOfIds.get(2); linkedParentAnalysis.setId(parentAnalysisId); linkedParentResult.setId(parentResultId); analysisDAO.getData(linkedParentAnalysis); resultDAO.getData(linkedParentResult); } //end 1798 Sample sample = new Sample(); sample.setAccessionNumber(accessionNumber); sample = sampleDAO.getSampleByAccessionNumber(accessionNumber); int pageResultIndex = 0; // pre-process the reflex tests List listOfTestsThatTriggeredReflex = new ArrayList(); List listOfTestResultsThatTriggeredReflex = new ArrayList(); // bugzilla 1882 List listOfAnalytesThatTriggeredReflex = new ArrayList(); List listOfAnalysesThatTriggeredReflex = new ArrayList(); List listOfResultsThatTriggeredReflex = new ArrayList(); List listOfAddedTests = new ArrayList(); if (!StringUtil.isNullorNill(addedReflexTestIds) && !StringUtil.isNullorNill(addedReflexTestParentResultIds)) { String idSeparator = SystemConfiguration.getInstance().getDefaultIdSeparator(); // populate list of parent results StringTokenizer parentResultTokenizer = new StringTokenizer(addedReflexTestParentResultIds, idSeparator); while (parentResultTokenizer.hasMoreElements()) { String testResultId = (String) parentResultTokenizer.nextElement(); TestResult testResult = new TestResult(); testResult.setId(testResultId); testResultDAO.getData(testResult); listOfTestResultsThatTriggeredReflex.add(testResult); String testId = testResult.getTest().getId(); listOfTestsThatTriggeredReflex.add(testId); } StringTokenizer addedTestTokenizer = new StringTokenizer(addedReflexTestIds, idSeparator); while (addedTestTokenizer.hasMoreElements()) { String testId = (String) addedTestTokenizer.nextElement(); // System.out // .println("This is a addedTestToken " + testId); Test test = new Test(); test.setId(testId); testDAO.getData(test); listOfAddedTests.add(test); } // bugzilla 1882 populate list of parent analytes StringTokenizer parentAnalyteTokenizer = new StringTokenizer(addedReflexTestParentAnalyteIds, idSeparator); while (parentAnalyteTokenizer.hasMoreElements()) { String testAnalyteId = (String) parentAnalyteTokenizer.nextElement(); TestAnalyte testAnalyte = new TestAnalyte(); testAnalyte.setId(testAnalyteId); testAnalyteDAO.getData(testAnalyte); listOfAnalytesThatTriggeredReflex.add(testAnalyte); } // bugzilla 1882 populate list of parent analyses StringTokenizer parentAnalysisTokenizer = new StringTokenizer(addedReflexTestParentAnalysisIds, idSeparator); while (parentAnalysisTokenizer.hasMoreElements()) { String analysisId2 = (String) parentAnalysisTokenizer.nextElement(); Analysis analysis2 = new Analysis(); analysis2.setId(analysisId2); listOfAnalysesThatTriggeredReflex.add(analysis2); } } for (int x = 0; x < testTestAnalytes.size(); x++) { Test_TestAnalyte test_testAnalyte = (Test_TestAnalyte) testTestAnalytes.get(x); TestAnalyte_TestResults[] testAnalyteTestResults = (TestAnalyte_TestResults[]) test_testAnalyte .getTestAnalyteTestResults(); Analysis analysis = test_testAnalyte.getAnalysis(); //bugzilla 1942 (if results for all REQUIRED test analytes have been entered then results entry is considered complete) boolean areResultsForRequiredTestAnalytesEntered = true; //bugzilla 1942 completedDate on analysis should only be update if // results entry is completed = areResultsForRequiredTestAnalytesEntered is true // AND if at least one result has changed boolean atLeastOneRequiredResultHasChanged = false; for (int i = 0; i < testAnalyteTestResults.length; i++) { TestAnalyte_TestResults taTr = (TestAnalyte_TestResults) testAnalyteTestResults[i]; String selectedTestResultId = taTr.getSelectedTestResultId(); TestAnalyte ta = taTr.getTestAnalyte(); Result result = new Result(); Result[] resultsFromTestTestAnalyte = test_testAnalyte.getResults(); for (int j = 0; j < resultsFromTestTestAnalyte.length; j++) { Result res = (Result) resultsFromTestTestAnalyte[j]; if (res != null && !StringUtil.isNullorNill(res.getId())) { if (res.getAnalyte().getId().equals(ta.getAnalyte().getId())) { result = res; break; } } } // bugzilla 1926 result.setSysUserId(sysUserId); //bugzilla 1942 boolean noResult = true; if (!StringUtil.isNullorNill(selectedTestResultId)) { if (!StringUtil.isNullorNill(selectedTestResultIds[pageResultIndex])) { noResult = false; TestResult tr = new TestResult(); tr.setId(selectedTestResultIds[pageResultIndex]); testResultDAO.getData(tr); //bugzilla 1942: find out if required results have changed on this test (needed to determine whether to update completed date) if (result.getIsReportable() != null && result.getIsReportable().equals(YES)) { if (result.getTestResult() != null && !StringUtil.isNullorNill(result.getTestResult().getValue())) { String oldResult = result.getTestResult().getValue(); if (!oldResult.equals(tr.getValue())) { atLeastOneRequiredResultHasChanged = true; } } } // update existing selection result.setTestResult(tr); if (tr.getTestResultType() .equalsIgnoreCase(SystemConfiguration.getInstance().getNumericType())) { result.setValue(resultValueN[pageResultIndex]); } else if (tr.getTestResultType() .equalsIgnoreCase(SystemConfiguration.getInstance().getTiterType())) { String setTiter = "1:" + resultValueN[pageResultIndex]; result.setValue(setTiter); } else { result.setValue(tr.getValue()); //bugzilla 2028 check for UNSATISFACTORY dictionary type results // get from dictionary Dictionary dictionary = new Dictionary(); dictionary.setId(result.getValue()); dictDAO.getData(dictionary); } result.setAnalysis(analysis); result.setIsReportable(selectedResultIsReportableFlags[pageResultIndex]); if (!StringUtil.isNullorNill(notesAnalyteId)) { if (result.getAnalyte().getId().equals(notesAnalyteId)) { notesRefId = result.getId(); } } resultDAO.updateData(result); } else { // bugzilla 1942: delete existing result List results = new ArrayList(); //bugzilla 1942 check if result has notes - THEN DON'T ALLOW DELETE (per Christina/Nancy) Note note = new Note(); List notesByResult = new ArrayList(); //bugzilla 2571 go through ReferenceTablesDAO to get reference tables info ReferenceTables referenceTables = new ReferenceTables(); referenceTables .setId(SystemConfiguration.getInstance().getResultReferenceTableId()); //bugzilla 2571 go through ReferenceTablesDAO to get reference tables info note.setReferenceTables(referenceTables); note.setReferenceId(result.getId()); notesByResult = noteDAO.getAllNotesByRefIdRefTable(note); //bugzilla 1798 List childAnalysesByResult = new ArrayList(); childAnalysesByResult = analysisDAO.getAllChildAnalysesByResult(result); if (notesByResult != null && notesByResult.size() > 0) { Exception e = new LIMSCannotDeleteDependentRecordExistsException( "Cannot delete - dependent record exists for " + result.getId()); throw new LIMSRuntimeException("Error in Result updateData()", e); } //bugzilla 1798 else if (childAnalysesByResult != null && childAnalysesByResult.size() > 0) { Exception e = new LIMSCannotDeleteDependentRecordExistsException( "Cannot delete - dependent record exists for " + result.getId()); throw new LIMSRuntimeException("Error in Result updateData()", e); } else { results.add(result); resultDAO.deleteData(results); } } } else { if (!StringUtil.isNullorNill(selectedTestResultIds[pageResultIndex])) { // insert new result noResult = false; TestResult tr = new TestResult(); tr.setId(selectedTestResultIds[pageResultIndex]); testResultDAO.getData(tr); // insert Analyte analyte = ta.getAnalyte(); result.setAnalyte(analyte); result.setAnalysis(analysis); result.setTestResult(tr); if (tr.getTestResultType() .equalsIgnoreCase(SystemConfiguration.getInstance().getNumericType())) { result.setValue(resultValueN[pageResultIndex]); } else if (tr.getTestResultType() .equalsIgnoreCase(SystemConfiguration.getInstance().getTiterType())) { String setTiter = "1:" + resultValueN[pageResultIndex]; result.setValue(setTiter); } else { result.setValue(tr.getValue()); //bugzilla 2028 check for UNSATISFACTORY dictionary type results // get from dictionary Dictionary dictionary = new Dictionary(); dictionary.setId(result.getValue()); dictDAO.getData(dictionary); } result.setResultType(tr.getTestResultType()); result.setIsReportable(selectedResultIsReportableFlags[pageResultIndex]); result.setSortOrder(ta.getSortOrder()); //bugzilla 1942: find out if required results have changed on this test (needed to determine whether to update completed date) //this result has changed for sure if (ta.getIsReportable() != null && ta.getIsReportable().equals(YES)) { atLeastOneRequiredResultHasChanged = true; } resultDAO.insertData(result); // need to add this new result to // test_testAnalyte // for display on right side of screen after // update // on route to notes popup resultsFromTestTestAnalyte[i] = result; test_testAnalyte.setResults(resultsFromTestTestAnalyte); if (!StringUtil.isNullorNill(notesAnalyteId)) { if (result.getAnalyte().getId().equals(notesAnalyteId)) { notesRefId = result.getId(); } } } else { // do nothing } } //bugzilla 1942 (if results for all REQUIRED test analytes have been entered then results entry is considered complete) // per Christina - all reportable results must have a value for a test otherwise results entry is not completed // need to check test_analyte for isReportable flag if there is NO result record if (noResult && !StringUtil.isNullorNill(ta.getIsReportable()) && ta.getIsReportable().equals(YES)) { areResultsForRequiredTestAnalytesEntered = false; } // if this is analyte that notes icon was selected for // then // set the result id (IActionConstants.NOTES_REFID) in // the // request // this can be used in NotesPopupAction pageResultIndex++; } // bugzilla 1926 analysis.setSysUserId(sysUserId); analysis.setIsReportable(selectedTestIsReportableFlags[x]); //bugzilla 1942 (if results for all REQUIRED test analytes have been entered then results entry is considered complete) if (areResultsForRequiredTestAnalytesEntered) { //bugzilla 1967 only if not already released //bugzilla 1942 AND if at least one result has changed if (!analysis.getStatus() .equals(SystemConfiguration.getInstance().getAnalysisStatusReleased()) && atLeastOneRequiredResultHasChanged) { analysis.setStatus( SystemConfiguration.getInstance().getAnalysisStatusResultCompleted()); analysis.setCompletedDateForDisplay(dateAsText); } } else { analysis.setStatus(SystemConfiguration.getInstance().getAnalysisStatusAssigned()); analysis.setCompletedDateForDisplay(null); } //bugzilla 1798 also update parent analysis/parent result if link was requested for this analysis //link if (!StringUtil.isNullorNill(linkedParentInformationString) && childAnalysisId.equals(analysis.getId())) { analysis.setParentAnalysis(linkedParentAnalysis); analysis.setParentResult(linkedParentResult); } //unlink if (!StringUtil.isNullorNill(unlinkedParentInformationString) && unlinkedParentInformationString.equals(analysis.getId())) { analysis.setParentAnalysis(null); analysis.setParentResult(null); } analysisDAO.updateData(analysis); } // bugzilla 1882 if (listOfAnalytesThatTriggeredReflex.size() > 0) { //create listOfResultsThatTriggeredReflex from analysis/analyte for (int i = 0; i < listOfAnalysesThatTriggeredReflex.size(); i++) { Analysis analysisThatTriggered = (Analysis) listOfAnalysesThatTriggeredReflex.get(i); TestAnalyte analyteThatTriggered = (TestAnalyte) listOfAnalytesThatTriggeredReflex.get(i); Result result = new Result(); resultDAO.getResultByAnalysisAndAnalyte(result, analysisThatTriggered, analyteThatTriggered); listOfResultsThatTriggeredReflex.add(result); } // Are there any added tests (reflex tests) for (int i = 0; i < listOfAnalytesThatTriggeredReflex.size(); i++) { Analysis analysisThatTriggered = (Analysis) listOfAnalysesThatTriggeredReflex.get(i); analysisDAO.getData(analysisThatTriggered); TestAnalyte analyteThatTriggered = (TestAnalyte) listOfAnalytesThatTriggeredReflex.get(i); Result result = (Result) listOfResultsThatTriggeredReflex.get(i); Test test = (Test) listOfAddedTests.get(i); Analysis newAnalysis = new Analysis(); // TODO: need to populate this with actual data!!! newAnalysis.setAnalysisType("TEST"); newAnalysis.setSampleItem(analysisThatTriggered.getSampleItem()); newAnalysis.setTest(test); newAnalysis.setTestSection(test.getTestSection()); newAnalysis.setStatus(SystemConfiguration.getInstance().getAnalysisStatusAssigned()); newAnalysis.setParentAnalysis(analysisThatTriggered); newAnalysis.setParentResult(result); newAnalysis.setIsReportable(test.getIsReportable()); // bugzilla 1926 newAnalysis.setSysUserId(sysUserId); //bugzilla 2064 newAnalysis.setRevision(SystemConfiguration.getInstance().getAnalysisDefaultRevision()); //bugzilla 2013 added duplicateCheck parameter analysisDAO.insertData(newAnalysis, false); } } tx.commit(); // bugzilla 1703: introducing a confirmation message after // updates and inserts have succeeded! errors = new ActionMessages(); ActionError error = null; error = new ActionError("resultsentry.confirmupdate.message", null, null); errors.add(ActionMessages.GLOBAL_MESSAGE, error); saveErrors(request, errors); request.setAttribute(Globals.ERROR_KEY, errors); // end bugzilla 1703 } catch (LIMSRuntimeException lre) { //bugzilla 2154 LogEvent.logError("ResultsEntryUpdateAction", "performAction()", lre.toString()); tx.rollback(); errors = new ActionMessages(); ActionError error = null; if (lre.getException() instanceof org.hibernate.StaleObjectStateException) { error = new ActionError("errors.OptimisticLockException", null, null); } else if (lre.getException() instanceof LIMSCannotDeleteDependentRecordExistsException) { error = new ActionError("resultsentry.changetonoresult.error", null, null); } else { error = new ActionError("errors.UpdateException", null, null); } errors.add(ActionMessages.GLOBAL_MESSAGE, error); saveErrors(request, errors); request.setAttribute(Globals.ERROR_KEY, errors); // bugzilla 1485 // request.setAttribute(IActionConstants.ALLOW_EDITS_KEY, // "false"); //bugzilla 2361 if (domain.equals(SystemConfiguration.getInstance().getHumanDomain())) { forward = FWD_FAIL_HUMAN; } else { forward = FWD_FAIL; } } finally { HibernateUtil.closeSession(); } } PropertyUtils.setProperty(dynaForm, "accessionNumber", accessionNumber); PropertyUtils.setProperty(dynaForm, "selectedTestResultIds", selectedTestResultIds); PropertyUtils.setProperty(dynaForm, "resultValueN", resultValueN); PropertyUtils.setProperty(dynaForm, "selectedResultIsReportableFlags", selectedResultIsReportableFlags); PropertyUtils.setProperty(dynaForm, "selectedTestIsReportableFlags", selectedTestIsReportableFlags); PropertyUtils.setProperty(dynaForm, "domain", domain); PropertyUtils.setProperty(dynaForm, "testTestAnalytes", testTestAnalytes); if (!StringUtil.isNullorNill(notesAnalyteId)) { request.setAttribute(NOTES_REFID, notesRefId); request.setAttribute(NOTES_REFTABLE, SystemConfiguration.getInstance().getResultReferenceTableId()); } else { request.setAttribute(NOTES_REFID, refId); request.setAttribute(NOTES_REFTABLE, SystemConfiguration.getInstance().getResultReferenceTableId()); } //bugzilla 2311 //bugzilla 2361 if (!forward.equals(FWD_FAIL) && !forward.equals(FWD_FAIL_HUMAN)) { //bugzilla 2028 Qa Events - if any of the results are UNSATISFACTORY then route to QAEvents Entry //bugzilla 2227 - don't route to qa events if Note or Amend were clicked //bugzilla 2254 if (hasNewUnsatisfactoryResult.equals(TRUE) && !mapping.getPath().contains("Note") && !mapping.getPath().contains("Amend")) { forward = FWD_SUCCESS_QA_EVENTS_ENTRY; return getForward(mapping.findForward(forward), accessionNumber); } //bugzilla 2227 if (!StringUtil.isNullorNill(amendedAnalysisId)) { return getForward(mapping.findForward(forward), accessionNumber, amendedAnalysisId); } } return mapping.findForward(forward); }
From source file:com.irets.datadownloader.SearchPropertyServlet.java
@Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm"); long reqInputArrivalTime = System.currentTimeMillis(); Date resultdate = new Date(reqInputArrivalTime); System.out.println("Calling Me @:" + sdf.format(resultdate) + ", from: " + request.getRemoteAddr() + ", with url> " + request.getRequestURL() + "?" + request.getQueryString()); long startTime = reqInputArrivalTime; WebApplicationContext wac = WebApplicationContextUtils .getRequiredWebApplicationContext(getServletContext()); SearchService propServices = this.getSearchService(wac); propServices.setContextPath(this.getUrl3(request)); //propServices.setServer(this.getServer(request)); Filter filer = new Filter(); ArrayList<FilterItem> filterItemArrayList = new ArrayList<FilterItem>(1); ArrayList<FilterItem> exactFilterItemArrayList = new ArrayList<FilterItem>(1); ArrayList<FilterItem> multipleFilterItemArrayList = new ArrayList<FilterItem>(1); ArrayList<String> keywordArrayList = new ArrayList<String>(1); Vector<SimpleRange> rangeVector = new Vector<SimpleRange>(1); GeoParameter geoParam = null;/*from w ww . j a va 2 s. com*/ // SimpleRange aRange = new SimpleRange("price_list",null,50000); // filer.setRanges(new SimpleRange[]{aRange}); int start = 0; int limit = -1; // if(request.getParameter("ListingId") != null){ // FilterItem filterItem = new FilterItem(); // filterItem.setField("number_MLS"); // filterItem.setValue(request.getParameter("ListingId")); // filterItemArrayList.add(filterItem); // } if (request.getParameter("ListPrice") != null) { SimpleRange aRange; String listPrice = request.getParameter("ListPrice"); System.out.println("List price is " + listPrice); String min = ""; String max = ""; if (!listPrice.equalsIgnoreCase("No Min-No Max")) { if (listPrice.indexOf(":") != -1) { // System.out.println("listPrice : -->>"+listPrice); min = listPrice.substring(0, listPrice.indexOf(":")); max = listPrice.substring(listPrice.indexOf(":") + 1, listPrice.length()); aRange = new SimpleRange("price_list", min, max); } else if (listPrice.endsWith("+")) { // System.out.println("listPrice +-->>"+listPrice); min = listPrice.substring(0, listPrice.indexOf("+")); aRange = new SimpleRange("price_list", min, null); } else if (listPrice.endsWith("-")) { // System.out.println("listPrice - -->>"+listPrice); max = listPrice.substring(0, listPrice.indexOf("-")); aRange = new SimpleRange("price_list", null, max); } else if (listPrice.length() > 0) { // Exact match.... min = listPrice.substring(0, listPrice.length()); max = min; aRange = new SimpleRange("price_list", min, max); } else { aRange = new SimpleRange("price_list", null, null); } rangeVector.add(aRange); } } if (request.getParameter("Bedrooms") != null) { SimpleRange aRange; String bedrooms = request.getParameter("Bedrooms"); String min = ""; String max = ""; if (!bedrooms.equalsIgnoreCase("No Min-No Max")) { if (bedrooms.indexOf(":") != -1) { // System.out.println("Bedrooms: -->>"+bedrooms); min = bedrooms.substring(0, bedrooms.indexOf(":")); max = bedrooms.substring(bedrooms.indexOf(":") + 1, bedrooms.length()); aRange = new SimpleRange("number_beds_Total", min, max); } else if (bedrooms.endsWith("+")) { // System.out.println("Bedrooms+ -->>"+bedrooms); min = bedrooms.substring(0, bedrooms.indexOf("+")); aRange = new SimpleRange("number_beds_Total", min, null); } else if (bedrooms.endsWith("-")) { // System.out.println("Bedrooms- -->>"+bedrooms); max = bedrooms.substring(0, bedrooms.indexOf("-")); aRange = new SimpleRange("number_beds_Total", null, max); } else if (bedrooms.length() > 0) { // Exact match.... min = bedrooms.substring(0, bedrooms.length()); max = min; aRange = new SimpleRange("number_beds_Total", min, max); } else { aRange = new SimpleRange("number_beds_Total", null, null); } rangeVector.add(aRange); } } if (request.getParameter("FullBathrooms") != null) { SimpleRange aRange; String fullBath = request.getParameter("FullBathrooms"); String min = ""; String max = ""; if (!fullBath.equalsIgnoreCase("No Min-No Max")) { if (fullBath.indexOf(":") != -1) { // System.out.println("FullBathrooms: -->>"+fullBath); min = fullBath.substring(0, fullBath.indexOf(":")); max = fullBath.substring(fullBath.indexOf(":") + 1, fullBath.length()); aRange = new SimpleRange("number_baths_Full", min, max); } else if (fullBath.endsWith("+")) { // System.out.println("FullBathrooms+ -->>"+fullBath); min = fullBath.substring(0, fullBath.indexOf("+")); aRange = new SimpleRange("number_baths_Full", min, null); } else if (fullBath.endsWith("-")) { // System.out.println("FullBathrooms- -->>"+fullBath); max = fullBath.substring(0, fullBath.indexOf("-")); aRange = new SimpleRange("number_baths_Full", null, max); } else if (fullBath.length() > 0) { min = fullBath.substring(0, fullBath.length()); max = min; aRange = new SimpleRange("number_baths_Full", min, max); } else { aRange = new SimpleRange("number_baths_Full", null, null); } rangeVector.add(aRange); } } if (request.getParameter("SqFt") != null) { SimpleRange aRange; String sqFt = request.getParameter("SqFt"); String min = ""; String max = ""; if (!sqFt.equalsIgnoreCase("No Min-No Max")) { if (sqFt.indexOf(":") != -1) { // System.out.println("SqFt: -->>"+sqFt); min = sqFt.substring(0, sqFt.indexOf(":")); max = sqFt.substring(sqFt.indexOf(":") + 1, sqFt.length()); aRange = new SimpleRange("sqft_Structure", min, max); } else if (sqFt.endsWith("+")) { // System.out.println("SqFt+ -->>"+sqFt); min = sqFt.substring(0, sqFt.indexOf("+")); aRange = new SimpleRange("sqft_Structure", min, null); } else if (sqFt.endsWith("-")) { // System.out.println("SqFt- -->>"+sqFt); max = sqFt.substring(0, sqFt.indexOf("-")); aRange = new SimpleRange("sqft_Structure", null, max); } else if (sqFt.length() > 0) { min = sqFt.substring(0, sqFt.length()); max = min; aRange = new SimpleRange("sqft_Structure", min, max); } else { aRange = new SimpleRange("sqft_Structure", null, null); } rangeVector.add(aRange); } } // Date range for the property. if (request.getParameter("Age") != null) { SimpleRange aRange; String age = request.getParameter("Age"); String min = ""; String max = ""; if (!age.equalsIgnoreCase("No Min-No Max")) { if (age.indexOf(":") != -1) { System.out.println("age: -->>" + age); min = age.substring(0, age.indexOf(":")); max = age.substring(age.indexOf(":") + 1, age.length()); aRange = new SimpleRange("date_Listing_Modification", min, max); } else if (age.endsWith("+")) { // System.out.println("SqFt+ -->>"+sqFt); min = age.substring(0, age.indexOf("+")); aRange = new SimpleRange("date_Listing_Modification", min, null); } else if (age.endsWith("-")) { // System.out.println("SqFt- -->>"+sqFt); max = age.substring(0, age.indexOf("-")); aRange = new SimpleRange("date_Listing_Modification", null, max); } else if (age.length() > 0) { min = age.substring(0, age.length()); max = min; aRange = new SimpleRange("date_Listing_Modification", min, max); } else { aRange = new SimpleRange("date_Listing_Modification", null, null); } System.out.println("Range is " + aRange.getMinValue() + ", " + aRange.getMaxValue()); rangeVector.add(aRange); } } // Range for Longitude if (request.getParameter("Longitude") != null) { SimpleRange aRange; String longitude = request.getParameter("Longitude"); System.out.println("Longitude is " + longitude); String min = ""; String max = ""; if (longitude.indexOf(":") != -1) { min = longitude.substring(0, longitude.indexOf(":")); max = longitude.substring(longitude.indexOf(":") + 1, longitude.length()); aRange = new SimpleRange("_long", min, max); } else { aRange = new SimpleRange("_long", null, null); } rangeVector.add(aRange); } // Range for Latitude if (request.getParameter("Latitude") != null) { SimpleRange aRange; String latitude = request.getParameter("Latitude"); System.out.println("Latitude is " + latitude); String min = ""; String max = ""; if (latitude.indexOf(":") != -1) { min = latitude.substring(0, latitude.indexOf(":")); max = latitude.substring(latitude.indexOf(":") + 1, latitude.length()); aRange = new SimpleRange("lat", min, max); } else { aRange = new SimpleRange("lat", null, null); } rangeVector.add(aRange); } // Near by homes // Format required is Latitude,Longitude,distance if (request.getParameter("NBH") != null) { String nbh = request.getParameter("NBH"); String[] s = nbh.split(","); if (s.length == 3) { Float f = Float.valueOf(s[2]); if (f >= 10) // 10 miles radius max s[2] = "10"; else if (f < 0) // if negative distance s[2] = "1"; geoParam = new GeoParameter(s[0], s[1], s[2]); } } else { // City and Zip are optional if NBH is provided. if (request.getParameter("Zip") != null) { FilterItem filterItem = new FilterItem(); filterItem.setField("zipCode"); // remove the space first String inZipcode = request.getParameter("Zip"); StringBuffer zipBuffer = new StringBuffer(); if (inZipcode.indexOf(",") > -1) { StringTokenizer sToken = new StringTokenizer(inZipcode, ","); while (sToken.hasMoreElements()) { String object = (String) sToken.nextElement(); zipBuffer.append("'"); zipBuffer.append(object); zipBuffer.append("'"); if (sToken.countTokens() > 0) zipBuffer.append(","); } } else { zipBuffer.append("'"); zipBuffer.append(inZipcode); zipBuffer.append("'"); } //System.out.println(zipBuffer.toString()); filterItem.setValue(zipBuffer.toString()); multipleFilterItemArrayList.add(filterItem); } if (request.getParameter("City") != null) { FilterItem filterItem = new FilterItem(); filterItem.setField("name_City"); String cityList = request.getParameter("City"); StringBuffer cityMod = new StringBuffer(); if (cityList.indexOf(",") > -1) { StringTokenizer sToken = new StringTokenizer(cityList, ","); while (sToken.hasMoreElements()) { String object = (String) sToken.nextElement(); cityMod.append("'"); cityMod.append(getCity(object)); cityMod.append("'"); if (sToken.countTokens() > 0) cityMod.append(","); } } else { cityMod.append("'"); cityMod.append(getCity(cityList)); cityMod.append("'"); } filterItem.setValue(cityMod.toString()); multipleFilterItemArrayList.add(filterItem); } } // Status of property, link Active or Pending // For backward compatibility, Status=A. we added extra checks // for Status=ACTIVE or PENDING /* * if(request.getParameter("Status") != null && (request.getParameter("Status").equalsIgnoreCase("ACTIVE")|| request.getParameter("Status").equalsIgnoreCase("PENDING"))){ FilterItem filterItem = new FilterItem(); filterItem.setField("status_Listing"); filterItem.setValue(request.getParameter("Status")); if (request.getParameter("Status").equalsIgnoreCase("PENDING")){ filterItem.setValue(propServices.getPendingStatus()); } filterItemArrayList.add(filterItem); } */ if (request.getParameter("Status") != null && (request.getParameter("Status").equalsIgnoreCase("ACTIVE") || request.getParameter("Status").equalsIgnoreCase("PENDING"))) { FilterItem filterItem = new FilterItem(); filterItem.setField("status_Listing"); StringBuffer statusMod = new StringBuffer(); String statusList = null; if (request.getParameter("Status").equalsIgnoreCase("ACTIVE")) { statusList = propServices.getActiveStatus(); } else if (request.getParameter("Status").equalsIgnoreCase("PENDING")) { statusList = propServices.getPendingStatus(); } if (statusList.indexOf(",") > -1) { StringTokenizer sToken = new StringTokenizer(statusList, ","); while (sToken.hasMoreElements()) { String object = (String) sToken.nextElement(); statusMod.append("'"); statusMod.append(object); statusMod.append("'"); if (sToken.countTokens() > 0) statusMod.append(","); } } else { statusMod.append("'"); statusMod.append(statusList); statusMod.append("'"); } System.out.println("Status query..: " + statusMod.toString()); filterItem.setValue(statusMod.toString()); multipleFilterItemArrayList.add(filterItem); } if (request.getParameter("ListingId") != null) { FilterItem filterItem = new FilterItem(); filterItem.setField("number_MLS"); String listingId = request.getParameter("ListingId"); String mlsNumberPrefix = propServices.getMlsNumberPrefix(); StringBuffer listingIdList = new StringBuffer(); if (listingId.indexOf(",") > -1) { StringTokenizer sToken = new StringTokenizer(listingId, ","); while (sToken.hasMoreElements()) { String object = (String) sToken.nextElement(); if ((mlsNumberPrefix != null) && (!mlsNumberPrefix.equals("")) && (!object.contains(mlsNumberPrefix))) { listingIdList.append("'" + mlsNumberPrefix); } else { listingIdList.append("'"); } listingIdList.append(object); listingIdList.append("'"); if (sToken.countTokens() > 0) listingIdList.append(","); } } else { if ((mlsNumberPrefix != null) && (!mlsNumberPrefix.equals("")) && (!listingId.contains(mlsNumberPrefix))) listingIdList.append("'" + mlsNumberPrefix); else listingIdList.append("'"); listingIdList.append(listingId); listingIdList.append("'"); } filterItem.setValue(listingIdList.toString()); multipleFilterItemArrayList.add(filterItem); //System.out.println("got listing id "+ request.getParameter("ListingId")); } if (request.getParameter("ListingAgentLic") != null) { FilterItem filterItem = new FilterItem(); filterItem.setField("listing_license_number"); String listingId = request.getParameter("ListingAgentLic"); if (listingId.indexOf(",") > -1) { StringTokenizer sToken = new StringTokenizer(listingId, ","); while (sToken.hasMoreElements()) { keywordArrayList.add((String) sToken.nextElement()); } } else { keywordArrayList.add(listingId); } //System.out.println("got listing agent lic "+ request.getParameter("ListingAgentLic")); } if (request.getParameter("offset") != null) { start = Integer.parseInt(request.getParameter("offset")); } if (request.getParameter("limit") != null) { limit = Integer.parseInt(request.getParameter("limit")); } String sort = request.getParameter("sort"); if (sort != null) { if (sort.equalsIgnoreCase("City")) { sort = "name_City"; } else if (sort.equalsIgnoreCase("YearBuilt")) { sort = "year_Built"; } else if (sort.equalsIgnoreCase("ListPrice")) { sort = "price_List"; } else if (sort.equalsIgnoreCase("Sqft")) { sort = "sqft_Structure"; } else if (sort.equalsIgnoreCase("LotSqFt")) { sort = "Size_Lot"; } else if (sort.equalsIgnoreCase("Type")) { sort = ""; } else if (sort.equalsIgnoreCase("Bedrooms")) { sort = "number_beds_Total"; } else if (sort.equalsIgnoreCase("FullBathrooms")) { sort = "number_baths_Full"; } else if (sort.equalsIgnoreCase("ExteriorFeatures")) { sort = "type_Property"; } else if (sort.equalsIgnoreCase("none")) { sort = null; } } String sort_direction = request.getParameter("sort_direction"); if (sort_direction != null) { if (sort_direction.equalsIgnoreCase("none")) { sort_direction = null; } else if (sort_direction.equalsIgnoreCase("ASC")) { sort_direction = "asc"; } else { sort_direction = "desc"; } } else { //{TOD: why do we need this?? if (request.getParameter("ListingAgentLic") != null) { sort = "price_List"; sort_direction = "desc"; // with agent listing, they want desc } else { sort_direction = "asc"; // default sorting order } } // Type of property, link Single Family, Townhouse, Condominium if (request.getParameter("ExteriorFeatures") != null) { String param = request.getParameter("ExteriorFeatures"); FilterItem filterItem = new FilterItem(); filterItem.setField("type_Property"); List<ExteriorFeaturesData> extFeatureData = propServices.getExtFeaturesData(); // Getting ExFeatures list from properties files if (extFeatureData != null) { System.out.println("Exterior Features param is " + param); for (ExteriorFeaturesData efd : extFeatureData) { if (efd.getName().equalsIgnoreCase(param)) { filterItem.setValue(efd.getInSearchFields()); break; } } if (filterItem.getValue() != null) { System.out.println("Exterior Features value " + filterItem.getValue()); multipleFilterItemArrayList.add(filterItem); } } else {// Getting ExFeatures list from DB filterItem.setValue(param); System.out.println("Exterior Features (single) " + filterItem.getValue()); filterItemArrayList.add(filterItem); } } // Adding the search parameter for Full Address if (request.getParameter("FullAddress") != null) { FilterItem filterItem = new FilterItem(); filterItem.setField("address_Filtered"); filterItem.setValue(request.getParameter("FullAddress")); filterItemArrayList.add(filterItem); } boolean returnOpenHouseData = false; if (request.getParameter("OpenHouse") != null) { if (request.getParameter("OpenHouse").equals("1")) { returnOpenHouseData = true; } } // Put the keyword search (using it for license id) String[] filterArrayKeyword = new String[keywordArrayList.size()]; filterArrayKeyword = keywordArrayList.toArray(filterArrayKeyword); filer.setKeywords(filterArrayKeyword); // Put range in the filter SimpleRange[] sRangeArray = new SimpleRange[rangeVector.size()]; sRangeArray = rangeVector.toArray(sRangeArray); filer.setRanges(sRangeArray); // Put single value item in the filter with '%value%' FilterItem[] filterArray = new FilterItem[filterItemArrayList.size()]; filterArray = filterItemArrayList.toArray(filterArray); filer.setFilters(filterArray); // Put single value item in the filter, with exact search with 'value' FilterItem[] exactFilterArray = new FilterItem[exactFilterItemArrayList.size()]; exactFilterArray = exactFilterItemArrayList.toArray(exactFilterArray); filer.setExactFilters(exactFilterArray); // Put the multiple values (',' separated) item in the filter. FilterItem[] filterItemA = new FilterItem[multipleFilterItemArrayList.size()]; filterItemA = multipleFilterItemArrayList.toArray(filterItemA); filer.setSearchForFieldItems(filterItemA); //System.out.println("time in making query:"+(new Date().getTime()-startTime)+" msecs"); //System.out.println("limit " + request.getParameter("limit") + ", offset " + // request.getParameter("offset") +", sort " + sort + ", sort direction "+ sort_direction); Object returnObj = null; startTime = new Date().getTime(); // Create a Timer and a TimerTask Timer timer = new Timer(); TimerTask task = new SearchPropertyTimerTask(request, response, this.getOutputType()); // Set timer for 30 sec, method takes args in milliseconds. timer.schedule(task, 30 * 1000); boolean timedoutResponse = true;// Default is timed out response. try { /* for testing of timer functionality. try { Thread.sleep(10000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); }*/ Properties prop = propServices.searchForProperties(start, limit, sort, sort_direction, filer, geoParam, returnOpenHouseData); prop.setElapsedTime(BigInteger.valueOf(System.currentTimeMillis() - reqInputArrivalTime)); if (this.getOutputType().equalsIgnoreCase("json")) { returnObj = getJSONReturnObj(prop); } else { returnObj = prop; } } catch (LargeResultSetException e) { Errors errors = new Errors(); com.irets.generated.Error error = new com.irets.generated.Error(); error.setCode(e.getErrorCode()); error.setDescription(e.getMessage()); errors.getError().add(error); errors.setTotalcount(BigInteger.valueOf(e.getTotalCount())); errors.setElapsedtime(BigInteger.valueOf(System.currentTimeMillis() - reqInputArrivalTime)); returnObj = errors; System.out.println(e.getMessage()); } finally { if (task.cancel()) { timedoutResponse = false;// No timeout, send normal response. } } System.out.println("time in database call:" + (new Date().getTime() - startTime) + " msecs"); //startTime = new Date().getTime(); //GSONHelper.serializeToJSON(prop, response.getOutputStream()); if (!timedoutResponse) { if (this.getOutputType().equalsIgnoreCase("json")) { response.setContentType("application/json"); JacksonJSONHelper.serializeToJSON(returnObj, response.getOutputStream(), response); } else { response.setContentType("text/xml"); JAXBHelper.serializeToXML(returnObj, response.getOutputStream()); } } //System.out.println("time in making output:"+(new Date().getTime()-startTime)+" msecs"); System.out.println("Done!!!! elapsed time: " + (System.currentTimeMillis() - reqInputArrivalTime)); }
From source file:org.LexGrid.LexBIG.caCore.web.util.LexEVSHTTPUtils.java
/** * Returns fully qualified search class names * @param searchClasses - specifies the search class names * @param packageName - specifies the package name * @return// w w w .ja va 2 s. c o m */ private String getSearchClassNames(String searchClasses) throws Exception { String path = ""; /** if(packageName != null && !(targetClassName.indexOf(SystemConstant.DOT)>0) && (targetClassName.indexOf(",")<0)){ targetClassName = packageName +SystemConstant.DOT+targetClassName; } **/ String delimiter = null; if (searchClasses.indexOf(SystemConstant.FORWARD_SLASH) > 0) { delimiter = SystemConstant.FORWARD_SLASH_STR; } else { delimiter = SystemConstant.COMMA_STR; } StringTokenizer st = new StringTokenizer(searchClasses, delimiter); String className = st.nextToken(); if (className.indexOf(SystemConstant.DOT) > 0) { path = className; } else { path = classCache.getQualifiedClassName(className); } if (st.countTokens() > 0) { while (st.hasMoreElements()) { className = st.nextToken().trim(); if (className.indexOf(SystemConstant.DOT) > 0) { path += SystemConstant.COMMA + className; } else { path += SystemConstant.COMMA + classCache.getQualifiedClassName(className); } } } return path; }