id
int64
22
34.9k
comment_id
int64
0
328
comment
stringlengths
2
2.55k
code
stringlengths
31
107k
classification
stringclasses
6 values
isFinished
bool
1 class
code_context_2
stringlengths
21
27.3k
code_context_10
stringlengths
29
27.3k
code_context_20
stringlengths
29
27.3k
25,117
4
// Do nothing
private void cleanProxy(SdlDisconnectedReason disconnectedReason) throws SdlException { try { // ALM Specific Cleanup if (_advancedLifecycleManagementEnabled) { _sdlConnectionState = SdlConnectionState.SDL_DISCONNECTED; firstTimeFull = true; // Should we wait for the interface to be unregistered? Boolean waitForInterfaceUnregistered = false; // Unregister app interface synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null && sdlSession.getIsConnected() && getAppInterfaceRegistered()) { waitForInterfaceUnregistered = true; unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID); } } // Wait for the app interface to be unregistered if (waitForInterfaceUnregistered) { synchronized(APP_INTERFACE_REGISTERED_LOCK) { try { APP_INTERFACE_REGISTERED_LOCK.wait(3000); } catch (InterruptedException e) { // Do nothing } } } } if(rpcResponseListeners != null){ rpcResponseListeners.clear(); } if(rpcNotificationListeners != null){ rpcNotificationListeners.clear(); //TODO make sure we want to clear this } // Clean up SDL Connection synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null) sdlSession.close(); } } catch (SdlException e) { throw e; } finally { SdlTrace.logProxyEvent("SdlProxy cleaned.", SDL_LIB_TRACE_KEY); } }
NONSATD
true
APP_INTERFACE_REGISTERED_LOCK.wait(3000); } catch (InterruptedException e) { // Do nothing } }
waitForInterfaceUnregistered = true; unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID); } } // Wait for the app interface to be unregistered if (waitForInterfaceUnregistered) { synchronized(APP_INTERFACE_REGISTERED_LOCK) { try { APP_INTERFACE_REGISTERED_LOCK.wait(3000); } catch (InterruptedException e) { // Do nothing } } } } if(rpcResponseListeners != null){ rpcResponseListeners.clear(); } if(rpcNotificationListeners != null){ rpcNotificationListeners.clear(); //TODO make sure we want to clear this }
try { // ALM Specific Cleanup if (_advancedLifecycleManagementEnabled) { _sdlConnectionState = SdlConnectionState.SDL_DISCONNECTED; firstTimeFull = true; // Should we wait for the interface to be unregistered? Boolean waitForInterfaceUnregistered = false; // Unregister app interface synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null && sdlSession.getIsConnected() && getAppInterfaceRegistered()) { waitForInterfaceUnregistered = true; unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID); } } // Wait for the app interface to be unregistered if (waitForInterfaceUnregistered) { synchronized(APP_INTERFACE_REGISTERED_LOCK) { try { APP_INTERFACE_REGISTERED_LOCK.wait(3000); } catch (InterruptedException e) { // Do nothing } } } } if(rpcResponseListeners != null){ rpcResponseListeners.clear(); } if(rpcNotificationListeners != null){ rpcNotificationListeners.clear(); //TODO make sure we want to clear this } // Clean up SDL Connection synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null) sdlSession.close(); } } catch (SdlException e) { throw e; } finally { SdlTrace.logProxyEvent("SdlProxy cleaned.", SDL_LIB_TRACE_KEY); } }
25,117
5
//TODO make sure we want to clear this
private void cleanProxy(SdlDisconnectedReason disconnectedReason) throws SdlException { try { // ALM Specific Cleanup if (_advancedLifecycleManagementEnabled) { _sdlConnectionState = SdlConnectionState.SDL_DISCONNECTED; firstTimeFull = true; // Should we wait for the interface to be unregistered? Boolean waitForInterfaceUnregistered = false; // Unregister app interface synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null && sdlSession.getIsConnected() && getAppInterfaceRegistered()) { waitForInterfaceUnregistered = true; unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID); } } // Wait for the app interface to be unregistered if (waitForInterfaceUnregistered) { synchronized(APP_INTERFACE_REGISTERED_LOCK) { try { APP_INTERFACE_REGISTERED_LOCK.wait(3000); } catch (InterruptedException e) { // Do nothing } } } } if(rpcResponseListeners != null){ rpcResponseListeners.clear(); } if(rpcNotificationListeners != null){ rpcNotificationListeners.clear(); //TODO make sure we want to clear this } // Clean up SDL Connection synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null) sdlSession.close(); } } catch (SdlException e) { throw e; } finally { SdlTrace.logProxyEvent("SdlProxy cleaned.", SDL_LIB_TRACE_KEY); } }
DESIGN
true
} if(rpcNotificationListeners != null){ rpcNotificationListeners.clear(); //TODO make sure we want to clear this } // Clean up SDL Connection
} catch (InterruptedException e) { // Do nothing } } } } if(rpcResponseListeners != null){ rpcResponseListeners.clear(); } if(rpcNotificationListeners != null){ rpcNotificationListeners.clear(); //TODO make sure we want to clear this } // Clean up SDL Connection synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null) sdlSession.close(); } } catch (SdlException e) { throw e; } finally { SdlTrace.logProxyEvent("SdlProxy cleaned.", SDL_LIB_TRACE_KEY); }
if (sdlSession != null && sdlSession.getIsConnected() && getAppInterfaceRegistered()) { waitForInterfaceUnregistered = true; unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID); } } // Wait for the app interface to be unregistered if (waitForInterfaceUnregistered) { synchronized(APP_INTERFACE_REGISTERED_LOCK) { try { APP_INTERFACE_REGISTERED_LOCK.wait(3000); } catch (InterruptedException e) { // Do nothing } } } } if(rpcResponseListeners != null){ rpcResponseListeners.clear(); } if(rpcNotificationListeners != null){ rpcNotificationListeners.clear(); //TODO make sure we want to clear this } // Clean up SDL Connection synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null) sdlSession.close(); } } catch (SdlException e) { throw e; } finally { SdlTrace.logProxyEvent("SdlProxy cleaned.", SDL_LIB_TRACE_KEY); } }
25,117
6
// Clean up SDL Connection
private void cleanProxy(SdlDisconnectedReason disconnectedReason) throws SdlException { try { // ALM Specific Cleanup if (_advancedLifecycleManagementEnabled) { _sdlConnectionState = SdlConnectionState.SDL_DISCONNECTED; firstTimeFull = true; // Should we wait for the interface to be unregistered? Boolean waitForInterfaceUnregistered = false; // Unregister app interface synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null && sdlSession.getIsConnected() && getAppInterfaceRegistered()) { waitForInterfaceUnregistered = true; unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID); } } // Wait for the app interface to be unregistered if (waitForInterfaceUnregistered) { synchronized(APP_INTERFACE_REGISTERED_LOCK) { try { APP_INTERFACE_REGISTERED_LOCK.wait(3000); } catch (InterruptedException e) { // Do nothing } } } } if(rpcResponseListeners != null){ rpcResponseListeners.clear(); } if(rpcNotificationListeners != null){ rpcNotificationListeners.clear(); //TODO make sure we want to clear this } // Clean up SDL Connection synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null) sdlSession.close(); } } catch (SdlException e) { throw e; } finally { SdlTrace.logProxyEvent("SdlProxy cleaned.", SDL_LIB_TRACE_KEY); } }
NONSATD
true
rpcNotificationListeners.clear(); //TODO make sure we want to clear this } // Clean up SDL Connection synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null) sdlSession.close();
} } } } if(rpcResponseListeners != null){ rpcResponseListeners.clear(); } if(rpcNotificationListeners != null){ rpcNotificationListeners.clear(); //TODO make sure we want to clear this } // Clean up SDL Connection synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null) sdlSession.close(); } } catch (SdlException e) { throw e; } finally { SdlTrace.logProxyEvent("SdlProxy cleaned.", SDL_LIB_TRACE_KEY); } }
unregisterAppInterfacePrivate(UNREGISTER_APP_INTERFACE_CORRELATION_ID); } } // Wait for the app interface to be unregistered if (waitForInterfaceUnregistered) { synchronized(APP_INTERFACE_REGISTERED_LOCK) { try { APP_INTERFACE_REGISTERED_LOCK.wait(3000); } catch (InterruptedException e) { // Do nothing } } } } if(rpcResponseListeners != null){ rpcResponseListeners.clear(); } if(rpcNotificationListeners != null){ rpcNotificationListeners.clear(); //TODO make sure we want to clear this } // Clean up SDL Connection synchronized(CONNECTION_REFERENCE_LOCK) { if (sdlSession != null) sdlSession.close(); } } catch (SdlException e) { throw e; } finally { SdlTrace.logProxyEvent("SdlProxy cleaned.", SDL_LIB_TRACE_KEY); } }
25,136
0
/* * TODO(cpovirk): make SleepingStopwatch the last parameter throughout the class so that the * overloads follow the usual convention: Foo(int), Foo(int, SleepingStopwatch) */
@VisibleForTesting static RateLimiter create(SleepingStopwatch stopwatch, double permitsPerSecond) { RateLimiter rateLimiter = new SmoothBursty(stopwatch, 1.0 /* maxBurstSeconds */); rateLimiter.setRate(permitsPerSecond); return rateLimiter; }
IMPLEMENTATION
true
@VisibleForTesting static RateLimiter create(SleepingStopwatch stopwatch, double permitsPerSecond) { RateLimiter rateLimiter = new SmoothBursty(stopwatch, 1.0 /* maxBurstSeconds */); rateLimiter.setRate(permitsPerSecond); return rateLimiter; }
@VisibleForTesting static RateLimiter create(SleepingStopwatch stopwatch, double permitsPerSecond) { RateLimiter rateLimiter = new SmoothBursty(stopwatch, 1.0 /* maxBurstSeconds */); rateLimiter.setRate(permitsPerSecond); return rateLimiter; }
@VisibleForTesting static RateLimiter create(SleepingStopwatch stopwatch, double permitsPerSecond) { RateLimiter rateLimiter = new SmoothBursty(stopwatch, 1.0 /* maxBurstSeconds */); rateLimiter.setRate(permitsPerSecond); return rateLimiter; }
25,136
1
/* maxBurstSeconds */
@VisibleForTesting static RateLimiter create(SleepingStopwatch stopwatch, double permitsPerSecond) { RateLimiter rateLimiter = new SmoothBursty(stopwatch, 1.0 /* maxBurstSeconds */); rateLimiter.setRate(permitsPerSecond); return rateLimiter; }
NONSATD
true
@VisibleForTesting static RateLimiter create(SleepingStopwatch stopwatch, double permitsPerSecond) { RateLimiter rateLimiter = new SmoothBursty(stopwatch, 1.0 /* maxBurstSeconds */); rateLimiter.setRate(permitsPerSecond); return rateLimiter;
@VisibleForTesting static RateLimiter create(SleepingStopwatch stopwatch, double permitsPerSecond) { RateLimiter rateLimiter = new SmoothBursty(stopwatch, 1.0 /* maxBurstSeconds */); rateLimiter.setRate(permitsPerSecond); return rateLimiter; }
@VisibleForTesting static RateLimiter create(SleepingStopwatch stopwatch, double permitsPerSecond) { RateLimiter rateLimiter = new SmoothBursty(stopwatch, 1.0 /* maxBurstSeconds */); rateLimiter.setRate(permitsPerSecond); return rateLimiter; }
16,946
0
//================= runXmlReplayFile ======================================================
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
NONSATD
true
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
16,946
1
//Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc.
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
NONSATD
true
String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir);
String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document);
16,946
2
//will check full path first, then checks relative to PWD.
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
NONSATD
true
String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test.");
List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; }
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap;
16,946
3
//controlFileName is just the short name, without the full path.
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
NONSATD
true
authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:"
throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================"
throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); }
16,946
4
// Used for expression language expansion from uri field.
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
NONSATD
true
testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap;
+"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']");
String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID");
16,946
5
//MapContext(); //Get a new JexlContext for each test group.
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
NONSATD
true
evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS");
if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1;
+ (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) {
16,946
6
// // Figure out if we will auto delete resources
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
NONSATD
true
String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>();
String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort;
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO;
16,946
7
//else just run with current from last loop;
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
NONSATD
true
} if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){
if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes");
String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir);
16,946
8
//System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts);
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
NONSATD
true
if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult;
if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){
} if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0);
16,946
9
//vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode.
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
NONSATD
true
uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){
PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult);
Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID;
16,946
10
//if (isPOST){
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
NONSATD
true
} results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //}
Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){
testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0;
16,946
11
//PUTs do not return a Location, so don't add PUTs to serviceResultsMap.
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
NONSATD
true
results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri);
if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes;
} if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID;
16,946
12
//}
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
NONSATD
true
//if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){
vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; }
if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL);
16,946
13
//gotExpectedResult depends on serviceResult.expectedCodes.
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
NONSATD
true
} results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); }
} else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID);
serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){
16,946
14
//TODO: empty for now, later may pick up from XML control file.
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
DESIGN
true
} else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult);
serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method;
} } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; }
16,946
15
//===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //=====================================================
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
NONSATD
true
serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct);
if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); }
serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) {
16,946
16
//=== Now spit out the HTML report file ===
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
NONSATD
true
} } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory.
ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results;
if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
16,946
17
//don't instantiate, just use File to extract file name without directory.
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
NONSATD
true
//=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName);
serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
16,946
18
//================================
public static List<ServiceResult> runXmlReplayFile(String xmlReplayBaseDir, String controlFileName, String testGroupID, String oneTestID, Map<String, ServiceResult> serviceResultsMap, boolean param_autoDeletePOSTS, Dump dump, String protoHostPortParam, AuthsMap defaultAuths, List<String> reportsList, String reportsDir) throws Exception { //Internally, we maintain two collections of ServiceResult: // the first is the return value of this method. // the second is the serviceResultsMap, which is used for keeping track of CSIDs created by POSTs, for later reference by DELETE, etc. List<ServiceResult> results = new ArrayList<ServiceResult>(); XmlReplayReport report = new XmlReplayReport(reportsDir); String controlFile = Tools.glue(xmlReplayBaseDir, "/", controlFileName); org.dom4j.Document document; document = getDocument(controlFile); //will check full path first, then checks relative to PWD. if (document==null){ throw new FileNotFoundException("XmlReplay control file ("+controlFileName+") not found in basedir: "+xmlReplayBaseDir+" Exiting test."); } String protoHostPort; if (Tools.isEmpty(protoHostPortParam)){ protoHostPort = document.selectSingleNode("/xmlReplay/protoHostPort").getText().trim(); System.out.println("DEPRECATED: Using protoHostPort ('"+protoHostPort+"') from xmlReplay file ('"+controlFile+"'), not master."); } else { protoHostPort = protoHostPortParam; } if (Tools.isEmpty(protoHostPort)){ throw new Exception("XmlReplay control file must have a protoHostPort element"); } String authsMapINFO; AuthsMap authsMap = readAuths(document); if (authsMap.map.size()==0){ authsMap = defaultAuths; authsMapINFO = "Using defaultAuths from master file: "+defaultAuths; } else { authsMapINFO = "Using AuthsMap from control file: "+authsMap; } report.addTestGroup(testGroupID, controlFileName); //controlFileName is just the short name, without the full path. String xmlReplayHeader = "========================================================================" +"\r\nXmlReplay running:" +"\r\n controlFile: "+ (new File(controlFile).getCanonicalPath()) +"\r\n protoHostPort: "+protoHostPort +"\r\n testGroup: "+testGroupID + (Tools.notEmpty(oneTestID) ? "\r\n oneTestID: "+oneTestID : "") +"\r\n AuthsMap: "+authsMapINFO +"\r\n param_autoDeletePOSTS: "+param_autoDeletePOSTS +"\r\n Dump info: "+dump +"\r\n========================================================================" +"\r\n"; report.addRunInfo(xmlReplayHeader); System.out.println(xmlReplayHeader); String autoDeletePOSTS = ""; List<Node> testgroupNodes; if (Tools.notEmpty(testGroupID)){ testgroupNodes = document.selectNodes("//testGroup[@ID='"+testGroupID+"']"); } else { testgroupNodes = document.selectNodes("//testGroup"); } JexlEngine jexl = new JexlEngine(); // Used for expression language expansion from uri field. XmlReplayEval evalStruct = new XmlReplayEval(); evalStruct.serviceResultsMap = serviceResultsMap; evalStruct.jexl = jexl; for (Node testgroup : testgroupNodes) { XmlReplayEval.MapContextWKeys jc = new XmlReplayEval.MapContextWKeys();//MapContext(); //Get a new JexlContext for each test group. evalStruct.jc = jc; autoDeletePOSTS = testgroup.valueOf("@autoDeletePOSTS"); List<Node> tests; if (Tools.notEmpty(oneTestID)){ tests = testgroup.selectNodes("test[@ID='"+oneTestID+"']"); } else { tests = testgroup.selectNodes("test"); } String authForTest = ""; int testElementIndex = -1; for (Node testNode : tests) { long startTime = System.currentTimeMillis(); try { testElementIndex++; String testID = testNode.valueOf("@ID"); // // Figure out if we will auto delete resources boolean autoDelete = param_autoDeletePOSTS; String autoDeleteValue = testNode.valueOf("@autoDeletePOSTS"); if (autoDeleteValue != null && !autoDeleteValue.trim().isEmpty()) { autoDelete = Boolean.valueOf(autoDeleteValue).booleanValue(); } String testIDLabel = Tools.notEmpty(testID) ? (testGroupID+'.'+testID) : (testGroupID+'.'+testElementIndex); String method = testNode.valueOf("method"); String contentType = testNode.valueOf("contentType"); String uri = testNode.valueOf("uri"); String fullURL = Tools.glue(protoHostPort, "/", uri); if (contentType == null || contentType.equals("")) { contentType = XmlReplayTransport.APPLICATION_XML; } String currentAuthForTest = null; String authIDForTest = testNode.valueOf("@auth"); if (Tools.notEmpty(authIDForTest)){ currentAuthForTest = authsMap.map.get(authIDForTest); } else { String tokenAuthExpression = testNode.valueOf("@tokenauth"); if (Tools.notEmpty(tokenAuthExpression)){ currentAuthForTest = "Bearer " + evalStruct.eval(tokenAuthExpression, serviceResultsMap, null, jexl, jc); } } if (Tools.notEmpty(currentAuthForTest)){ authForTest = currentAuthForTest; //else just run with current from last loop; } if (Tools.isEmpty(authForTest)){ authForTest = defaultAuths.getDefaultAuth(); } if (uri.indexOf("$")>-1){ uri = evalStruct.eval(uri, serviceResultsMap, null, jexl, jc); } fullURL = fixupFullURL(fullURL, protoHostPort, uri); List<Integer> expectedCodes = new ArrayList<Integer>(); String expectedCodesStr = testNode.valueOf("expectedCodes"); if (Tools.notEmpty(expectedCodesStr)){ String[] codesArray = expectedCodesStr.split(","); for (String code : codesArray){ expectedCodes.add(new Integer(code.trim())); } } Node responseNode = testNode.selectSingleNode("response"); PartsStruct expectedResponseParts = null; if (responseNode!=null){ expectedResponseParts = PartsStruct.readParts(responseNode, testID, xmlReplayBaseDir); //System.out.println("reponse parts: >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"+expectedResponseParts); } ServiceResult serviceResult; boolean isPOST = method.equalsIgnoreCase("POST"); boolean isPUT = method.equalsIgnoreCase("PUT"); if ( isPOST || isPUT ) { PartsStruct parts = PartsStruct.readParts(testNode, testID, xmlReplayBaseDir); if (Tools.notEmpty(parts.overrideTestID)) { testID = parts.overrideTestID; } if (isPOST){ String csid = CSIDfromTestID(testNode, serviceResultsMap); if (Tools.notEmpty(csid)) uri = Tools.glue(uri, "/", csid+"/items/"); } else if (isPUT) { uri = fromTestID(uri, testNode, serviceResultsMap); } //vars only make sense in two contexts: POST/PUT, because you are submitting another file with internal expressions, // and in <response> nodes. For GET, DELETE, there is no payload, so all the URLs with potential expressions are right there in the testNode. Map<String,String> vars = null; if (parts.varsList.size()>0){ vars = parts.varsList.get(0); } serviceResult = XmlReplayTransport.doPOST_PUTFromXML(parts.responseFilename, vars, protoHostPort, uri, method, contentType, evalStruct, authForTest, testIDLabel); serviceResult.autoDelete = autoDelete; if (vars!=null) { serviceResult.addVars(vars); } results.add(serviceResult); //if (isPOST){ serviceResultsMap.put(testID, serviceResult); //PUTs do not return a Location, so don't add PUTs to serviceResultsMap. //} fullURL = fixupFullURL(fullURL, protoHostPort, uri); } else if (method.equalsIgnoreCase("DELETE")){ String fromTestID = testNode.valueOf("fromTestID"); ServiceResult pr = serviceResultsMap.get(fromTestID); if (pr!=null){ serviceResult = XmlReplayTransport.doDELETE(pr.deleteURL, authForTest, testIDLabel, fromTestID); serviceResult.fromTestID = fromTestID; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } results.add(serviceResult); if (serviceResult.codeInSuccessRange(serviceResult.responseCode)){ //gotExpectedResult depends on serviceResult.expectedCodes. serviceResultsMap.remove(fromTestID); } } else { if (Tools.notEmpty(fromTestID)){ serviceResult = new ServiceResult(); serviceResult.responseCode = 0; serviceResult.error = "ID not found in element fromTestID: "+fromTestID; System.err.println("****\r\nServiceResult: "+serviceResult.error+". SKIPPING TEST. Full URL: "+fullURL); } else { serviceResult = XmlReplayTransport.doDELETE(fullURL, authForTest, testID, fromTestID); } serviceResult.fromTestID = fromTestID; results.add(serviceResult); } } else if (method.equalsIgnoreCase("GET")){ fullURL = fromTestID(fullURL, testNode, serviceResultsMap); serviceResult = XmlReplayTransport.doGET(fullURL, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else if (method.equalsIgnoreCase("LIST")){ fullURL = fixupFullURL(fullURL, protoHostPort, uri); String listQueryParams = ""; //TODO: empty for now, later may pick up from XML control file. serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); } System.out.println(timeString()+" "+leader+serviceResultRow+"\r\n"); if (dump.payloads || (doingAuto&&hasError) ) { if (Tools.notBlank(serviceResult.requestPayload)){ System.out.println("\r\n========== request payload ==============="); System.out.println(serviceResult.requestPayload); System.out.println("==========================================\r\n"); } } if (dump.payloads || (doingAuto&&hasError)) { if (Tools.notBlank(serviceResult.result)){ System.out.println("\r\n========== response payload =============="); System.out.println(serviceResult.result); System.out.println("==========================================\r\n"); } } } catch (Throwable t) { String msg = "ERROR: XmlReplay experienced an error in a test node: "+testNode+" Throwable: "+t; System.out.println(msg); System.out.println(Tools.getStackTrace(t)); ServiceResult serviceResult = new ServiceResult(); serviceResult.error = msg; serviceResult.failureReason = " : SYSTEM ERROR; "; results.add(serviceResult); } } if (Tools.isTrue(autoDeletePOSTS) && param_autoDeletePOSTS){ autoDelete(serviceResultsMap, "default", 0); } } //=== Now spit out the HTML report file === File m = new File(controlFileName); String localName = m.getName();//don't instantiate, just use File to extract file name without directory. String reportName = localName+'-'+testGroupID+".html"; File resultFile = report.saveReport(xmlReplayBaseDir, reportsDir, reportName); if (resultFile!=null) { String toc = report.getTOC(reportName); reportsList.add(toc); } //================================ return results; }
NONSATD
true
serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //=====================================================
if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){
serviceResult = XmlReplayTransport.doLIST(fullURL, listQueryParams, authForTest, testIDLabel); results.add(serviceResult); serviceResultsMap.put(testID, serviceResult); } else { throw new Exception("HTTP method not supported by XmlReplay: "+method); } serviceResult.testID = testID; serviceResult.fullURL = fullURL; serviceResult.auth = authForTest; serviceResult.method = method; if (expectedCodes.size()>0){ serviceResult.expectedCodes = expectedCodes; } if (Tools.isEmpty(serviceResult.testID)) serviceResult.testID = testIDLabel; if (Tools.isEmpty(serviceResult.testGroupID)) serviceResult.testGroupID = testGroupID; Node expectedLevel = testNode.selectSingleNode("response/expected"); if (expectedLevel!=null){ String level = expectedLevel.valueOf("@level"); serviceResult.payloadStrictness = level; } //===================================================== // ALL VALIDATION FOR ALL REQUESTS IS DONE HERE: //===================================================== boolean hasError = false; String vError = validateResponse(serviceResult, serviceResultsMap, expectedResponseParts, evalStruct); if (Tools.notEmpty(vError)){ serviceResult.error = vError; serviceResult.failureReason = " : VALIDATION ERROR; "; hasError = true; } if (hasError == false){ hasError = ! serviceResult.gotExpectedResult(); } boolean doingAuto = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.auto); String serviceResultRow = serviceResult.dump(dump.dumpServiceResult, hasError)+"; time:"+(System.currentTimeMillis()-startTime); String leader = (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) ? "XmlReplay:"+testIDLabel+": ": ""; report.addTestResult(serviceResult); if ( (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.detailed) || (dump.dumpServiceResult == ServiceResult.DUMP_OPTIONS.full) ){ System.out.println("\r\n#---------------------#"); }
8,757
0
// TODO(Post-P): Need a way to notify to a specific browser in framework.
@Override public void notifyChildrenChanged(final RemoteUserInfo remoteUserInfo, final String parentId, final Bundle options) { // TODO(Post-P): Need a way to notify to a specific browser in framework. notifyChildrenChangedForCompat(remoteUserInfo, parentId, options); }
DESIGN
true
public void notifyChildrenChanged(final RemoteUserInfo remoteUserInfo, final String parentId, final Bundle options) { // TODO(Post-P): Need a way to notify to a specific browser in framework. notifyChildrenChangedForCompat(remoteUserInfo, parentId, options); }
@Override public void notifyChildrenChanged(final RemoteUserInfo remoteUserInfo, final String parentId, final Bundle options) { // TODO(Post-P): Need a way to notify to a specific browser in framework. notifyChildrenChangedForCompat(remoteUserInfo, parentId, options); }
@Override public void notifyChildrenChanged(final RemoteUserInfo remoteUserInfo, final String parentId, final Bundle options) { // TODO(Post-P): Need a way to notify to a specific browser in framework. notifyChildrenChangedForCompat(remoteUserInfo, parentId, options); }
571
0
/** * Oracle11 does not have auto incremented values. This method uses a sequence and a trigger to create the same * behavior. * * @param connection The connection to the database that will be used to execute the queries * @param tableName The name of the table that contains the column that should be automatically incremented * @param columnName The name of the column that should be automatically incremented * @throws SQLException if the auto increment statement cannot be created or executed */
public static void simulateAutoIncrement(Connection connection, String tableName, String columnName) throws SQLException { String sequenceName = tableName + "_seq"; String triggerName = tableName + "_id"; connection.prepareStatement( "CREATE sequence " + sequenceName + " start with 1 increment by 1 nocycle" ).executeUpdate(); // The oracle driver is getting confused by this statement, claiming we have to declare some in out parameter, // when we execute this as a prepared statement. Might be a config issue on our side. connection .createStatement() .execute( "create or replace trigger " + triggerName + " before insert on " + tableName + " for each row " + " begin " + " :new." + columnName + " := " + sequenceName + ".nextval; " + " end;" ); }
NONSATD
true
public static void simulateAutoIncrement(Connection connection, String tableName, String columnName) throws SQLException { String sequenceName = tableName + "_seq"; String triggerName = tableName + "_id"; connection.prepareStatement( "CREATE sequence " + sequenceName + " start with 1 increment by 1 nocycle" ).executeUpdate(); // The oracle driver is getting confused by this statement, claiming we have to declare some in out parameter, // when we execute this as a prepared statement. Might be a config issue on our side. connection .createStatement() .execute( "create or replace trigger " + triggerName + " before insert on " + tableName + " for each row " + " begin " + " :new." + columnName + " := " + sequenceName + ".nextval; " + " end;" ); }
public static void simulateAutoIncrement(Connection connection, String tableName, String columnName) throws SQLException { String sequenceName = tableName + "_seq"; String triggerName = tableName + "_id"; connection.prepareStatement( "CREATE sequence " + sequenceName + " start with 1 increment by 1 nocycle" ).executeUpdate(); // The oracle driver is getting confused by this statement, claiming we have to declare some in out parameter, // when we execute this as a prepared statement. Might be a config issue on our side. connection .createStatement() .execute( "create or replace trigger " + triggerName + " before insert on " + tableName + " for each row " + " begin " + " :new." + columnName + " := " + sequenceName + ".nextval; " + " end;" ); }
public static void simulateAutoIncrement(Connection connection, String tableName, String columnName) throws SQLException { String sequenceName = tableName + "_seq"; String triggerName = tableName + "_id"; connection.prepareStatement( "CREATE sequence " + sequenceName + " start with 1 increment by 1 nocycle" ).executeUpdate(); // The oracle driver is getting confused by this statement, claiming we have to declare some in out parameter, // when we execute this as a prepared statement. Might be a config issue on our side. connection .createStatement() .execute( "create or replace trigger " + triggerName + " before insert on " + tableName + " for each row " + " begin " + " :new." + columnName + " := " + sequenceName + ".nextval; " + " end;" ); }
571
1
// The oracle driver is getting confused by this statement, claiming we have to declare some in out parameter, // when we execute this as a prepared statement. Might be a config issue on our side.
public static void simulateAutoIncrement(Connection connection, String tableName, String columnName) throws SQLException { String sequenceName = tableName + "_seq"; String triggerName = tableName + "_id"; connection.prepareStatement( "CREATE sequence " + sequenceName + " start with 1 increment by 1 nocycle" ).executeUpdate(); // The oracle driver is getting confused by this statement, claiming we have to declare some in out parameter, // when we execute this as a prepared statement. Might be a config issue on our side. connection .createStatement() .execute( "create or replace trigger " + triggerName + " before insert on " + tableName + " for each row " + " begin " + " :new." + columnName + " := " + sequenceName + ".nextval; " + " end;" ); }
DEFECT
true
"CREATE sequence " + sequenceName + " start with 1 increment by 1 nocycle" ).executeUpdate(); // The oracle driver is getting confused by this statement, claiming we have to declare some in out parameter, // when we execute this as a prepared statement. Might be a config issue on our side. connection .createStatement()
public static void simulateAutoIncrement(Connection connection, String tableName, String columnName) throws SQLException { String sequenceName = tableName + "_seq"; String triggerName = tableName + "_id"; connection.prepareStatement( "CREATE sequence " + sequenceName + " start with 1 increment by 1 nocycle" ).executeUpdate(); // The oracle driver is getting confused by this statement, claiming we have to declare some in out parameter, // when we execute this as a prepared statement. Might be a config issue on our side. connection .createStatement() .execute( "create or replace trigger " + triggerName + " before insert on " + tableName + " for each row " + " begin " + " :new." + columnName + " := " + sequenceName + ".nextval; " + " end;" );
public static void simulateAutoIncrement(Connection connection, String tableName, String columnName) throws SQLException { String sequenceName = tableName + "_seq"; String triggerName = tableName + "_id"; connection.prepareStatement( "CREATE sequence " + sequenceName + " start with 1 increment by 1 nocycle" ).executeUpdate(); // The oracle driver is getting confused by this statement, claiming we have to declare some in out parameter, // when we execute this as a prepared statement. Might be a config issue on our side. connection .createStatement() .execute( "create or replace trigger " + triggerName + " before insert on " + tableName + " for each row " + " begin " + " :new." + columnName + " := " + sequenceName + ".nextval; " + " end;" ); }
25,149
0
// maybe we could handle java.lang === java.lang.reflect as well ?
@Override @JRubyMethod(name = "===") public RubyBoolean op_eqq(ThreadContext context, IRubyObject obj) { // maybe we could handle java.lang === java.lang.reflect as well ? return context.runtime.newBoolean(obj == this || isInstance(obj)); }
DESIGN
true
@JRubyMethod(name = "===") public RubyBoolean op_eqq(ThreadContext context, IRubyObject obj) { // maybe we could handle java.lang === java.lang.reflect as well ? return context.runtime.newBoolean(obj == this || isInstance(obj)); }
@Override @JRubyMethod(name = "===") public RubyBoolean op_eqq(ThreadContext context, IRubyObject obj) { // maybe we could handle java.lang === java.lang.reflect as well ? return context.runtime.newBoolean(obj == this || isInstance(obj)); }
@Override @JRubyMethod(name = "===") public RubyBoolean op_eqq(ThreadContext context, IRubyObject obj) { // maybe we could handle java.lang === java.lang.reflect as well ? return context.runtime.newBoolean(obj == this || isInstance(obj)); }
574
0
// TODO: customize your mock logic for s3 client
@Before public void setUp() throws IOException { event = TestUtils.parse("/s3-event.put.json", S3Event.class); // TODO: customize your mock logic for s3 client ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentType(CONTENT_TYPE); when(s3Object.getObjectMetadata()).thenReturn(objectMetadata); when(s3Client.getObject(getObjectRequest.capture())).thenReturn(s3Object); }
DESIGN
true
public void setUp() throws IOException { event = TestUtils.parse("/s3-event.put.json", S3Event.class); // TODO: customize your mock logic for s3 client ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentType(CONTENT_TYPE);
@Before public void setUp() throws IOException { event = TestUtils.parse("/s3-event.put.json", S3Event.class); // TODO: customize your mock logic for s3 client ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentType(CONTENT_TYPE); when(s3Object.getObjectMetadata()).thenReturn(objectMetadata); when(s3Client.getObject(getObjectRequest.capture())).thenReturn(s3Object); }
@Before public void setUp() throws IOException { event = TestUtils.parse("/s3-event.put.json", S3Event.class); // TODO: customize your mock logic for s3 client ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentType(CONTENT_TYPE); when(s3Object.getObjectMetadata()).thenReturn(objectMetadata); when(s3Client.getObject(getObjectRequest.capture())).thenReturn(s3Object); }
16,966
0
// //perhaps, one day we should implement RemoteControlClient for better Bluetooth support...? //http://developer.android.com/reference/android/media/RemoteControlClient.html //https://android.googlesource.com/platform/packages/apps/Music/+/master/src/com/android/music/MediaPlaybackService.java // //http://stackoverflow.com/questions/15527614/send-track-informations-via-a2dp-avrcp //http://stackoverflow.com/questions/14536597/how-does-the-android-lockscreen-get-playing-song //http://stackoverflow.com/questions/10510292/how-to-get-current-music-track-info // //https://android.googlesource.com/platform/packages/apps/Bluetooth/+/android-4.3_r0.9.1/src/com/android/bluetooth/a2dp/Avrcp.java //
@SuppressWarnings("deprecation") private static void broadcastStateChange(String title, boolean preparing, boolean titleOrSongHaveChanged) { if (notificationBroadcastPending) { localHandler.removeMessages(MSG_BROADCAST_STATE_CHANGE); notificationBroadcastPending = false; } final long now = SystemClock.uptimeMillis(); final long delta = now - notificationLastUpdateTime; if (delta < 100 || notificationLastUpdateTime == 0) { notificationBroadcastPending = true; localHandler.sendMessageAtTime(Message.obtain(localHandler, MSG_BROADCAST_STATE_CHANGE, (preparing ? 0x01 : 0) | (titleOrSongHaveChanged ? 0x02 : 0), 0, title), (notificationLastUpdateTime == 0 ? ((notificationLastUpdateTime = now) + 2000) : (notificationLastUpdateTime + 110 - delta))); return; } notificationLastUpdateTime = now; refreshNotification(); WidgetMain.updateWidgets(); // //perhaps, one day we should implement RemoteControlClient for better Bluetooth support...? //http://developer.android.com/reference/android/media/RemoteControlClient.html //https://android.googlesource.com/platform/packages/apps/Music/+/master/src/com/android/music/MediaPlaybackService.java // //http://stackoverflow.com/questions/15527614/send-track-informations-via-a2dp-avrcp //http://stackoverflow.com/questions/14536597/how-does-the-android-lockscreen-get-playing-song //http://stackoverflow.com/questions/10510292/how-to-get-current-music-track-info // //https://android.googlesource.com/platform/packages/apps/Bluetooth/+/android-4.3_r0.9.1/src/com/android/bluetooth/a2dp/Avrcp.java // if (localSong == null) { stickyBroadcast.setAction("com.android.music.playbackcomplete"); stickyBroadcast.removeExtra("id"); stickyBroadcast.removeExtra("songid"); stickyBroadcast.removeExtra("track"); stickyBroadcast.removeExtra("artist"); stickyBroadcast.removeExtra("album"); stickyBroadcast.removeExtra("duration"); //stickyBroadcast.removeExtra("position"); stickyBroadcast.removeExtra("playing"); } else { //apparently, a few 4.3 devices have an issue with com.android.music.metachanged.... //stickyBroadcast.setAction(playbackHasChanged ? "com.android.music.playstatechanged" : "com.android.music.metachanged"); stickyBroadcast.setAction("com.android.music.playstatechanged"); stickyBroadcast.putExtra("id", localSong.id); stickyBroadcast.putExtra("songid", localSong.id); stickyBroadcast.putExtra("track", title); stickyBroadcast.putExtra("artist", localSong.artist); stickyBroadcast.putExtra("album", localSong.album); stickyBroadcast.putExtra("duration", (long)localSong.lengthMS); //stickyBroadcast.putExtra("position", (long)0); stickyBroadcast.putExtra("playing", localPlaying); } // maybe check if api >= 21, and if so, use sendBroadcast instead.....??? // https://developer.android.com/reference/android/content/Context#sendStickyBroadcast(android.content.Intent) try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) thePlayer.sendBroadcast(stickyBroadcast); else thePlayer.sendStickyBroadcast(stickyBroadcast); } catch (RuntimeException ex) { //just ignore because most apps actually use RemoteControlClient on newer Androids } if (remoteControlClient != null) broadcastStateChangeToRemoteControl(title, preparing, titleOrSongHaveChanged); if (mediaSession != null) broadcastStateChangeToMediaSession(title, preparing, titleOrSongHaveChanged); }
IMPLEMENTATION
true
refreshNotification(); WidgetMain.updateWidgets(); // //perhaps, one day we should implement RemoteControlClient for better Bluetooth support...? //http://developer.android.com/reference/android/media/RemoteControlClient.html //https://android.googlesource.com/platform/packages/apps/Music/+/master/src/com/android/music/MediaPlaybackService.java // //http://stackoverflow.com/questions/15527614/send-track-informations-via-a2dp-avrcp //http://stackoverflow.com/questions/14536597/how-does-the-android-lockscreen-get-playing-song //http://stackoverflow.com/questions/10510292/how-to-get-current-music-track-info // //https://android.googlesource.com/platform/packages/apps/Bluetooth/+/android-4.3_r0.9.1/src/com/android/bluetooth/a2dp/Avrcp.java // if (localSong == null) { stickyBroadcast.setAction("com.android.music.playbackcomplete");
final long now = SystemClock.uptimeMillis(); final long delta = now - notificationLastUpdateTime; if (delta < 100 || notificationLastUpdateTime == 0) { notificationBroadcastPending = true; localHandler.sendMessageAtTime(Message.obtain(localHandler, MSG_BROADCAST_STATE_CHANGE, (preparing ? 0x01 : 0) | (titleOrSongHaveChanged ? 0x02 : 0), 0, title), (notificationLastUpdateTime == 0 ? ((notificationLastUpdateTime = now) + 2000) : (notificationLastUpdateTime + 110 - delta))); return; } notificationLastUpdateTime = now; refreshNotification(); WidgetMain.updateWidgets(); // //perhaps, one day we should implement RemoteControlClient for better Bluetooth support...? //http://developer.android.com/reference/android/media/RemoteControlClient.html //https://android.googlesource.com/platform/packages/apps/Music/+/master/src/com/android/music/MediaPlaybackService.java // //http://stackoverflow.com/questions/15527614/send-track-informations-via-a2dp-avrcp //http://stackoverflow.com/questions/14536597/how-does-the-android-lockscreen-get-playing-song //http://stackoverflow.com/questions/10510292/how-to-get-current-music-track-info // //https://android.googlesource.com/platform/packages/apps/Bluetooth/+/android-4.3_r0.9.1/src/com/android/bluetooth/a2dp/Avrcp.java // if (localSong == null) { stickyBroadcast.setAction("com.android.music.playbackcomplete"); stickyBroadcast.removeExtra("id"); stickyBroadcast.removeExtra("songid"); stickyBroadcast.removeExtra("track"); stickyBroadcast.removeExtra("artist"); stickyBroadcast.removeExtra("album"); stickyBroadcast.removeExtra("duration"); //stickyBroadcast.removeExtra("position"); stickyBroadcast.removeExtra("playing");
@SuppressWarnings("deprecation") private static void broadcastStateChange(String title, boolean preparing, boolean titleOrSongHaveChanged) { if (notificationBroadcastPending) { localHandler.removeMessages(MSG_BROADCAST_STATE_CHANGE); notificationBroadcastPending = false; } final long now = SystemClock.uptimeMillis(); final long delta = now - notificationLastUpdateTime; if (delta < 100 || notificationLastUpdateTime == 0) { notificationBroadcastPending = true; localHandler.sendMessageAtTime(Message.obtain(localHandler, MSG_BROADCAST_STATE_CHANGE, (preparing ? 0x01 : 0) | (titleOrSongHaveChanged ? 0x02 : 0), 0, title), (notificationLastUpdateTime == 0 ? ((notificationLastUpdateTime = now) + 2000) : (notificationLastUpdateTime + 110 - delta))); return; } notificationLastUpdateTime = now; refreshNotification(); WidgetMain.updateWidgets(); // //perhaps, one day we should implement RemoteControlClient for better Bluetooth support...? //http://developer.android.com/reference/android/media/RemoteControlClient.html //https://android.googlesource.com/platform/packages/apps/Music/+/master/src/com/android/music/MediaPlaybackService.java // //http://stackoverflow.com/questions/15527614/send-track-informations-via-a2dp-avrcp //http://stackoverflow.com/questions/14536597/how-does-the-android-lockscreen-get-playing-song //http://stackoverflow.com/questions/10510292/how-to-get-current-music-track-info // //https://android.googlesource.com/platform/packages/apps/Bluetooth/+/android-4.3_r0.9.1/src/com/android/bluetooth/a2dp/Avrcp.java // if (localSong == null) { stickyBroadcast.setAction("com.android.music.playbackcomplete"); stickyBroadcast.removeExtra("id"); stickyBroadcast.removeExtra("songid"); stickyBroadcast.removeExtra("track"); stickyBroadcast.removeExtra("artist"); stickyBroadcast.removeExtra("album"); stickyBroadcast.removeExtra("duration"); //stickyBroadcast.removeExtra("position"); stickyBroadcast.removeExtra("playing"); } else { //apparently, a few 4.3 devices have an issue with com.android.music.metachanged.... //stickyBroadcast.setAction(playbackHasChanged ? "com.android.music.playstatechanged" : "com.android.music.metachanged"); stickyBroadcast.setAction("com.android.music.playstatechanged"); stickyBroadcast.putExtra("id", localSong.id); stickyBroadcast.putExtra("songid", localSong.id); stickyBroadcast.putExtra("track", title); stickyBroadcast.putExtra("artist", localSong.artist); stickyBroadcast.putExtra("album", localSong.album); stickyBroadcast.putExtra("duration", (long)localSong.lengthMS);
16,966
1
//stickyBroadcast.removeExtra("position");
@SuppressWarnings("deprecation") private static void broadcastStateChange(String title, boolean preparing, boolean titleOrSongHaveChanged) { if (notificationBroadcastPending) { localHandler.removeMessages(MSG_BROADCAST_STATE_CHANGE); notificationBroadcastPending = false; } final long now = SystemClock.uptimeMillis(); final long delta = now - notificationLastUpdateTime; if (delta < 100 || notificationLastUpdateTime == 0) { notificationBroadcastPending = true; localHandler.sendMessageAtTime(Message.obtain(localHandler, MSG_BROADCAST_STATE_CHANGE, (preparing ? 0x01 : 0) | (titleOrSongHaveChanged ? 0x02 : 0), 0, title), (notificationLastUpdateTime == 0 ? ((notificationLastUpdateTime = now) + 2000) : (notificationLastUpdateTime + 110 - delta))); return; } notificationLastUpdateTime = now; refreshNotification(); WidgetMain.updateWidgets(); // //perhaps, one day we should implement RemoteControlClient for better Bluetooth support...? //http://developer.android.com/reference/android/media/RemoteControlClient.html //https://android.googlesource.com/platform/packages/apps/Music/+/master/src/com/android/music/MediaPlaybackService.java // //http://stackoverflow.com/questions/15527614/send-track-informations-via-a2dp-avrcp //http://stackoverflow.com/questions/14536597/how-does-the-android-lockscreen-get-playing-song //http://stackoverflow.com/questions/10510292/how-to-get-current-music-track-info // //https://android.googlesource.com/platform/packages/apps/Bluetooth/+/android-4.3_r0.9.1/src/com/android/bluetooth/a2dp/Avrcp.java // if (localSong == null) { stickyBroadcast.setAction("com.android.music.playbackcomplete"); stickyBroadcast.removeExtra("id"); stickyBroadcast.removeExtra("songid"); stickyBroadcast.removeExtra("track"); stickyBroadcast.removeExtra("artist"); stickyBroadcast.removeExtra("album"); stickyBroadcast.removeExtra("duration"); //stickyBroadcast.removeExtra("position"); stickyBroadcast.removeExtra("playing"); } else { //apparently, a few 4.3 devices have an issue with com.android.music.metachanged.... //stickyBroadcast.setAction(playbackHasChanged ? "com.android.music.playstatechanged" : "com.android.music.metachanged"); stickyBroadcast.setAction("com.android.music.playstatechanged"); stickyBroadcast.putExtra("id", localSong.id); stickyBroadcast.putExtra("songid", localSong.id); stickyBroadcast.putExtra("track", title); stickyBroadcast.putExtra("artist", localSong.artist); stickyBroadcast.putExtra("album", localSong.album); stickyBroadcast.putExtra("duration", (long)localSong.lengthMS); //stickyBroadcast.putExtra("position", (long)0); stickyBroadcast.putExtra("playing", localPlaying); } // maybe check if api >= 21, and if so, use sendBroadcast instead.....??? // https://developer.android.com/reference/android/content/Context#sendStickyBroadcast(android.content.Intent) try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) thePlayer.sendBroadcast(stickyBroadcast); else thePlayer.sendStickyBroadcast(stickyBroadcast); } catch (RuntimeException ex) { //just ignore because most apps actually use RemoteControlClient on newer Androids } if (remoteControlClient != null) broadcastStateChangeToRemoteControl(title, preparing, titleOrSongHaveChanged); if (mediaSession != null) broadcastStateChangeToMediaSession(title, preparing, titleOrSongHaveChanged); }
NONSATD
true
stickyBroadcast.removeExtra("album"); stickyBroadcast.removeExtra("duration"); //stickyBroadcast.removeExtra("position"); stickyBroadcast.removeExtra("playing"); } else {
//https://android.googlesource.com/platform/packages/apps/Bluetooth/+/android-4.3_r0.9.1/src/com/android/bluetooth/a2dp/Avrcp.java // if (localSong == null) { stickyBroadcast.setAction("com.android.music.playbackcomplete"); stickyBroadcast.removeExtra("id"); stickyBroadcast.removeExtra("songid"); stickyBroadcast.removeExtra("track"); stickyBroadcast.removeExtra("artist"); stickyBroadcast.removeExtra("album"); stickyBroadcast.removeExtra("duration"); //stickyBroadcast.removeExtra("position"); stickyBroadcast.removeExtra("playing"); } else { //apparently, a few 4.3 devices have an issue with com.android.music.metachanged.... //stickyBroadcast.setAction(playbackHasChanged ? "com.android.music.playstatechanged" : "com.android.music.metachanged"); stickyBroadcast.setAction("com.android.music.playstatechanged"); stickyBroadcast.putExtra("id", localSong.id); stickyBroadcast.putExtra("songid", localSong.id); stickyBroadcast.putExtra("track", title); stickyBroadcast.putExtra("artist", localSong.artist); stickyBroadcast.putExtra("album", localSong.album);
WidgetMain.updateWidgets(); // //perhaps, one day we should implement RemoteControlClient for better Bluetooth support...? //http://developer.android.com/reference/android/media/RemoteControlClient.html //https://android.googlesource.com/platform/packages/apps/Music/+/master/src/com/android/music/MediaPlaybackService.java // //http://stackoverflow.com/questions/15527614/send-track-informations-via-a2dp-avrcp //http://stackoverflow.com/questions/14536597/how-does-the-android-lockscreen-get-playing-song //http://stackoverflow.com/questions/10510292/how-to-get-current-music-track-info // //https://android.googlesource.com/platform/packages/apps/Bluetooth/+/android-4.3_r0.9.1/src/com/android/bluetooth/a2dp/Avrcp.java // if (localSong == null) { stickyBroadcast.setAction("com.android.music.playbackcomplete"); stickyBroadcast.removeExtra("id"); stickyBroadcast.removeExtra("songid"); stickyBroadcast.removeExtra("track"); stickyBroadcast.removeExtra("artist"); stickyBroadcast.removeExtra("album"); stickyBroadcast.removeExtra("duration"); //stickyBroadcast.removeExtra("position"); stickyBroadcast.removeExtra("playing"); } else { //apparently, a few 4.3 devices have an issue with com.android.music.metachanged.... //stickyBroadcast.setAction(playbackHasChanged ? "com.android.music.playstatechanged" : "com.android.music.metachanged"); stickyBroadcast.setAction("com.android.music.playstatechanged"); stickyBroadcast.putExtra("id", localSong.id); stickyBroadcast.putExtra("songid", localSong.id); stickyBroadcast.putExtra("track", title); stickyBroadcast.putExtra("artist", localSong.artist); stickyBroadcast.putExtra("album", localSong.album); stickyBroadcast.putExtra("duration", (long)localSong.lengthMS); //stickyBroadcast.putExtra("position", (long)0); stickyBroadcast.putExtra("playing", localPlaying); } // maybe check if api >= 21, and if so, use sendBroadcast instead.....??? // https://developer.android.com/reference/android/content/Context#sendStickyBroadcast(android.content.Intent) try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) thePlayer.sendBroadcast(stickyBroadcast); else
16,966
2
//apparently, a few 4.3 devices have an issue with com.android.music.metachanged.... //stickyBroadcast.setAction(playbackHasChanged ? "com.android.music.playstatechanged" : "com.android.music.metachanged");
@SuppressWarnings("deprecation") private static void broadcastStateChange(String title, boolean preparing, boolean titleOrSongHaveChanged) { if (notificationBroadcastPending) { localHandler.removeMessages(MSG_BROADCAST_STATE_CHANGE); notificationBroadcastPending = false; } final long now = SystemClock.uptimeMillis(); final long delta = now - notificationLastUpdateTime; if (delta < 100 || notificationLastUpdateTime == 0) { notificationBroadcastPending = true; localHandler.sendMessageAtTime(Message.obtain(localHandler, MSG_BROADCAST_STATE_CHANGE, (preparing ? 0x01 : 0) | (titleOrSongHaveChanged ? 0x02 : 0), 0, title), (notificationLastUpdateTime == 0 ? ((notificationLastUpdateTime = now) + 2000) : (notificationLastUpdateTime + 110 - delta))); return; } notificationLastUpdateTime = now; refreshNotification(); WidgetMain.updateWidgets(); // //perhaps, one day we should implement RemoteControlClient for better Bluetooth support...? //http://developer.android.com/reference/android/media/RemoteControlClient.html //https://android.googlesource.com/platform/packages/apps/Music/+/master/src/com/android/music/MediaPlaybackService.java // //http://stackoverflow.com/questions/15527614/send-track-informations-via-a2dp-avrcp //http://stackoverflow.com/questions/14536597/how-does-the-android-lockscreen-get-playing-song //http://stackoverflow.com/questions/10510292/how-to-get-current-music-track-info // //https://android.googlesource.com/platform/packages/apps/Bluetooth/+/android-4.3_r0.9.1/src/com/android/bluetooth/a2dp/Avrcp.java // if (localSong == null) { stickyBroadcast.setAction("com.android.music.playbackcomplete"); stickyBroadcast.removeExtra("id"); stickyBroadcast.removeExtra("songid"); stickyBroadcast.removeExtra("track"); stickyBroadcast.removeExtra("artist"); stickyBroadcast.removeExtra("album"); stickyBroadcast.removeExtra("duration"); //stickyBroadcast.removeExtra("position"); stickyBroadcast.removeExtra("playing"); } else { //apparently, a few 4.3 devices have an issue with com.android.music.metachanged.... //stickyBroadcast.setAction(playbackHasChanged ? "com.android.music.playstatechanged" : "com.android.music.metachanged"); stickyBroadcast.setAction("com.android.music.playstatechanged"); stickyBroadcast.putExtra("id", localSong.id); stickyBroadcast.putExtra("songid", localSong.id); stickyBroadcast.putExtra("track", title); stickyBroadcast.putExtra("artist", localSong.artist); stickyBroadcast.putExtra("album", localSong.album); stickyBroadcast.putExtra("duration", (long)localSong.lengthMS); //stickyBroadcast.putExtra("position", (long)0); stickyBroadcast.putExtra("playing", localPlaying); } // maybe check if api >= 21, and if so, use sendBroadcast instead.....??? // https://developer.android.com/reference/android/content/Context#sendStickyBroadcast(android.content.Intent) try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) thePlayer.sendBroadcast(stickyBroadcast); else thePlayer.sendStickyBroadcast(stickyBroadcast); } catch (RuntimeException ex) { //just ignore because most apps actually use RemoteControlClient on newer Androids } if (remoteControlClient != null) broadcastStateChangeToRemoteControl(title, preparing, titleOrSongHaveChanged); if (mediaSession != null) broadcastStateChangeToMediaSession(title, preparing, titleOrSongHaveChanged); }
DEFECT
true
stickyBroadcast.removeExtra("playing"); } else { //apparently, a few 4.3 devices have an issue with com.android.music.metachanged.... //stickyBroadcast.setAction(playbackHasChanged ? "com.android.music.playstatechanged" : "com.android.music.metachanged"); stickyBroadcast.setAction("com.android.music.playstatechanged"); stickyBroadcast.putExtra("id", localSong.id);
stickyBroadcast.setAction("com.android.music.playbackcomplete"); stickyBroadcast.removeExtra("id"); stickyBroadcast.removeExtra("songid"); stickyBroadcast.removeExtra("track"); stickyBroadcast.removeExtra("artist"); stickyBroadcast.removeExtra("album"); stickyBroadcast.removeExtra("duration"); //stickyBroadcast.removeExtra("position"); stickyBroadcast.removeExtra("playing"); } else { //apparently, a few 4.3 devices have an issue with com.android.music.metachanged.... //stickyBroadcast.setAction(playbackHasChanged ? "com.android.music.playstatechanged" : "com.android.music.metachanged"); stickyBroadcast.setAction("com.android.music.playstatechanged"); stickyBroadcast.putExtra("id", localSong.id); stickyBroadcast.putExtra("songid", localSong.id); stickyBroadcast.putExtra("track", title); stickyBroadcast.putExtra("artist", localSong.artist); stickyBroadcast.putExtra("album", localSong.album); stickyBroadcast.putExtra("duration", (long)localSong.lengthMS); //stickyBroadcast.putExtra("position", (long)0); stickyBroadcast.putExtra("playing", localPlaying); }
//http://developer.android.com/reference/android/media/RemoteControlClient.html //https://android.googlesource.com/platform/packages/apps/Music/+/master/src/com/android/music/MediaPlaybackService.java // //http://stackoverflow.com/questions/15527614/send-track-informations-via-a2dp-avrcp //http://stackoverflow.com/questions/14536597/how-does-the-android-lockscreen-get-playing-song //http://stackoverflow.com/questions/10510292/how-to-get-current-music-track-info // //https://android.googlesource.com/platform/packages/apps/Bluetooth/+/android-4.3_r0.9.1/src/com/android/bluetooth/a2dp/Avrcp.java // if (localSong == null) { stickyBroadcast.setAction("com.android.music.playbackcomplete"); stickyBroadcast.removeExtra("id"); stickyBroadcast.removeExtra("songid"); stickyBroadcast.removeExtra("track"); stickyBroadcast.removeExtra("artist"); stickyBroadcast.removeExtra("album"); stickyBroadcast.removeExtra("duration"); //stickyBroadcast.removeExtra("position"); stickyBroadcast.removeExtra("playing"); } else { //apparently, a few 4.3 devices have an issue with com.android.music.metachanged.... //stickyBroadcast.setAction(playbackHasChanged ? "com.android.music.playstatechanged" : "com.android.music.metachanged"); stickyBroadcast.setAction("com.android.music.playstatechanged"); stickyBroadcast.putExtra("id", localSong.id); stickyBroadcast.putExtra("songid", localSong.id); stickyBroadcast.putExtra("track", title); stickyBroadcast.putExtra("artist", localSong.artist); stickyBroadcast.putExtra("album", localSong.album); stickyBroadcast.putExtra("duration", (long)localSong.lengthMS); //stickyBroadcast.putExtra("position", (long)0); stickyBroadcast.putExtra("playing", localPlaying); } // maybe check if api >= 21, and if so, use sendBroadcast instead.....??? // https://developer.android.com/reference/android/content/Context#sendStickyBroadcast(android.content.Intent) try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) thePlayer.sendBroadcast(stickyBroadcast); else thePlayer.sendStickyBroadcast(stickyBroadcast); } catch (RuntimeException ex) { //just ignore because most apps actually use RemoteControlClient on newer Androids }
16,966
3
//stickyBroadcast.putExtra("position", (long)0);
@SuppressWarnings("deprecation") private static void broadcastStateChange(String title, boolean preparing, boolean titleOrSongHaveChanged) { if (notificationBroadcastPending) { localHandler.removeMessages(MSG_BROADCAST_STATE_CHANGE); notificationBroadcastPending = false; } final long now = SystemClock.uptimeMillis(); final long delta = now - notificationLastUpdateTime; if (delta < 100 || notificationLastUpdateTime == 0) { notificationBroadcastPending = true; localHandler.sendMessageAtTime(Message.obtain(localHandler, MSG_BROADCAST_STATE_CHANGE, (preparing ? 0x01 : 0) | (titleOrSongHaveChanged ? 0x02 : 0), 0, title), (notificationLastUpdateTime == 0 ? ((notificationLastUpdateTime = now) + 2000) : (notificationLastUpdateTime + 110 - delta))); return; } notificationLastUpdateTime = now; refreshNotification(); WidgetMain.updateWidgets(); // //perhaps, one day we should implement RemoteControlClient for better Bluetooth support...? //http://developer.android.com/reference/android/media/RemoteControlClient.html //https://android.googlesource.com/platform/packages/apps/Music/+/master/src/com/android/music/MediaPlaybackService.java // //http://stackoverflow.com/questions/15527614/send-track-informations-via-a2dp-avrcp //http://stackoverflow.com/questions/14536597/how-does-the-android-lockscreen-get-playing-song //http://stackoverflow.com/questions/10510292/how-to-get-current-music-track-info // //https://android.googlesource.com/platform/packages/apps/Bluetooth/+/android-4.3_r0.9.1/src/com/android/bluetooth/a2dp/Avrcp.java // if (localSong == null) { stickyBroadcast.setAction("com.android.music.playbackcomplete"); stickyBroadcast.removeExtra("id"); stickyBroadcast.removeExtra("songid"); stickyBroadcast.removeExtra("track"); stickyBroadcast.removeExtra("artist"); stickyBroadcast.removeExtra("album"); stickyBroadcast.removeExtra("duration"); //stickyBroadcast.removeExtra("position"); stickyBroadcast.removeExtra("playing"); } else { //apparently, a few 4.3 devices have an issue with com.android.music.metachanged.... //stickyBroadcast.setAction(playbackHasChanged ? "com.android.music.playstatechanged" : "com.android.music.metachanged"); stickyBroadcast.setAction("com.android.music.playstatechanged"); stickyBroadcast.putExtra("id", localSong.id); stickyBroadcast.putExtra("songid", localSong.id); stickyBroadcast.putExtra("track", title); stickyBroadcast.putExtra("artist", localSong.artist); stickyBroadcast.putExtra("album", localSong.album); stickyBroadcast.putExtra("duration", (long)localSong.lengthMS); //stickyBroadcast.putExtra("position", (long)0); stickyBroadcast.putExtra("playing", localPlaying); } // maybe check if api >= 21, and if so, use sendBroadcast instead.....??? // https://developer.android.com/reference/android/content/Context#sendStickyBroadcast(android.content.Intent) try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) thePlayer.sendBroadcast(stickyBroadcast); else thePlayer.sendStickyBroadcast(stickyBroadcast); } catch (RuntimeException ex) { //just ignore because most apps actually use RemoteControlClient on newer Androids } if (remoteControlClient != null) broadcastStateChangeToRemoteControl(title, preparing, titleOrSongHaveChanged); if (mediaSession != null) broadcastStateChangeToMediaSession(title, preparing, titleOrSongHaveChanged); }
NONSATD
true
stickyBroadcast.putExtra("album", localSong.album); stickyBroadcast.putExtra("duration", (long)localSong.lengthMS); //stickyBroadcast.putExtra("position", (long)0); stickyBroadcast.putExtra("playing", localPlaying); }
} else { //apparently, a few 4.3 devices have an issue with com.android.music.metachanged.... //stickyBroadcast.setAction(playbackHasChanged ? "com.android.music.playstatechanged" : "com.android.music.metachanged"); stickyBroadcast.setAction("com.android.music.playstatechanged"); stickyBroadcast.putExtra("id", localSong.id); stickyBroadcast.putExtra("songid", localSong.id); stickyBroadcast.putExtra("track", title); stickyBroadcast.putExtra("artist", localSong.artist); stickyBroadcast.putExtra("album", localSong.album); stickyBroadcast.putExtra("duration", (long)localSong.lengthMS); //stickyBroadcast.putExtra("position", (long)0); stickyBroadcast.putExtra("playing", localPlaying); } // maybe check if api >= 21, and if so, use sendBroadcast instead.....??? // https://developer.android.com/reference/android/content/Context#sendStickyBroadcast(android.content.Intent) try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) thePlayer.sendBroadcast(stickyBroadcast); else thePlayer.sendStickyBroadcast(stickyBroadcast); } catch (RuntimeException ex) {
if (localSong == null) { stickyBroadcast.setAction("com.android.music.playbackcomplete"); stickyBroadcast.removeExtra("id"); stickyBroadcast.removeExtra("songid"); stickyBroadcast.removeExtra("track"); stickyBroadcast.removeExtra("artist"); stickyBroadcast.removeExtra("album"); stickyBroadcast.removeExtra("duration"); //stickyBroadcast.removeExtra("position"); stickyBroadcast.removeExtra("playing"); } else { //apparently, a few 4.3 devices have an issue with com.android.music.metachanged.... //stickyBroadcast.setAction(playbackHasChanged ? "com.android.music.playstatechanged" : "com.android.music.metachanged"); stickyBroadcast.setAction("com.android.music.playstatechanged"); stickyBroadcast.putExtra("id", localSong.id); stickyBroadcast.putExtra("songid", localSong.id); stickyBroadcast.putExtra("track", title); stickyBroadcast.putExtra("artist", localSong.artist); stickyBroadcast.putExtra("album", localSong.album); stickyBroadcast.putExtra("duration", (long)localSong.lengthMS); //stickyBroadcast.putExtra("position", (long)0); stickyBroadcast.putExtra("playing", localPlaying); } // maybe check if api >= 21, and if so, use sendBroadcast instead.....??? // https://developer.android.com/reference/android/content/Context#sendStickyBroadcast(android.content.Intent) try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) thePlayer.sendBroadcast(stickyBroadcast); else thePlayer.sendStickyBroadcast(stickyBroadcast); } catch (RuntimeException ex) { //just ignore because most apps actually use RemoteControlClient on newer Androids } if (remoteControlClient != null) broadcastStateChangeToRemoteControl(title, preparing, titleOrSongHaveChanged); if (mediaSession != null) broadcastStateChangeToMediaSession(title, preparing, titleOrSongHaveChanged); }
16,966
4
// maybe check if api >= 21, and if so, use sendBroadcast instead.....??? // https://developer.android.com/reference/android/content/Context#sendStickyBroadcast(android.content.Intent)
@SuppressWarnings("deprecation") private static void broadcastStateChange(String title, boolean preparing, boolean titleOrSongHaveChanged) { if (notificationBroadcastPending) { localHandler.removeMessages(MSG_BROADCAST_STATE_CHANGE); notificationBroadcastPending = false; } final long now = SystemClock.uptimeMillis(); final long delta = now - notificationLastUpdateTime; if (delta < 100 || notificationLastUpdateTime == 0) { notificationBroadcastPending = true; localHandler.sendMessageAtTime(Message.obtain(localHandler, MSG_BROADCAST_STATE_CHANGE, (preparing ? 0x01 : 0) | (titleOrSongHaveChanged ? 0x02 : 0), 0, title), (notificationLastUpdateTime == 0 ? ((notificationLastUpdateTime = now) + 2000) : (notificationLastUpdateTime + 110 - delta))); return; } notificationLastUpdateTime = now; refreshNotification(); WidgetMain.updateWidgets(); // //perhaps, one day we should implement RemoteControlClient for better Bluetooth support...? //http://developer.android.com/reference/android/media/RemoteControlClient.html //https://android.googlesource.com/platform/packages/apps/Music/+/master/src/com/android/music/MediaPlaybackService.java // //http://stackoverflow.com/questions/15527614/send-track-informations-via-a2dp-avrcp //http://stackoverflow.com/questions/14536597/how-does-the-android-lockscreen-get-playing-song //http://stackoverflow.com/questions/10510292/how-to-get-current-music-track-info // //https://android.googlesource.com/platform/packages/apps/Bluetooth/+/android-4.3_r0.9.1/src/com/android/bluetooth/a2dp/Avrcp.java // if (localSong == null) { stickyBroadcast.setAction("com.android.music.playbackcomplete"); stickyBroadcast.removeExtra("id"); stickyBroadcast.removeExtra("songid"); stickyBroadcast.removeExtra("track"); stickyBroadcast.removeExtra("artist"); stickyBroadcast.removeExtra("album"); stickyBroadcast.removeExtra("duration"); //stickyBroadcast.removeExtra("position"); stickyBroadcast.removeExtra("playing"); } else { //apparently, a few 4.3 devices have an issue with com.android.music.metachanged.... //stickyBroadcast.setAction(playbackHasChanged ? "com.android.music.playstatechanged" : "com.android.music.metachanged"); stickyBroadcast.setAction("com.android.music.playstatechanged"); stickyBroadcast.putExtra("id", localSong.id); stickyBroadcast.putExtra("songid", localSong.id); stickyBroadcast.putExtra("track", title); stickyBroadcast.putExtra("artist", localSong.artist); stickyBroadcast.putExtra("album", localSong.album); stickyBroadcast.putExtra("duration", (long)localSong.lengthMS); //stickyBroadcast.putExtra("position", (long)0); stickyBroadcast.putExtra("playing", localPlaying); } // maybe check if api >= 21, and if so, use sendBroadcast instead.....??? // https://developer.android.com/reference/android/content/Context#sendStickyBroadcast(android.content.Intent) try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) thePlayer.sendBroadcast(stickyBroadcast); else thePlayer.sendStickyBroadcast(stickyBroadcast); } catch (RuntimeException ex) { //just ignore because most apps actually use RemoteControlClient on newer Androids } if (remoteControlClient != null) broadcastStateChangeToRemoteControl(title, preparing, titleOrSongHaveChanged); if (mediaSession != null) broadcastStateChangeToMediaSession(title, preparing, titleOrSongHaveChanged); }
IMPLEMENTATION
true
stickyBroadcast.putExtra("playing", localPlaying); } // maybe check if api >= 21, and if so, use sendBroadcast instead.....??? // https://developer.android.com/reference/android/content/Context#sendStickyBroadcast(android.content.Intent) try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
stickyBroadcast.setAction("com.android.music.playstatechanged"); stickyBroadcast.putExtra("id", localSong.id); stickyBroadcast.putExtra("songid", localSong.id); stickyBroadcast.putExtra("track", title); stickyBroadcast.putExtra("artist", localSong.artist); stickyBroadcast.putExtra("album", localSong.album); stickyBroadcast.putExtra("duration", (long)localSong.lengthMS); //stickyBroadcast.putExtra("position", (long)0); stickyBroadcast.putExtra("playing", localPlaying); } // maybe check if api >= 21, and if so, use sendBroadcast instead.....??? // https://developer.android.com/reference/android/content/Context#sendStickyBroadcast(android.content.Intent) try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) thePlayer.sendBroadcast(stickyBroadcast); else thePlayer.sendStickyBroadcast(stickyBroadcast); } catch (RuntimeException ex) { //just ignore because most apps actually use RemoteControlClient on newer Androids } if (remoteControlClient != null) broadcastStateChangeToRemoteControl(title, preparing, titleOrSongHaveChanged);
stickyBroadcast.removeExtra("songid"); stickyBroadcast.removeExtra("track"); stickyBroadcast.removeExtra("artist"); stickyBroadcast.removeExtra("album"); stickyBroadcast.removeExtra("duration"); //stickyBroadcast.removeExtra("position"); stickyBroadcast.removeExtra("playing"); } else { //apparently, a few 4.3 devices have an issue with com.android.music.metachanged.... //stickyBroadcast.setAction(playbackHasChanged ? "com.android.music.playstatechanged" : "com.android.music.metachanged"); stickyBroadcast.setAction("com.android.music.playstatechanged"); stickyBroadcast.putExtra("id", localSong.id); stickyBroadcast.putExtra("songid", localSong.id); stickyBroadcast.putExtra("track", title); stickyBroadcast.putExtra("artist", localSong.artist); stickyBroadcast.putExtra("album", localSong.album); stickyBroadcast.putExtra("duration", (long)localSong.lengthMS); //stickyBroadcast.putExtra("position", (long)0); stickyBroadcast.putExtra("playing", localPlaying); } // maybe check if api >= 21, and if so, use sendBroadcast instead.....??? // https://developer.android.com/reference/android/content/Context#sendStickyBroadcast(android.content.Intent) try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) thePlayer.sendBroadcast(stickyBroadcast); else thePlayer.sendStickyBroadcast(stickyBroadcast); } catch (RuntimeException ex) { //just ignore because most apps actually use RemoteControlClient on newer Androids } if (remoteControlClient != null) broadcastStateChangeToRemoteControl(title, preparing, titleOrSongHaveChanged); if (mediaSession != null) broadcastStateChangeToMediaSession(title, preparing, titleOrSongHaveChanged); }
16,966
5
//just ignore because most apps actually use RemoteControlClient on newer Androids
@SuppressWarnings("deprecation") private static void broadcastStateChange(String title, boolean preparing, boolean titleOrSongHaveChanged) { if (notificationBroadcastPending) { localHandler.removeMessages(MSG_BROADCAST_STATE_CHANGE); notificationBroadcastPending = false; } final long now = SystemClock.uptimeMillis(); final long delta = now - notificationLastUpdateTime; if (delta < 100 || notificationLastUpdateTime == 0) { notificationBroadcastPending = true; localHandler.sendMessageAtTime(Message.obtain(localHandler, MSG_BROADCAST_STATE_CHANGE, (preparing ? 0x01 : 0) | (titleOrSongHaveChanged ? 0x02 : 0), 0, title), (notificationLastUpdateTime == 0 ? ((notificationLastUpdateTime = now) + 2000) : (notificationLastUpdateTime + 110 - delta))); return; } notificationLastUpdateTime = now; refreshNotification(); WidgetMain.updateWidgets(); // //perhaps, one day we should implement RemoteControlClient for better Bluetooth support...? //http://developer.android.com/reference/android/media/RemoteControlClient.html //https://android.googlesource.com/platform/packages/apps/Music/+/master/src/com/android/music/MediaPlaybackService.java // //http://stackoverflow.com/questions/15527614/send-track-informations-via-a2dp-avrcp //http://stackoverflow.com/questions/14536597/how-does-the-android-lockscreen-get-playing-song //http://stackoverflow.com/questions/10510292/how-to-get-current-music-track-info // //https://android.googlesource.com/platform/packages/apps/Bluetooth/+/android-4.3_r0.9.1/src/com/android/bluetooth/a2dp/Avrcp.java // if (localSong == null) { stickyBroadcast.setAction("com.android.music.playbackcomplete"); stickyBroadcast.removeExtra("id"); stickyBroadcast.removeExtra("songid"); stickyBroadcast.removeExtra("track"); stickyBroadcast.removeExtra("artist"); stickyBroadcast.removeExtra("album"); stickyBroadcast.removeExtra("duration"); //stickyBroadcast.removeExtra("position"); stickyBroadcast.removeExtra("playing"); } else { //apparently, a few 4.3 devices have an issue with com.android.music.metachanged.... //stickyBroadcast.setAction(playbackHasChanged ? "com.android.music.playstatechanged" : "com.android.music.metachanged"); stickyBroadcast.setAction("com.android.music.playstatechanged"); stickyBroadcast.putExtra("id", localSong.id); stickyBroadcast.putExtra("songid", localSong.id); stickyBroadcast.putExtra("track", title); stickyBroadcast.putExtra("artist", localSong.artist); stickyBroadcast.putExtra("album", localSong.album); stickyBroadcast.putExtra("duration", (long)localSong.lengthMS); //stickyBroadcast.putExtra("position", (long)0); stickyBroadcast.putExtra("playing", localPlaying); } // maybe check if api >= 21, and if so, use sendBroadcast instead.....??? // https://developer.android.com/reference/android/content/Context#sendStickyBroadcast(android.content.Intent) try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) thePlayer.sendBroadcast(stickyBroadcast); else thePlayer.sendStickyBroadcast(stickyBroadcast); } catch (RuntimeException ex) { //just ignore because most apps actually use RemoteControlClient on newer Androids } if (remoteControlClient != null) broadcastStateChangeToRemoteControl(title, preparing, titleOrSongHaveChanged); if (mediaSession != null) broadcastStateChangeToMediaSession(title, preparing, titleOrSongHaveChanged); }
NONSATD
true
thePlayer.sendStickyBroadcast(stickyBroadcast); } catch (RuntimeException ex) { //just ignore because most apps actually use RemoteControlClient on newer Androids } if (remoteControlClient != null)
stickyBroadcast.putExtra("playing", localPlaying); } // maybe check if api >= 21, and if so, use sendBroadcast instead.....??? // https://developer.android.com/reference/android/content/Context#sendStickyBroadcast(android.content.Intent) try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) thePlayer.sendBroadcast(stickyBroadcast); else thePlayer.sendStickyBroadcast(stickyBroadcast); } catch (RuntimeException ex) { //just ignore because most apps actually use RemoteControlClient on newer Androids } if (remoteControlClient != null) broadcastStateChangeToRemoteControl(title, preparing, titleOrSongHaveChanged); if (mediaSession != null) broadcastStateChangeToMediaSession(title, preparing, titleOrSongHaveChanged); }
//apparently, a few 4.3 devices have an issue with com.android.music.metachanged.... //stickyBroadcast.setAction(playbackHasChanged ? "com.android.music.playstatechanged" : "com.android.music.metachanged"); stickyBroadcast.setAction("com.android.music.playstatechanged"); stickyBroadcast.putExtra("id", localSong.id); stickyBroadcast.putExtra("songid", localSong.id); stickyBroadcast.putExtra("track", title); stickyBroadcast.putExtra("artist", localSong.artist); stickyBroadcast.putExtra("album", localSong.album); stickyBroadcast.putExtra("duration", (long)localSong.lengthMS); //stickyBroadcast.putExtra("position", (long)0); stickyBroadcast.putExtra("playing", localPlaying); } // maybe check if api >= 21, and if so, use sendBroadcast instead.....??? // https://developer.android.com/reference/android/content/Context#sendStickyBroadcast(android.content.Intent) try { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) thePlayer.sendBroadcast(stickyBroadcast); else thePlayer.sendStickyBroadcast(stickyBroadcast); } catch (RuntimeException ex) { //just ignore because most apps actually use RemoteControlClient on newer Androids } if (remoteControlClient != null) broadcastStateChangeToRemoteControl(title, preparing, titleOrSongHaveChanged); if (mediaSession != null) broadcastStateChangeToMediaSession(title, preparing, titleOrSongHaveChanged); }
25,166
0
// TODO why is this working with so few steps?
@Test public void testCEV() { int timeSteps = 200;// TODO why is this working with so few steps? int priceSteps = 100; double lowerMoneyness = 0.3; // Not working well for ITM calls double upperMoneyness = 3.0; double volTol = 5e-3; boolean print = false; // set to false before pushing TESTER.testCEV(SOLVER, timeSteps, priceSteps, lowerMoneyness, upperMoneyness, volTol, print); }
DESIGN
true
@Test public void testCEV() { int timeSteps = 200;// TODO why is this working with so few steps? int priceSteps = 100; double lowerMoneyness = 0.3; // Not working well for ITM calls
@Test public void testCEV() { int timeSteps = 200;// TODO why is this working with so few steps? int priceSteps = 100; double lowerMoneyness = 0.3; // Not working well for ITM calls double upperMoneyness = 3.0; double volTol = 5e-3; boolean print = false; // set to false before pushing TESTER.testCEV(SOLVER, timeSteps, priceSteps, lowerMoneyness, upperMoneyness, volTol, print); }
@Test public void testCEV() { int timeSteps = 200;// TODO why is this working with so few steps? int priceSteps = 100; double lowerMoneyness = 0.3; // Not working well for ITM calls double upperMoneyness = 3.0; double volTol = 5e-3; boolean print = false; // set to false before pushing TESTER.testCEV(SOLVER, timeSteps, priceSteps, lowerMoneyness, upperMoneyness, volTol, print); }
25,166
1
// Not working well for ITM calls
@Test public void testCEV() { int timeSteps = 200;// TODO why is this working with so few steps? int priceSteps = 100; double lowerMoneyness = 0.3; // Not working well for ITM calls double upperMoneyness = 3.0; double volTol = 5e-3; boolean print = false; // set to false before pushing TESTER.testCEV(SOLVER, timeSteps, priceSteps, lowerMoneyness, upperMoneyness, volTol, print); }
DEFECT
true
int timeSteps = 200;// TODO why is this working with so few steps? int priceSteps = 100; double lowerMoneyness = 0.3; // Not working well for ITM calls double upperMoneyness = 3.0; double volTol = 5e-3;
@Test public void testCEV() { int timeSteps = 200;// TODO why is this working with so few steps? int priceSteps = 100; double lowerMoneyness = 0.3; // Not working well for ITM calls double upperMoneyness = 3.0; double volTol = 5e-3; boolean print = false; // set to false before pushing TESTER.testCEV(SOLVER, timeSteps, priceSteps, lowerMoneyness, upperMoneyness, volTol, print); }
@Test public void testCEV() { int timeSteps = 200;// TODO why is this working with so few steps? int priceSteps = 100; double lowerMoneyness = 0.3; // Not working well for ITM calls double upperMoneyness = 3.0; double volTol = 5e-3; boolean print = false; // set to false before pushing TESTER.testCEV(SOLVER, timeSteps, priceSteps, lowerMoneyness, upperMoneyness, volTol, print); }
25,166
2
// set to false before pushing
@Test public void testCEV() { int timeSteps = 200;// TODO why is this working with so few steps? int priceSteps = 100; double lowerMoneyness = 0.3; // Not working well for ITM calls double upperMoneyness = 3.0; double volTol = 5e-3; boolean print = false; // set to false before pushing TESTER.testCEV(SOLVER, timeSteps, priceSteps, lowerMoneyness, upperMoneyness, volTol, print); }
NONSATD
true
double upperMoneyness = 3.0; double volTol = 5e-3; boolean print = false; // set to false before pushing TESTER.testCEV(SOLVER, timeSteps, priceSteps, lowerMoneyness, upperMoneyness, volTol, print); }
@Test public void testCEV() { int timeSteps = 200;// TODO why is this working with so few steps? int priceSteps = 100; double lowerMoneyness = 0.3; // Not working well for ITM calls double upperMoneyness = 3.0; double volTol = 5e-3; boolean print = false; // set to false before pushing TESTER.testCEV(SOLVER, timeSteps, priceSteps, lowerMoneyness, upperMoneyness, volTol, print); }
@Test public void testCEV() { int timeSteps = 200;// TODO why is this working with so few steps? int priceSteps = 100; double lowerMoneyness = 0.3; // Not working well for ITM calls double upperMoneyness = 3.0; double volTol = 5e-3; boolean print = false; // set to false before pushing TESTER.testCEV(SOLVER, timeSteps, priceSteps, lowerMoneyness, upperMoneyness, volTol, print); }
16,985
0
/** * Ensures that you can't publish an automatically added Quay/Github tool with an alternate structure unless you change the Dockerfile and Dockstore.cwl locations */
@Test public void testQuayGithubPublishAlternateStructure() { systemExit.expectSystemExitWithStatus(Client.API_ERROR); Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "publish", "--entry", "quay.io/dockstoretestuser/quayandgithubalternate", "--script" }); // TODO: change the tag tag locations of Dockerfile and Dockstore.cwl, now should be able to publish }
NONSATD
true
@Test public void testQuayGithubPublishAlternateStructure() { systemExit.expectSystemExitWithStatus(Client.API_ERROR); Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "publish", "--entry", "quay.io/dockstoretestuser/quayandgithubalternate", "--script" }); // TODO: change the tag tag locations of Dockerfile and Dockstore.cwl, now should be able to publish }
@Test public void testQuayGithubPublishAlternateStructure() { systemExit.expectSystemExitWithStatus(Client.API_ERROR); Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "publish", "--entry", "quay.io/dockstoretestuser/quayandgithubalternate", "--script" }); // TODO: change the tag tag locations of Dockerfile and Dockstore.cwl, now should be able to publish }
@Test public void testQuayGithubPublishAlternateStructure() { systemExit.expectSystemExitWithStatus(Client.API_ERROR); Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "publish", "--entry", "quay.io/dockstoretestuser/quayandgithubalternate", "--script" }); // TODO: change the tag tag locations of Dockerfile and Dockstore.cwl, now should be able to publish }
16,985
1
// TODO: change the tag tag locations of Dockerfile and Dockstore.cwl, now should be able to publish
@Test public void testQuayGithubPublishAlternateStructure() { systemExit.expectSystemExitWithStatus(Client.API_ERROR); Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "publish", "--entry", "quay.io/dockstoretestuser/quayandgithubalternate", "--script" }); // TODO: change the tag tag locations of Dockerfile and Dockstore.cwl, now should be able to publish }
IMPLEMENTATION
true
Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "publish", "--entry", "quay.io/dockstoretestuser/quayandgithubalternate", "--script" }); // TODO: change the tag tag locations of Dockerfile and Dockstore.cwl, now should be able to publish }
@Test public void testQuayGithubPublishAlternateStructure() { systemExit.expectSystemExitWithStatus(Client.API_ERROR); Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "publish", "--entry", "quay.io/dockstoretestuser/quayandgithubalternate", "--script" }); // TODO: change the tag tag locations of Dockerfile and Dockstore.cwl, now should be able to publish }
@Test public void testQuayGithubPublishAlternateStructure() { systemExit.expectSystemExitWithStatus(Client.API_ERROR); Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "publish", "--entry", "quay.io/dockstoretestuser/quayandgithubalternate", "--script" }); // TODO: change the tag tag locations of Dockerfile and Dockstore.cwl, now should be able to publish }
16,986
0
/** * Ensures that you can't publish an automatically added Quay/Bitbucket entry with an alternate structure unless you change the Dockerfile and Dockstore.cwl locations */
@Test public void testQuayBitbucketPublishAlternateStructure() { systemExit.expectSystemExitWithStatus(Client.API_ERROR); Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "publish", "--entry", "quay.io/dockstoretestuser/quayandbitbucketalternate", "--script" }); // TODO: change the tag tag locations of Dockerfile and Dockstore.cwl, now should be able to publish }
NONSATD
true
@Test public void testQuayBitbucketPublishAlternateStructure() { systemExit.expectSystemExitWithStatus(Client.API_ERROR); Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "publish", "--entry", "quay.io/dockstoretestuser/quayandbitbucketalternate", "--script" }); // TODO: change the tag tag locations of Dockerfile and Dockstore.cwl, now should be able to publish }
@Test public void testQuayBitbucketPublishAlternateStructure() { systemExit.expectSystemExitWithStatus(Client.API_ERROR); Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "publish", "--entry", "quay.io/dockstoretestuser/quayandbitbucketalternate", "--script" }); // TODO: change the tag tag locations of Dockerfile and Dockstore.cwl, now should be able to publish }
@Test public void testQuayBitbucketPublishAlternateStructure() { systemExit.expectSystemExitWithStatus(Client.API_ERROR); Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "publish", "--entry", "quay.io/dockstoretestuser/quayandbitbucketalternate", "--script" }); // TODO: change the tag tag locations of Dockerfile and Dockstore.cwl, now should be able to publish }
16,986
1
// TODO: change the tag tag locations of Dockerfile and Dockstore.cwl, now should be able to publish
@Test public void testQuayBitbucketPublishAlternateStructure() { systemExit.expectSystemExitWithStatus(Client.API_ERROR); Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "publish", "--entry", "quay.io/dockstoretestuser/quayandbitbucketalternate", "--script" }); // TODO: change the tag tag locations of Dockerfile and Dockstore.cwl, now should be able to publish }
IMPLEMENTATION
true
Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "publish", "--entry", "quay.io/dockstoretestuser/quayandbitbucketalternate", "--script" }); // TODO: change the tag tag locations of Dockerfile and Dockstore.cwl, now should be able to publish }
@Test public void testQuayBitbucketPublishAlternateStructure() { systemExit.expectSystemExitWithStatus(Client.API_ERROR); Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "publish", "--entry", "quay.io/dockstoretestuser/quayandbitbucketalternate", "--script" }); // TODO: change the tag tag locations of Dockerfile and Dockstore.cwl, now should be able to publish }
@Test public void testQuayBitbucketPublishAlternateStructure() { systemExit.expectSystemExitWithStatus(Client.API_ERROR); Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "publish", "--entry", "quay.io/dockstoretestuser/quayandbitbucketalternate", "--script" }); // TODO: change the tag tag locations of Dockerfile and Dockstore.cwl, now should be able to publish }
25,180
0
/** * Static helper method that can be used instead of instantiating comparator * (used by unit tests, can be used by code too) */
public static int staticCompare(UUID u1, UUID u2) { // First: major sorting by types int type = u1.version(); int diff = type - u2.version(); if (diff != 0) { return diff; } // Second: for time-based variant, order by time stamp: if (type == UUIDType.TIME_BASED.raw()) { diff = compareULongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { // or if that won't work, by other bits lexically diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } else { // note: java.util.UUIDs compares with sign extension, IMO that's wrong, so: diff = compareULongs(u1.getMostSignificantBits(), u2.getMostSignificantBits()); if (diff == 0) { diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } return diff; }
NONSATD
true
public static int staticCompare(UUID u1, UUID u2) { // First: major sorting by types int type = u1.version(); int diff = type - u2.version(); if (diff != 0) { return diff; } // Second: for time-based variant, order by time stamp: if (type == UUIDType.TIME_BASED.raw()) { diff = compareULongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { // or if that won't work, by other bits lexically diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } else { // note: java.util.UUIDs compares with sign extension, IMO that's wrong, so: diff = compareULongs(u1.getMostSignificantBits(), u2.getMostSignificantBits()); if (diff == 0) { diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } return diff; }
public static int staticCompare(UUID u1, UUID u2) { // First: major sorting by types int type = u1.version(); int diff = type - u2.version(); if (diff != 0) { return diff; } // Second: for time-based variant, order by time stamp: if (type == UUIDType.TIME_BASED.raw()) { diff = compareULongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { // or if that won't work, by other bits lexically diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } else { // note: java.util.UUIDs compares with sign extension, IMO that's wrong, so: diff = compareULongs(u1.getMostSignificantBits(), u2.getMostSignificantBits()); if (diff == 0) { diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } return diff; }
public static int staticCompare(UUID u1, UUID u2) { // First: major sorting by types int type = u1.version(); int diff = type - u2.version(); if (diff != 0) { return diff; } // Second: for time-based variant, order by time stamp: if (type == UUIDType.TIME_BASED.raw()) { diff = compareULongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { // or if that won't work, by other bits lexically diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } else { // note: java.util.UUIDs compares with sign extension, IMO that's wrong, so: diff = compareULongs(u1.getMostSignificantBits(), u2.getMostSignificantBits()); if (diff == 0) { diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } return diff; }
25,180
1
// First: major sorting by types
public static int staticCompare(UUID u1, UUID u2) { // First: major sorting by types int type = u1.version(); int diff = type - u2.version(); if (diff != 0) { return diff; } // Second: for time-based variant, order by time stamp: if (type == UUIDType.TIME_BASED.raw()) { diff = compareULongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { // or if that won't work, by other bits lexically diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } else { // note: java.util.UUIDs compares with sign extension, IMO that's wrong, so: diff = compareULongs(u1.getMostSignificantBits(), u2.getMostSignificantBits()); if (diff == 0) { diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } return diff; }
NONSATD
true
public static int staticCompare(UUID u1, UUID u2) { // First: major sorting by types int type = u1.version(); int diff = type - u2.version();
public static int staticCompare(UUID u1, UUID u2) { // First: major sorting by types int type = u1.version(); int diff = type - u2.version(); if (diff != 0) { return diff; } // Second: for time-based variant, order by time stamp: if (type == UUIDType.TIME_BASED.raw()) { diff = compareULongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { // or if that won't work, by other bits lexically
public static int staticCompare(UUID u1, UUID u2) { // First: major sorting by types int type = u1.version(); int diff = type - u2.version(); if (diff != 0) { return diff; } // Second: for time-based variant, order by time stamp: if (type == UUIDType.TIME_BASED.raw()) { diff = compareULongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { // or if that won't work, by other bits lexically diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } else { // note: java.util.UUIDs compares with sign extension, IMO that's wrong, so: diff = compareULongs(u1.getMostSignificantBits(), u2.getMostSignificantBits()); if (diff == 0) { diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); }
25,180
2
// Second: for time-based variant, order by time stamp:
public static int staticCompare(UUID u1, UUID u2) { // First: major sorting by types int type = u1.version(); int diff = type - u2.version(); if (diff != 0) { return diff; } // Second: for time-based variant, order by time stamp: if (type == UUIDType.TIME_BASED.raw()) { diff = compareULongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { // or if that won't work, by other bits lexically diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } else { // note: java.util.UUIDs compares with sign extension, IMO that's wrong, so: diff = compareULongs(u1.getMostSignificantBits(), u2.getMostSignificantBits()); if (diff == 0) { diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } return diff; }
NONSATD
true
return diff; } // Second: for time-based variant, order by time stamp: if (type == UUIDType.TIME_BASED.raw()) { diff = compareULongs(u1.timestamp(), u2.timestamp());
public static int staticCompare(UUID u1, UUID u2) { // First: major sorting by types int type = u1.version(); int diff = type - u2.version(); if (diff != 0) { return diff; } // Second: for time-based variant, order by time stamp: if (type == UUIDType.TIME_BASED.raw()) { diff = compareULongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { // or if that won't work, by other bits lexically diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } else { // note: java.util.UUIDs compares with sign extension, IMO that's wrong, so: diff = compareULongs(u1.getMostSignificantBits(), u2.getMostSignificantBits());
public static int staticCompare(UUID u1, UUID u2) { // First: major sorting by types int type = u1.version(); int diff = type - u2.version(); if (diff != 0) { return diff; } // Second: for time-based variant, order by time stamp: if (type == UUIDType.TIME_BASED.raw()) { diff = compareULongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { // or if that won't work, by other bits lexically diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } else { // note: java.util.UUIDs compares with sign extension, IMO that's wrong, so: diff = compareULongs(u1.getMostSignificantBits(), u2.getMostSignificantBits()); if (diff == 0) { diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } return diff; }
25,180
3
// or if that won't work, by other bits lexically
public static int staticCompare(UUID u1, UUID u2) { // First: major sorting by types int type = u1.version(); int diff = type - u2.version(); if (diff != 0) { return diff; } // Second: for time-based variant, order by time stamp: if (type == UUIDType.TIME_BASED.raw()) { diff = compareULongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { // or if that won't work, by other bits lexically diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } else { // note: java.util.UUIDs compares with sign extension, IMO that's wrong, so: diff = compareULongs(u1.getMostSignificantBits(), u2.getMostSignificantBits()); if (diff == 0) { diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } return diff; }
NONSATD
true
diff = compareULongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { // or if that won't work, by other bits lexically diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); }
// First: major sorting by types int type = u1.version(); int diff = type - u2.version(); if (diff != 0) { return diff; } // Second: for time-based variant, order by time stamp: if (type == UUIDType.TIME_BASED.raw()) { diff = compareULongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { // or if that won't work, by other bits lexically diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } else { // note: java.util.UUIDs compares with sign extension, IMO that's wrong, so: diff = compareULongs(u1.getMostSignificantBits(), u2.getMostSignificantBits()); if (diff == 0) { diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); }
public static int staticCompare(UUID u1, UUID u2) { // First: major sorting by types int type = u1.version(); int diff = type - u2.version(); if (diff != 0) { return diff; } // Second: for time-based variant, order by time stamp: if (type == UUIDType.TIME_BASED.raw()) { diff = compareULongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { // or if that won't work, by other bits lexically diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } else { // note: java.util.UUIDs compares with sign extension, IMO that's wrong, so: diff = compareULongs(u1.getMostSignificantBits(), u2.getMostSignificantBits()); if (diff == 0) { diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } return diff; }
25,180
4
// note: java.util.UUIDs compares with sign extension, IMO that's wrong, so:
public static int staticCompare(UUID u1, UUID u2) { // First: major sorting by types int type = u1.version(); int diff = type - u2.version(); if (diff != 0) { return diff; } // Second: for time-based variant, order by time stamp: if (type == UUIDType.TIME_BASED.raw()) { diff = compareULongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { // or if that won't work, by other bits lexically diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } else { // note: java.util.UUIDs compares with sign extension, IMO that's wrong, so: diff = compareULongs(u1.getMostSignificantBits(), u2.getMostSignificantBits()); if (diff == 0) { diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } return diff; }
NONSATD
true
} } else { // note: java.util.UUIDs compares with sign extension, IMO that's wrong, so: diff = compareULongs(u1.getMostSignificantBits(), u2.getMostSignificantBits());
return diff; } // Second: for time-based variant, order by time stamp: if (type == UUIDType.TIME_BASED.raw()) { diff = compareULongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { // or if that won't work, by other bits lexically diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } else { // note: java.util.UUIDs compares with sign extension, IMO that's wrong, so: diff = compareULongs(u1.getMostSignificantBits(), u2.getMostSignificantBits()); if (diff == 0) { diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } return diff; }
public static int staticCompare(UUID u1, UUID u2) { // First: major sorting by types int type = u1.version(); int diff = type - u2.version(); if (diff != 0) { return diff; } // Second: for time-based variant, order by time stamp: if (type == UUIDType.TIME_BASED.raw()) { diff = compareULongs(u1.timestamp(), u2.timestamp()); if (diff == 0) { // or if that won't work, by other bits lexically diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } else { // note: java.util.UUIDs compares with sign extension, IMO that's wrong, so: diff = compareULongs(u1.getMostSignificantBits(), u2.getMostSignificantBits()); if (diff == 0) { diff = compareULongs(u1.getLeastSignificantBits(), u2.getLeastSignificantBits()); } } return diff; }
16,991
0
/** * This tests that you can refresh user data by refreshing a tool * ONLY WORKS if the current user in the database dump has no metadata, and on Github there is metadata (bio, location) * If the user has metadata, test will pass as long as the user's metadata isn't the same as Github already */
@Test public void testRefreshingUserMetadata() { // Setup database // Refresh a tool Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "refresh", "--entry", "quay.io/dockstoretestuser/quayandbitbucket", "--script" }); // Check that user has been updated // TODO: bizarrely, the new GitHub Java API library doesn't seem to handle bio //final long count = testingPostgres.runSelectStatement("select count(*) from enduser where location='Toronto' and bio='I am a test user'", long.class); final long count = testingPostgres.runSelectStatement("select count(*) from user_profile where location='Toronto'", long.class); Assert.assertEquals("One user should have this info now, there are " + count, 1, count); }
NONSATD
true
@Test public void testRefreshingUserMetadata() { // Setup database // Refresh a tool Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "refresh", "--entry", "quay.io/dockstoretestuser/quayandbitbucket", "--script" }); // Check that user has been updated // TODO: bizarrely, the new GitHub Java API library doesn't seem to handle bio //final long count = testingPostgres.runSelectStatement("select count(*) from enduser where location='Toronto' and bio='I am a test user'", long.class); final long count = testingPostgres.runSelectStatement("select count(*) from user_profile where location='Toronto'", long.class); Assert.assertEquals("One user should have this info now, there are " + count, 1, count); }
@Test public void testRefreshingUserMetadata() { // Setup database // Refresh a tool Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "refresh", "--entry", "quay.io/dockstoretestuser/quayandbitbucket", "--script" }); // Check that user has been updated // TODO: bizarrely, the new GitHub Java API library doesn't seem to handle bio //final long count = testingPostgres.runSelectStatement("select count(*) from enduser where location='Toronto' and bio='I am a test user'", long.class); final long count = testingPostgres.runSelectStatement("select count(*) from user_profile where location='Toronto'", long.class); Assert.assertEquals("One user should have this info now, there are " + count, 1, count); }
@Test public void testRefreshingUserMetadata() { // Setup database // Refresh a tool Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "refresh", "--entry", "quay.io/dockstoretestuser/quayandbitbucket", "--script" }); // Check that user has been updated // TODO: bizarrely, the new GitHub Java API library doesn't seem to handle bio //final long count = testingPostgres.runSelectStatement("select count(*) from enduser where location='Toronto' and bio='I am a test user'", long.class); final long count = testingPostgres.runSelectStatement("select count(*) from user_profile where location='Toronto'", long.class); Assert.assertEquals("One user should have this info now, there are " + count, 1, count); }
16,991
1
// Setup database // Refresh a tool
@Test public void testRefreshingUserMetadata() { // Setup database // Refresh a tool Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "refresh", "--entry", "quay.io/dockstoretestuser/quayandbitbucket", "--script" }); // Check that user has been updated // TODO: bizarrely, the new GitHub Java API library doesn't seem to handle bio //final long count = testingPostgres.runSelectStatement("select count(*) from enduser where location='Toronto' and bio='I am a test user'", long.class); final long count = testingPostgres.runSelectStatement("select count(*) from user_profile where location='Toronto'", long.class); Assert.assertEquals("One user should have this info now, there are " + count, 1, count); }
NONSATD
true
@Test public void testRefreshingUserMetadata() { // Setup database // Refresh a tool Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "refresh", "--entry", "quay.io/dockstoretestuser/quayandbitbucket", "--script" });
@Test public void testRefreshingUserMetadata() { // Setup database // Refresh a tool Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "refresh", "--entry", "quay.io/dockstoretestuser/quayandbitbucket", "--script" }); // Check that user has been updated // TODO: bizarrely, the new GitHub Java API library doesn't seem to handle bio //final long count = testingPostgres.runSelectStatement("select count(*) from enduser where location='Toronto' and bio='I am a test user'", long.class); final long count = testingPostgres.runSelectStatement("select count(*) from user_profile where location='Toronto'", long.class); Assert.assertEquals("One user should have this info now, there are " + count, 1, count); }
@Test public void testRefreshingUserMetadata() { // Setup database // Refresh a tool Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "refresh", "--entry", "quay.io/dockstoretestuser/quayandbitbucket", "--script" }); // Check that user has been updated // TODO: bizarrely, the new GitHub Java API library doesn't seem to handle bio //final long count = testingPostgres.runSelectStatement("select count(*) from enduser where location='Toronto' and bio='I am a test user'", long.class); final long count = testingPostgres.runSelectStatement("select count(*) from user_profile where location='Toronto'", long.class); Assert.assertEquals("One user should have this info now, there are " + count, 1, count); }
16,991
2
// Check that user has been updated // TODO: bizarrely, the new GitHub Java API library doesn't seem to handle bio //final long count = testingPostgres.runSelectStatement("select count(*) from enduser where location='Toronto' and bio='I am a test user'", long.class);
@Test public void testRefreshingUserMetadata() { // Setup database // Refresh a tool Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "refresh", "--entry", "quay.io/dockstoretestuser/quayandbitbucket", "--script" }); // Check that user has been updated // TODO: bizarrely, the new GitHub Java API library doesn't seem to handle bio //final long count = testingPostgres.runSelectStatement("select count(*) from enduser where location='Toronto' and bio='I am a test user'", long.class); final long count = testingPostgres.runSelectStatement("select count(*) from user_profile where location='Toronto'", long.class); Assert.assertEquals("One user should have this info now, there are " + count, 1, count); }
DEFECT
true
Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "refresh", "--entry", "quay.io/dockstoretestuser/quayandbitbucket", "--script" }); // Check that user has been updated // TODO: bizarrely, the new GitHub Java API library doesn't seem to handle bio //final long count = testingPostgres.runSelectStatement("select count(*) from enduser where location='Toronto' and bio='I am a test user'", long.class); final long count = testingPostgres.runSelectStatement("select count(*) from user_profile where location='Toronto'", long.class); Assert.assertEquals("One user should have this info now, there are " + count, 1, count);
@Test public void testRefreshingUserMetadata() { // Setup database // Refresh a tool Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "refresh", "--entry", "quay.io/dockstoretestuser/quayandbitbucket", "--script" }); // Check that user has been updated // TODO: bizarrely, the new GitHub Java API library doesn't seem to handle bio //final long count = testingPostgres.runSelectStatement("select count(*) from enduser where location='Toronto' and bio='I am a test user'", long.class); final long count = testingPostgres.runSelectStatement("select count(*) from user_profile where location='Toronto'", long.class); Assert.assertEquals("One user should have this info now, there are " + count, 1, count); }
@Test public void testRefreshingUserMetadata() { // Setup database // Refresh a tool Client.main(new String[] { "--config", ResourceHelpers.resourceFilePath("config_file.txt"), "tool", "refresh", "--entry", "quay.io/dockstoretestuser/quayandbitbucket", "--script" }); // Check that user has been updated // TODO: bizarrely, the new GitHub Java API library doesn't seem to handle bio //final long count = testingPostgres.runSelectStatement("select count(*) from enduser where location='Toronto' and bio='I am a test user'", long.class); final long count = testingPostgres.runSelectStatement("select count(*) from user_profile where location='Toronto'", long.class); Assert.assertEquals("One user should have this info now, there are " + count, 1, count); }
8,804
0
// If the block does not exist anymore, then it's not an error.
public void handle(ExtendedBlock block, IOException e) { FsVolumeSpi volume = scanner.volume; if (e == null) { LOG.trace("Successfully scanned {} on {}", block, volume); return; } // If the block does not exist anymore, then it's not an error. if (!volume.getDataset().contains(block)) { LOG.debug("Volume {}: block {} is no longer in the dataset.", volume, block); return; } // If the block exists, the exception may due to a race with write: // The BlockSender got an old block path in rbw. BlockReceiver removed // the rbw block from rbw to finalized but BlockSender tried to open the // file before BlockReceiver updated the VolumeMap. The state of the // block can be changed again now, so ignore this error here. If there // is a block really deleted by mistake, DirectoryScan should catch it. if (e instanceof FileNotFoundException ) { LOG.info("Volume {}: verification failed for {} because of " + "FileNotFoundException. This may be due to a race with write.", volume, block); return; } LOG.warn("Reporting bad {} on {}", block, volume); try { scanner.datanode.reportBadBlocks(block, volume); } catch (IOException ie) { // This is bad, but not bad enough to shut down the scanner. LOG.warn("Cannot report bad block " + block, ie); } }
NONSATD
true
return; } // If the block does not exist anymore, then it's not an error. if (!volume.getDataset().contains(block)) { LOG.debug("Volume {}: block {} is no longer in the dataset.",
public void handle(ExtendedBlock block, IOException e) { FsVolumeSpi volume = scanner.volume; if (e == null) { LOG.trace("Successfully scanned {} on {}", block, volume); return; } // If the block does not exist anymore, then it's not an error. if (!volume.getDataset().contains(block)) { LOG.debug("Volume {}: block {} is no longer in the dataset.", volume, block); return; } // If the block exists, the exception may due to a race with write: // The BlockSender got an old block path in rbw. BlockReceiver removed // the rbw block from rbw to finalized but BlockSender tried to open the // file before BlockReceiver updated the VolumeMap. The state of the // block can be changed again now, so ignore this error here. If there
public void handle(ExtendedBlock block, IOException e) { FsVolumeSpi volume = scanner.volume; if (e == null) { LOG.trace("Successfully scanned {} on {}", block, volume); return; } // If the block does not exist anymore, then it's not an error. if (!volume.getDataset().contains(block)) { LOG.debug("Volume {}: block {} is no longer in the dataset.", volume, block); return; } // If the block exists, the exception may due to a race with write: // The BlockSender got an old block path in rbw. BlockReceiver removed // the rbw block from rbw to finalized but BlockSender tried to open the // file before BlockReceiver updated the VolumeMap. The state of the // block can be changed again now, so ignore this error here. If there // is a block really deleted by mistake, DirectoryScan should catch it. if (e instanceof FileNotFoundException ) { LOG.info("Volume {}: verification failed for {} because of " + "FileNotFoundException. This may be due to a race with write.", volume, block); return; } LOG.warn("Reporting bad {} on {}", block, volume); try { scanner.datanode.reportBadBlocks(block, volume);
8,804
1
// If the block exists, the exception may due to a race with write: // The BlockSender got an old block path in rbw. BlockReceiver removed // the rbw block from rbw to finalized but BlockSender tried to open the // file before BlockReceiver updated the VolumeMap. The state of the // block can be changed again now, so ignore this error here. If there // is a block really deleted by mistake, DirectoryScan should catch it.
public void handle(ExtendedBlock block, IOException e) { FsVolumeSpi volume = scanner.volume; if (e == null) { LOG.trace("Successfully scanned {} on {}", block, volume); return; } // If the block does not exist anymore, then it's not an error. if (!volume.getDataset().contains(block)) { LOG.debug("Volume {}: block {} is no longer in the dataset.", volume, block); return; } // If the block exists, the exception may due to a race with write: // The BlockSender got an old block path in rbw. BlockReceiver removed // the rbw block from rbw to finalized but BlockSender tried to open the // file before BlockReceiver updated the VolumeMap. The state of the // block can be changed again now, so ignore this error here. If there // is a block really deleted by mistake, DirectoryScan should catch it. if (e instanceof FileNotFoundException ) { LOG.info("Volume {}: verification failed for {} because of " + "FileNotFoundException. This may be due to a race with write.", volume, block); return; } LOG.warn("Reporting bad {} on {}", block, volume); try { scanner.datanode.reportBadBlocks(block, volume); } catch (IOException ie) { // This is bad, but not bad enough to shut down the scanner. LOG.warn("Cannot report bad block " + block, ie); } }
NONSATD
true
return; } // If the block exists, the exception may due to a race with write: // The BlockSender got an old block path in rbw. BlockReceiver removed // the rbw block from rbw to finalized but BlockSender tried to open the // file before BlockReceiver updated the VolumeMap. The state of the // block can be changed again now, so ignore this error here. If there // is a block really deleted by mistake, DirectoryScan should catch it. if (e instanceof FileNotFoundException ) { LOG.info("Volume {}: verification failed for {} because of " +
if (e == null) { LOG.trace("Successfully scanned {} on {}", block, volume); return; } // If the block does not exist anymore, then it's not an error. if (!volume.getDataset().contains(block)) { LOG.debug("Volume {}: block {} is no longer in the dataset.", volume, block); return; } // If the block exists, the exception may due to a race with write: // The BlockSender got an old block path in rbw. BlockReceiver removed // the rbw block from rbw to finalized but BlockSender tried to open the // file before BlockReceiver updated the VolumeMap. The state of the // block can be changed again now, so ignore this error here. If there // is a block really deleted by mistake, DirectoryScan should catch it. if (e instanceof FileNotFoundException ) { LOG.info("Volume {}: verification failed for {} because of " + "FileNotFoundException. This may be due to a race with write.", volume, block); return; } LOG.warn("Reporting bad {} on {}", block, volume); try { scanner.datanode.reportBadBlocks(block, volume); } catch (IOException ie) {
public void handle(ExtendedBlock block, IOException e) { FsVolumeSpi volume = scanner.volume; if (e == null) { LOG.trace("Successfully scanned {} on {}", block, volume); return; } // If the block does not exist anymore, then it's not an error. if (!volume.getDataset().contains(block)) { LOG.debug("Volume {}: block {} is no longer in the dataset.", volume, block); return; } // If the block exists, the exception may due to a race with write: // The BlockSender got an old block path in rbw. BlockReceiver removed // the rbw block from rbw to finalized but BlockSender tried to open the // file before BlockReceiver updated the VolumeMap. The state of the // block can be changed again now, so ignore this error here. If there // is a block really deleted by mistake, DirectoryScan should catch it. if (e instanceof FileNotFoundException ) { LOG.info("Volume {}: verification failed for {} because of " + "FileNotFoundException. This may be due to a race with write.", volume, block); return; } LOG.warn("Reporting bad {} on {}", block, volume); try { scanner.datanode.reportBadBlocks(block, volume); } catch (IOException ie) { // This is bad, but not bad enough to shut down the scanner. LOG.warn("Cannot report bad block " + block, ie); } }
8,804
2
// This is bad, but not bad enough to shut down the scanner.
public void handle(ExtendedBlock block, IOException e) { FsVolumeSpi volume = scanner.volume; if (e == null) { LOG.trace("Successfully scanned {} on {}", block, volume); return; } // If the block does not exist anymore, then it's not an error. if (!volume.getDataset().contains(block)) { LOG.debug("Volume {}: block {} is no longer in the dataset.", volume, block); return; } // If the block exists, the exception may due to a race with write: // The BlockSender got an old block path in rbw. BlockReceiver removed // the rbw block from rbw to finalized but BlockSender tried to open the // file before BlockReceiver updated the VolumeMap. The state of the // block can be changed again now, so ignore this error here. If there // is a block really deleted by mistake, DirectoryScan should catch it. if (e instanceof FileNotFoundException ) { LOG.info("Volume {}: verification failed for {} because of " + "FileNotFoundException. This may be due to a race with write.", volume, block); return; } LOG.warn("Reporting bad {} on {}", block, volume); try { scanner.datanode.reportBadBlocks(block, volume); } catch (IOException ie) { // This is bad, but not bad enough to shut down the scanner. LOG.warn("Cannot report bad block " + block, ie); } }
DESIGN
true
scanner.datanode.reportBadBlocks(block, volume); } catch (IOException ie) { // This is bad, but not bad enough to shut down the scanner. LOG.warn("Cannot report bad block " + block, ie); }
if (e instanceof FileNotFoundException ) { LOG.info("Volume {}: verification failed for {} because of " + "FileNotFoundException. This may be due to a race with write.", volume, block); return; } LOG.warn("Reporting bad {} on {}", block, volume); try { scanner.datanode.reportBadBlocks(block, volume); } catch (IOException ie) { // This is bad, but not bad enough to shut down the scanner. LOG.warn("Cannot report bad block " + block, ie); } }
LOG.debug("Volume {}: block {} is no longer in the dataset.", volume, block); return; } // If the block exists, the exception may due to a race with write: // The BlockSender got an old block path in rbw. BlockReceiver removed // the rbw block from rbw to finalized but BlockSender tried to open the // file before BlockReceiver updated the VolumeMap. The state of the // block can be changed again now, so ignore this error here. If there // is a block really deleted by mistake, DirectoryScan should catch it. if (e instanceof FileNotFoundException ) { LOG.info("Volume {}: verification failed for {} because of " + "FileNotFoundException. This may be due to a race with write.", volume, block); return; } LOG.warn("Reporting bad {} on {}", block, volume); try { scanner.datanode.reportBadBlocks(block, volume); } catch (IOException ie) { // This is bad, but not bad enough to shut down the scanner. LOG.warn("Cannot report bad block " + block, ie); } }
16,997
0
/** * Handler for an embedded member. * @param mmds Chain of member metadata to the embedded member * @param embCmd Class metadata for the embedded member type * @param clr ClassLoader resolver * @param embmd Any EmbeddedMetaData defining column info * @param ownerNested Whether the owner is nested */
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
NONSATD
true
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
16,997
1
// Go through all members of the embedded type
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
NONSATD
true
NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++)
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName()))
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) {
16,997
2
// Don't need column if not persistent
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
NONSATD
true
if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; }
MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) {
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; }
16,997
3
// Special case of this being a link back to the owner. TODO Repeat this for nested and their owners
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
NONSATD
true
if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; }
for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) {
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd))
16,997
4
// Nested embedded PC, so recurse
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
NONSATD
true
if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED))
break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } }
if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true);
16,997
5
// Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
NONSATD
true
if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0);
String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) {
RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); }
16,997
6
// TODO Create mapping for the related info under the above column
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
IMPLEMENTATION
true
} mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member
{ col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED))
} else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) {
16,997
7
// Recurse through the embedded member
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
NONSATD
true
// TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); }
} MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds);
{ col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); }
16,997
8
// Nested embedded collection, so recurse
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
NONSATD
true
if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) {
mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null)
else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType());
16,997
9
// Add column for the collection (since the store needs a name to reference it by)
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
NONSATD
true
List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0);
} else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) {
col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); }
16,997
10
// TODO Create mapping for the related info under the above column // Recurse through the embedded collection element
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
IMPLEMENTATION
true
} mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested);
{ col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) {
} else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition());
16,997
11
// Nested embedded map, so recurse
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
NONSATD
true
else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) {
processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; }
} MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData();
16,997
12
// TODO Support nested embedded map key/value
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
IMPLEMENTATION
true
if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); }
{ NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) {
if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true);
16,997
13
// Nested embedded array, so recurse
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
NONSATD
true
else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) {
NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null)
NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType());
16,997
14
// Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
IMPLEMENTATION
true
List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0);
continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) {
{ // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); }
16,997
15
// TODO Create mapping for the related info under the above column // Recurse through the embedded array element
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
IMPLEMENTATION
true
} mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested);
{ col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) {
} else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition());
16,997
16
// 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
NONSATD
true
if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null);
} } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition());
mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col);
16,997
17
// TODO Pass in embedded colmds if they have jdbcType info?
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
DESIGN
true
else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) {
MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j);
col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); }
16,997
18
// Create column(s) for this type using a TypeConverter
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
NONSATD
true
if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) {
{ schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null)
{ col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType());
16,997
19
// Create column for basic type
protected void processEmbeddedMember(List<AbstractMemberMetaData> mmds, AbstractClassMetaData embCmd, ClassLoaderResolver clr, EmbeddedMetaData embmd, boolean ownerNested) { TypeManager typeMgr = storeMgr.getNucleusContext().getTypeManager(); MetaDataManager mmgr = storeMgr.getMetaDataManager(); NamingFactory namingFactory = storeMgr.getNamingFactory(); AbstractMemberMetaData lastMmd = mmds.get(mmds.size()-1); // Go through all members of the embedded type int[] memberPositions = embCmd.getAllMemberPositions(); for (int i=0;i<memberPositions.length;i++) { AbstractMemberMetaData mmd = embCmd.getMetaDataForManagedMemberAtAbsolutePosition(memberPositions[i]); if (mmd.getPersistenceModifier() != FieldPersistenceModifier.PERSISTENT) { // Don't need column if not persistent continue; } if (mmds.size() == 1 && embmd != null && embmd.getOwnerMember() != null && embmd.getOwnerMember().equals(mmd.getName())) { // Special case of this being a link back to the owner. TODO Repeat this for nested and their owners continue; } AbstractMemberMetaData embmdMmd = null; if (embmd != null) { AbstractMemberMetaData[] embmdMmds = embmd.getMemberMetaData(); if (embmdMmds != null) { for (AbstractMemberMetaData thisMmd : embmdMmds) { if (thisMmd.getName().equals(mmd.getName())) { embmdMmd = thisMmd; break; } } } } RelationType relationType = mmd.getRelationType(clr); if (relationType != RelationType.NONE && MetaDataUtils.getInstance().isMemberEmbedded(mmgr, clr, mmd, relationType, lastMmd)) { if (RelationType.isRelationSingleValued(relationType)) { // Nested embedded PC, so recurse boolean nested = false; if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_PC_NESTED)) { nested = !storeMgr.getNucleusContext().getConfiguration().getBooleanProperty(PropertyNames.PROPERTY_METADATA_EMBEDDED_PC_FLAT); String nestedStr = mmd.getValueForExtension("nested"); if (nestedStr != null && nestedStr.equalsIgnoreCase("" + !nested)) { nested = !nested; } } List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); if (nested) { // Embedded object stored as nested under this in the owner table (where the datastore supports that) // Add column for the owner of the embedded object, typically for the column name only ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column } // Recurse through the embedded member processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, nested); } else { if (mmd.hasCollection()) { // Nested embedded collection, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_COLLECTION_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the collection (since the store needs a name to reference it by) ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded collection element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getCollection().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded collection. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasMap()) { // Nested embedded map, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_MAP_NESTED)) { // TODO Support nested embedded map key/value NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not yet supported so ignoring"); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded map. Not supported for this datastore so ignoring"); continue; } } else if (mmd.hasArray()) { // Nested embedded array, so recurse if (storeMgr.getSupportedOptions().contains(StoreManager.OPTION_ORM_EMBEDDED_ARRAY_NESTED)) { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); // Add column for the array (since the store needs a name to reference it by) TODO Extract this block out and reuse it ColumnMetaData[] colmds = mmd.getColumnMetaData(); String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(true); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); // TODO Create mapping for the related info under the above column // Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { TypeConverter typeConv = getTypeConverterForMember(mmd, colmds, typeMgr); // TODO Pass in embedded colmds if they have jdbcType info? if (typeConv != null) { // Create column(s) for this type using a TypeConverter if (typeConv instanceof MultiColumnConverter) { Class[] colJavaTypes = ((MultiColumnConverter)typeConv).getDatastoreColumnTypes(); Column[] cols = new Column[colJavaTypes.length]; for (int j=0;j<colJavaTypes.length;j++) { String colName = namingFactory.getColumnName(embMmds, j); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[j].getPosition()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getPosition() != null) { col.setPosition(colmds[j].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == colJavaTypes.length && embmdMmd.getColumnMetaData()[j].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[j].getJdbcType()); } else if (colmds != null && colmds.length == colJavaTypes.length && colmds[j].getJdbcType() != null) { col.setJdbcType(colmds[j].getJdbcType()); } cols[j] = col; } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, cols, typeConv); for (int j=0;j<colJavaTypes.length;j++) { ((ColumnImpl)cols[j]).setMemberColumnMapping(mapping); } if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } else { String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, typeConv); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); mapping.setTypeConverter(typeConv); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } else { // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); AbstractMemberMetaData theMmd = embMmds.get(0); if (theMmd.isPrimaryKey()) { col.setPrimaryKey(); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col); col.setMemberColumnMapping(mapping); if (schemaVerifier != null) { schemaVerifier.attributeEmbeddedMember(mapping, embMmds); } mappingByEmbeddedMember.put(getEmbeddedMemberNavigatedPath(embMmds), mapping); } } } } }
NONSATD
true
// 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null);
} else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition());
// Recurse through the embedded array element processEmbeddedMember(embMmds, mmgr.getMetaDataForClass(mmd.getArray().getElementType(), clr), clr, embmdMmd != null ? embmdMmd.getEmbeddedMetaData() : null, true); } else { NucleusLogger.DATASTORE_SCHEMA.warn("Member " + mmd.getFullFieldName() + " is a (nested) embedded array. Not supported for this datastore so ignoring"); continue; } } } } else { List<AbstractMemberMetaData> embMmds = new ArrayList<AbstractMemberMetaData>(mmds); embMmds.add(mmd); ColumnMetaData[] colmds = mmd.getColumnMetaData(); if (relationType != RelationType.NONE) { // 1-1/N-1 stored as single column with persistable-id // 1-N/M-N stored as single column with collection<persistable-id> // Create column for basic type String colName = namingFactory.getColumnName(embMmds, 0); ColumnImpl col = addEmbeddedColumn(colName, null); col.setNested(ownerNested); if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getPosition() != null) { col.setPosition(embmdMmd.getColumnMetaData()[0].getPosition()); } else if (colmds != null && colmds.length == 1 && colmds[0].getPosition() != null) { col.setPosition(colmds[0].getPosition()); } if (embmdMmd != null && embmdMmd.getColumnMetaData() != null && embmdMmd.getColumnMetaData().length == 1 && embmdMmd.getColumnMetaData()[0].getJdbcType() != null) { col.setJdbcType(embmdMmd.getColumnMetaData()[0].getJdbcType()); } else if (colmds != null && colmds.length == 1 && colmds[0].getJdbcType() != null) { col.setJdbcType(colmds[0].getJdbcType()); } MemberColumnMapping mapping = new MemberColumnMappingImpl(mmd, col);
17,001
0
// TODO: Can't we just use the original set?
@Override @SuppressWarnings("unchecked") public Set keySet(Predicate predicate) { checkTransactionState(); checkNotNull(predicate, "Predicate should not be null!"); checkNotInstanceOf(PagingPredicate.class, predicate, "Paging is not supported for Transactional queries!"); MapQueryEngine queryEngine = mapServiceContext.getMapQueryEngine(name); SerializationService serializationService = getNodeEngine().getSerializationService(); QueryResult result = queryEngine.invokeQueryAllPartitions(name, predicate, IterationType.KEY); Set<Object> queryResult = new QueryResultCollection(serializationService, IterationType.KEY, false, true, result); // TODO: Can't we just use the original set? Set<Object> keySet = new HashSet<Object>(queryResult); Extractors extractors = mapServiceContext.getExtractors(name); for (Map.Entry<Data, TxnValueWrapper> entry : txMap.entrySet()) { Data keyData = entry.getKey(); if (!Type.REMOVED.equals(entry.getValue().type)) { Object value = (entry.getValue().value instanceof Data) ? toObjectIfNeeded(entry.getValue().value) : entry.getValue().value; QueryableEntry queryEntry = new CachedQueryEntry((InternalSerializationService) serializationService, keyData, value, extractors); // apply predicate on txMap if (predicate.apply(queryEntry)) { Object keyObject = serializationService.toObject(keyData); keySet.add(keyObject); } } else { // meanwhile remove keys which are not in txMap Object keyObject = serializationService.toObject(keyData); keySet.remove(keyObject); } } return keySet; }
DESIGN
true
QueryResult result = queryEngine.invokeQueryAllPartitions(name, predicate, IterationType.KEY); Set<Object> queryResult = new QueryResultCollection(serializationService, IterationType.KEY, false, true, result); // TODO: Can't we just use the original set? Set<Object> keySet = new HashSet<Object>(queryResult); Extractors extractors = mapServiceContext.getExtractors(name);
@Override @SuppressWarnings("unchecked") public Set keySet(Predicate predicate) { checkTransactionState(); checkNotNull(predicate, "Predicate should not be null!"); checkNotInstanceOf(PagingPredicate.class, predicate, "Paging is not supported for Transactional queries!"); MapQueryEngine queryEngine = mapServiceContext.getMapQueryEngine(name); SerializationService serializationService = getNodeEngine().getSerializationService(); QueryResult result = queryEngine.invokeQueryAllPartitions(name, predicate, IterationType.KEY); Set<Object> queryResult = new QueryResultCollection(serializationService, IterationType.KEY, false, true, result); // TODO: Can't we just use the original set? Set<Object> keySet = new HashSet<Object>(queryResult); Extractors extractors = mapServiceContext.getExtractors(name); for (Map.Entry<Data, TxnValueWrapper> entry : txMap.entrySet()) { Data keyData = entry.getKey(); if (!Type.REMOVED.equals(entry.getValue().type)) { Object value = (entry.getValue().value instanceof Data) ? toObjectIfNeeded(entry.getValue().value) : entry.getValue().value; QueryableEntry queryEntry = new CachedQueryEntry((InternalSerializationService) serializationService, keyData, value, extractors); // apply predicate on txMap
@Override @SuppressWarnings("unchecked") public Set keySet(Predicate predicate) { checkTransactionState(); checkNotNull(predicate, "Predicate should not be null!"); checkNotInstanceOf(PagingPredicate.class, predicate, "Paging is not supported for Transactional queries!"); MapQueryEngine queryEngine = mapServiceContext.getMapQueryEngine(name); SerializationService serializationService = getNodeEngine().getSerializationService(); QueryResult result = queryEngine.invokeQueryAllPartitions(name, predicate, IterationType.KEY); Set<Object> queryResult = new QueryResultCollection(serializationService, IterationType.KEY, false, true, result); // TODO: Can't we just use the original set? Set<Object> keySet = new HashSet<Object>(queryResult); Extractors extractors = mapServiceContext.getExtractors(name); for (Map.Entry<Data, TxnValueWrapper> entry : txMap.entrySet()) { Data keyData = entry.getKey(); if (!Type.REMOVED.equals(entry.getValue().type)) { Object value = (entry.getValue().value instanceof Data) ? toObjectIfNeeded(entry.getValue().value) : entry.getValue().value; QueryableEntry queryEntry = new CachedQueryEntry((InternalSerializationService) serializationService, keyData, value, extractors); // apply predicate on txMap if (predicate.apply(queryEntry)) { Object keyObject = serializationService.toObject(keyData); keySet.add(keyObject); } } else { // meanwhile remove keys which are not in txMap Object keyObject = serializationService.toObject(keyData); keySet.remove(keyObject); } }
17,001
1
// apply predicate on txMap
@Override @SuppressWarnings("unchecked") public Set keySet(Predicate predicate) { checkTransactionState(); checkNotNull(predicate, "Predicate should not be null!"); checkNotInstanceOf(PagingPredicate.class, predicate, "Paging is not supported for Transactional queries!"); MapQueryEngine queryEngine = mapServiceContext.getMapQueryEngine(name); SerializationService serializationService = getNodeEngine().getSerializationService(); QueryResult result = queryEngine.invokeQueryAllPartitions(name, predicate, IterationType.KEY); Set<Object> queryResult = new QueryResultCollection(serializationService, IterationType.KEY, false, true, result); // TODO: Can't we just use the original set? Set<Object> keySet = new HashSet<Object>(queryResult); Extractors extractors = mapServiceContext.getExtractors(name); for (Map.Entry<Data, TxnValueWrapper> entry : txMap.entrySet()) { Data keyData = entry.getKey(); if (!Type.REMOVED.equals(entry.getValue().type)) { Object value = (entry.getValue().value instanceof Data) ? toObjectIfNeeded(entry.getValue().value) : entry.getValue().value; QueryableEntry queryEntry = new CachedQueryEntry((InternalSerializationService) serializationService, keyData, value, extractors); // apply predicate on txMap if (predicate.apply(queryEntry)) { Object keyObject = serializationService.toObject(keyData); keySet.add(keyObject); } } else { // meanwhile remove keys which are not in txMap Object keyObject = serializationService.toObject(keyData); keySet.remove(keyObject); } } return keySet; }
NONSATD
true
QueryableEntry queryEntry = new CachedQueryEntry((InternalSerializationService) serializationService, keyData, value, extractors); // apply predicate on txMap if (predicate.apply(queryEntry)) { Object keyObject = serializationService.toObject(keyData);
// TODO: Can't we just use the original set? Set<Object> keySet = new HashSet<Object>(queryResult); Extractors extractors = mapServiceContext.getExtractors(name); for (Map.Entry<Data, TxnValueWrapper> entry : txMap.entrySet()) { Data keyData = entry.getKey(); if (!Type.REMOVED.equals(entry.getValue().type)) { Object value = (entry.getValue().value instanceof Data) ? toObjectIfNeeded(entry.getValue().value) : entry.getValue().value; QueryableEntry queryEntry = new CachedQueryEntry((InternalSerializationService) serializationService, keyData, value, extractors); // apply predicate on txMap if (predicate.apply(queryEntry)) { Object keyObject = serializationService.toObject(keyData); keySet.add(keyObject); } } else { // meanwhile remove keys which are not in txMap Object keyObject = serializationService.toObject(keyData); keySet.remove(keyObject); } }
@Override @SuppressWarnings("unchecked") public Set keySet(Predicate predicate) { checkTransactionState(); checkNotNull(predicate, "Predicate should not be null!"); checkNotInstanceOf(PagingPredicate.class, predicate, "Paging is not supported for Transactional queries!"); MapQueryEngine queryEngine = mapServiceContext.getMapQueryEngine(name); SerializationService serializationService = getNodeEngine().getSerializationService(); QueryResult result = queryEngine.invokeQueryAllPartitions(name, predicate, IterationType.KEY); Set<Object> queryResult = new QueryResultCollection(serializationService, IterationType.KEY, false, true, result); // TODO: Can't we just use the original set? Set<Object> keySet = new HashSet<Object>(queryResult); Extractors extractors = mapServiceContext.getExtractors(name); for (Map.Entry<Data, TxnValueWrapper> entry : txMap.entrySet()) { Data keyData = entry.getKey(); if (!Type.REMOVED.equals(entry.getValue().type)) { Object value = (entry.getValue().value instanceof Data) ? toObjectIfNeeded(entry.getValue().value) : entry.getValue().value; QueryableEntry queryEntry = new CachedQueryEntry((InternalSerializationService) serializationService, keyData, value, extractors); // apply predicate on txMap if (predicate.apply(queryEntry)) { Object keyObject = serializationService.toObject(keyData); keySet.add(keyObject); } } else { // meanwhile remove keys which are not in txMap Object keyObject = serializationService.toObject(keyData); keySet.remove(keyObject); } } return keySet; }
17,001
2
// meanwhile remove keys which are not in txMap
@Override @SuppressWarnings("unchecked") public Set keySet(Predicate predicate) { checkTransactionState(); checkNotNull(predicate, "Predicate should not be null!"); checkNotInstanceOf(PagingPredicate.class, predicate, "Paging is not supported for Transactional queries!"); MapQueryEngine queryEngine = mapServiceContext.getMapQueryEngine(name); SerializationService serializationService = getNodeEngine().getSerializationService(); QueryResult result = queryEngine.invokeQueryAllPartitions(name, predicate, IterationType.KEY); Set<Object> queryResult = new QueryResultCollection(serializationService, IterationType.KEY, false, true, result); // TODO: Can't we just use the original set? Set<Object> keySet = new HashSet<Object>(queryResult); Extractors extractors = mapServiceContext.getExtractors(name); for (Map.Entry<Data, TxnValueWrapper> entry : txMap.entrySet()) { Data keyData = entry.getKey(); if (!Type.REMOVED.equals(entry.getValue().type)) { Object value = (entry.getValue().value instanceof Data) ? toObjectIfNeeded(entry.getValue().value) : entry.getValue().value; QueryableEntry queryEntry = new CachedQueryEntry((InternalSerializationService) serializationService, keyData, value, extractors); // apply predicate on txMap if (predicate.apply(queryEntry)) { Object keyObject = serializationService.toObject(keyData); keySet.add(keyObject); } } else { // meanwhile remove keys which are not in txMap Object keyObject = serializationService.toObject(keyData); keySet.remove(keyObject); } } return keySet; }
NONSATD
true
} } else { // meanwhile remove keys which are not in txMap Object keyObject = serializationService.toObject(keyData); keySet.remove(keyObject);
Object value = (entry.getValue().value instanceof Data) ? toObjectIfNeeded(entry.getValue().value) : entry.getValue().value; QueryableEntry queryEntry = new CachedQueryEntry((InternalSerializationService) serializationService, keyData, value, extractors); // apply predicate on txMap if (predicate.apply(queryEntry)) { Object keyObject = serializationService.toObject(keyData); keySet.add(keyObject); } } else { // meanwhile remove keys which are not in txMap Object keyObject = serializationService.toObject(keyData); keySet.remove(keyObject); } } return keySet; }
MapQueryEngine queryEngine = mapServiceContext.getMapQueryEngine(name); SerializationService serializationService = getNodeEngine().getSerializationService(); QueryResult result = queryEngine.invokeQueryAllPartitions(name, predicate, IterationType.KEY); Set<Object> queryResult = new QueryResultCollection(serializationService, IterationType.KEY, false, true, result); // TODO: Can't we just use the original set? Set<Object> keySet = new HashSet<Object>(queryResult); Extractors extractors = mapServiceContext.getExtractors(name); for (Map.Entry<Data, TxnValueWrapper> entry : txMap.entrySet()) { Data keyData = entry.getKey(); if (!Type.REMOVED.equals(entry.getValue().type)) { Object value = (entry.getValue().value instanceof Data) ? toObjectIfNeeded(entry.getValue().value) : entry.getValue().value; QueryableEntry queryEntry = new CachedQueryEntry((InternalSerializationService) serializationService, keyData, value, extractors); // apply predicate on txMap if (predicate.apply(queryEntry)) { Object keyObject = serializationService.toObject(keyData); keySet.add(keyObject); } } else { // meanwhile remove keys which are not in txMap Object keyObject = serializationService.toObject(keyData); keySet.remove(keyObject); } } return keySet; }
17,002
0
// TODO: Can't we just use the original set?
@Override @SuppressWarnings("unchecked") public Collection values(Predicate predicate) { checkTransactionState(); checkNotNull(predicate, "Predicate can not be null!"); checkNotInstanceOf(PagingPredicate.class, predicate, "Paging is not supported for Transactional queries"); MapQueryEngine queryEngine = mapServiceContext.getMapQueryEngine(name); SerializationService serializationService = getNodeEngine().getSerializationService(); QueryResult result = queryEngine.invokeQueryAllPartitions(name, predicate, IterationType.ENTRY); QueryResultCollection<Map.Entry> queryResult = new QueryResultCollection<Map.Entry>(serializationService, IterationType.ENTRY, false, true, result); // TODO: Can't we just use the original set? List<Object> valueSet = new ArrayList<Object>(); Set<Object> keyWontBeIncluded = new HashSet<Object>(); Extractors extractors = mapServiceContext.getExtractors(name); // iterate over the txMap and see if the values are updated or removed for (Map.Entry<Data, TxnValueWrapper> entry : txMap.entrySet()) { boolean isRemoved = Type.REMOVED.equals(entry.getValue().type); boolean isUpdated = Type.UPDATED.equals(entry.getValue().type); Object keyObject = serializationService.toObject(entry.getKey()); if (isRemoved) { keyWontBeIncluded.add(keyObject); } else { if (isUpdated) { keyWontBeIncluded.add(keyObject); } Object entryValue = entry.getValue().value; QueryableEntry queryEntry = new CachedQueryEntry((InternalSerializationService) serializationService, entry.getKey(), entryValue, extractors); if (predicate.apply(queryEntry)) { valueSet.add(queryEntry.getValue()); } } } removeFromResultSet(queryResult, valueSet, keyWontBeIncluded); return valueSet; }
DESIGN
true
QueryResultCollection<Map.Entry> queryResult = new QueryResultCollection<Map.Entry>(serializationService, IterationType.ENTRY, false, true, result); // TODO: Can't we just use the original set? List<Object> valueSet = new ArrayList<Object>(); Set<Object> keyWontBeIncluded = new HashSet<Object>();
@SuppressWarnings("unchecked") public Collection values(Predicate predicate) { checkTransactionState(); checkNotNull(predicate, "Predicate can not be null!"); checkNotInstanceOf(PagingPredicate.class, predicate, "Paging is not supported for Transactional queries"); MapQueryEngine queryEngine = mapServiceContext.getMapQueryEngine(name); SerializationService serializationService = getNodeEngine().getSerializationService(); QueryResult result = queryEngine.invokeQueryAllPartitions(name, predicate, IterationType.ENTRY); QueryResultCollection<Map.Entry> queryResult = new QueryResultCollection<Map.Entry>(serializationService, IterationType.ENTRY, false, true, result); // TODO: Can't we just use the original set? List<Object> valueSet = new ArrayList<Object>(); Set<Object> keyWontBeIncluded = new HashSet<Object>(); Extractors extractors = mapServiceContext.getExtractors(name); // iterate over the txMap and see if the values are updated or removed for (Map.Entry<Data, TxnValueWrapper> entry : txMap.entrySet()) { boolean isRemoved = Type.REMOVED.equals(entry.getValue().type); boolean isUpdated = Type.UPDATED.equals(entry.getValue().type); Object keyObject = serializationService.toObject(entry.getKey()); if (isRemoved) { keyWontBeIncluded.add(keyObject);
@Override @SuppressWarnings("unchecked") public Collection values(Predicate predicate) { checkTransactionState(); checkNotNull(predicate, "Predicate can not be null!"); checkNotInstanceOf(PagingPredicate.class, predicate, "Paging is not supported for Transactional queries"); MapQueryEngine queryEngine = mapServiceContext.getMapQueryEngine(name); SerializationService serializationService = getNodeEngine().getSerializationService(); QueryResult result = queryEngine.invokeQueryAllPartitions(name, predicate, IterationType.ENTRY); QueryResultCollection<Map.Entry> queryResult = new QueryResultCollection<Map.Entry>(serializationService, IterationType.ENTRY, false, true, result); // TODO: Can't we just use the original set? List<Object> valueSet = new ArrayList<Object>(); Set<Object> keyWontBeIncluded = new HashSet<Object>(); Extractors extractors = mapServiceContext.getExtractors(name); // iterate over the txMap and see if the values are updated or removed for (Map.Entry<Data, TxnValueWrapper> entry : txMap.entrySet()) { boolean isRemoved = Type.REMOVED.equals(entry.getValue().type); boolean isUpdated = Type.UPDATED.equals(entry.getValue().type); Object keyObject = serializationService.toObject(entry.getKey()); if (isRemoved) { keyWontBeIncluded.add(keyObject); } else { if (isUpdated) { keyWontBeIncluded.add(keyObject); } Object entryValue = entry.getValue().value; QueryableEntry queryEntry = new CachedQueryEntry((InternalSerializationService) serializationService, entry.getKey(), entryValue, extractors); if (predicate.apply(queryEntry)) { valueSet.add(queryEntry.getValue()); }
17,002
1
// iterate over the txMap and see if the values are updated or removed
@Override @SuppressWarnings("unchecked") public Collection values(Predicate predicate) { checkTransactionState(); checkNotNull(predicate, "Predicate can not be null!"); checkNotInstanceOf(PagingPredicate.class, predicate, "Paging is not supported for Transactional queries"); MapQueryEngine queryEngine = mapServiceContext.getMapQueryEngine(name); SerializationService serializationService = getNodeEngine().getSerializationService(); QueryResult result = queryEngine.invokeQueryAllPartitions(name, predicate, IterationType.ENTRY); QueryResultCollection<Map.Entry> queryResult = new QueryResultCollection<Map.Entry>(serializationService, IterationType.ENTRY, false, true, result); // TODO: Can't we just use the original set? List<Object> valueSet = new ArrayList<Object>(); Set<Object> keyWontBeIncluded = new HashSet<Object>(); Extractors extractors = mapServiceContext.getExtractors(name); // iterate over the txMap and see if the values are updated or removed for (Map.Entry<Data, TxnValueWrapper> entry : txMap.entrySet()) { boolean isRemoved = Type.REMOVED.equals(entry.getValue().type); boolean isUpdated = Type.UPDATED.equals(entry.getValue().type); Object keyObject = serializationService.toObject(entry.getKey()); if (isRemoved) { keyWontBeIncluded.add(keyObject); } else { if (isUpdated) { keyWontBeIncluded.add(keyObject); } Object entryValue = entry.getValue().value; QueryableEntry queryEntry = new CachedQueryEntry((InternalSerializationService) serializationService, entry.getKey(), entryValue, extractors); if (predicate.apply(queryEntry)) { valueSet.add(queryEntry.getValue()); } } } removeFromResultSet(queryResult, valueSet, keyWontBeIncluded); return valueSet; }
NONSATD
true
Set<Object> keyWontBeIncluded = new HashSet<Object>(); Extractors extractors = mapServiceContext.getExtractors(name); // iterate over the txMap and see if the values are updated or removed for (Map.Entry<Data, TxnValueWrapper> entry : txMap.entrySet()) { boolean isRemoved = Type.REMOVED.equals(entry.getValue().type);
checkNotInstanceOf(PagingPredicate.class, predicate, "Paging is not supported for Transactional queries"); MapQueryEngine queryEngine = mapServiceContext.getMapQueryEngine(name); SerializationService serializationService = getNodeEngine().getSerializationService(); QueryResult result = queryEngine.invokeQueryAllPartitions(name, predicate, IterationType.ENTRY); QueryResultCollection<Map.Entry> queryResult = new QueryResultCollection<Map.Entry>(serializationService, IterationType.ENTRY, false, true, result); // TODO: Can't we just use the original set? List<Object> valueSet = new ArrayList<Object>(); Set<Object> keyWontBeIncluded = new HashSet<Object>(); Extractors extractors = mapServiceContext.getExtractors(name); // iterate over the txMap and see if the values are updated or removed for (Map.Entry<Data, TxnValueWrapper> entry : txMap.entrySet()) { boolean isRemoved = Type.REMOVED.equals(entry.getValue().type); boolean isUpdated = Type.UPDATED.equals(entry.getValue().type); Object keyObject = serializationService.toObject(entry.getKey()); if (isRemoved) { keyWontBeIncluded.add(keyObject); } else { if (isUpdated) { keyWontBeIncluded.add(keyObject); }
@Override @SuppressWarnings("unchecked") public Collection values(Predicate predicate) { checkTransactionState(); checkNotNull(predicate, "Predicate can not be null!"); checkNotInstanceOf(PagingPredicate.class, predicate, "Paging is not supported for Transactional queries"); MapQueryEngine queryEngine = mapServiceContext.getMapQueryEngine(name); SerializationService serializationService = getNodeEngine().getSerializationService(); QueryResult result = queryEngine.invokeQueryAllPartitions(name, predicate, IterationType.ENTRY); QueryResultCollection<Map.Entry> queryResult = new QueryResultCollection<Map.Entry>(serializationService, IterationType.ENTRY, false, true, result); // TODO: Can't we just use the original set? List<Object> valueSet = new ArrayList<Object>(); Set<Object> keyWontBeIncluded = new HashSet<Object>(); Extractors extractors = mapServiceContext.getExtractors(name); // iterate over the txMap and see if the values are updated or removed for (Map.Entry<Data, TxnValueWrapper> entry : txMap.entrySet()) { boolean isRemoved = Type.REMOVED.equals(entry.getValue().type); boolean isUpdated = Type.UPDATED.equals(entry.getValue().type); Object keyObject = serializationService.toObject(entry.getKey()); if (isRemoved) { keyWontBeIncluded.add(keyObject); } else { if (isUpdated) { keyWontBeIncluded.add(keyObject); } Object entryValue = entry.getValue().value; QueryableEntry queryEntry = new CachedQueryEntry((InternalSerializationService) serializationService, entry.getKey(), entryValue, extractors); if (predicate.apply(queryEntry)) { valueSet.add(queryEntry.getValue()); } } } removeFromResultSet(queryResult, valueSet, keyWontBeIncluded); return valueSet;
636
0
//endregion //region > Facet Handling
@Override public <Q extends Facet> Q getFacet(final Class<Q> facetType) { final Q facet = super.getFacet(facetType); Q noopFacet = null; if (isNotANoopFacet(facet)) { return facet; } else { noopFacet = facet; } if (interfaces() != null) { final List<ObjectSpecification> interfaces = interfaces(); for (int i = 0; i < interfaces.size(); i++) { final ObjectSpecification interfaceSpec = interfaces.get(i); if (interfaceSpec == null) { // HACK: shouldn't happen, but occurring on occasion when // running // XATs under JUnit4. Some sort of race condition? continue; } final Q interfaceFacet = interfaceSpec.getFacet(facetType); if (isNotANoopFacet(interfaceFacet)) { return interfaceFacet; } else { if (noopFacet == null) { noopFacet = interfaceFacet; } } } } // search up the inheritance hierarchy final ObjectSpecification superSpec = superclass(); if (superSpec != null) { final Q superClassFacet = superSpec.getFacet(facetType); if (isNotANoopFacet(superClassFacet)) { return superClassFacet; } } return noopFacet; }
NONSATD
true
@Override public <Q extends Facet> Q getFacet(final Class<Q> facetType) { final Q facet = super.getFacet(facetType); Q noopFacet = null; if (isNotANoopFacet(facet)) { return facet; } else { noopFacet = facet; } if (interfaces() != null) { final List<ObjectSpecification> interfaces = interfaces(); for (int i = 0; i < interfaces.size(); i++) { final ObjectSpecification interfaceSpec = interfaces.get(i); if (interfaceSpec == null) { // HACK: shouldn't happen, but occurring on occasion when // running // XATs under JUnit4. Some sort of race condition? continue; } final Q interfaceFacet = interfaceSpec.getFacet(facetType); if (isNotANoopFacet(interfaceFacet)) { return interfaceFacet; } else { if (noopFacet == null) { noopFacet = interfaceFacet; } } } } // search up the inheritance hierarchy final ObjectSpecification superSpec = superclass(); if (superSpec != null) { final Q superClassFacet = superSpec.getFacet(facetType); if (isNotANoopFacet(superClassFacet)) { return superClassFacet; } } return noopFacet; }
@Override public <Q extends Facet> Q getFacet(final Class<Q> facetType) { final Q facet = super.getFacet(facetType); Q noopFacet = null; if (isNotANoopFacet(facet)) { return facet; } else { noopFacet = facet; } if (interfaces() != null) { final List<ObjectSpecification> interfaces = interfaces(); for (int i = 0; i < interfaces.size(); i++) { final ObjectSpecification interfaceSpec = interfaces.get(i); if (interfaceSpec == null) { // HACK: shouldn't happen, but occurring on occasion when // running // XATs under JUnit4. Some sort of race condition? continue; } final Q interfaceFacet = interfaceSpec.getFacet(facetType); if (isNotANoopFacet(interfaceFacet)) { return interfaceFacet; } else { if (noopFacet == null) { noopFacet = interfaceFacet; } } } } // search up the inheritance hierarchy final ObjectSpecification superSpec = superclass(); if (superSpec != null) { final Q superClassFacet = superSpec.getFacet(facetType); if (isNotANoopFacet(superClassFacet)) { return superClassFacet; } } return noopFacet; }
@Override public <Q extends Facet> Q getFacet(final Class<Q> facetType) { final Q facet = super.getFacet(facetType); Q noopFacet = null; if (isNotANoopFacet(facet)) { return facet; } else { noopFacet = facet; } if (interfaces() != null) { final List<ObjectSpecification> interfaces = interfaces(); for (int i = 0; i < interfaces.size(); i++) { final ObjectSpecification interfaceSpec = interfaces.get(i); if (interfaceSpec == null) { // HACK: shouldn't happen, but occurring on occasion when // running // XATs under JUnit4. Some sort of race condition? continue; } final Q interfaceFacet = interfaceSpec.getFacet(facetType); if (isNotANoopFacet(interfaceFacet)) { return interfaceFacet; } else { if (noopFacet == null) { noopFacet = interfaceFacet; } } } } // search up the inheritance hierarchy final ObjectSpecification superSpec = superclass(); if (superSpec != null) { final Q superClassFacet = superSpec.getFacet(facetType); if (isNotANoopFacet(superClassFacet)) { return superClassFacet; } } return noopFacet; }
636
1
// HACK: shouldn't happen, but occurring on occasion when // running // XATs under JUnit4. Some sort of race condition?
@Override public <Q extends Facet> Q getFacet(final Class<Q> facetType) { final Q facet = super.getFacet(facetType); Q noopFacet = null; if (isNotANoopFacet(facet)) { return facet; } else { noopFacet = facet; } if (interfaces() != null) { final List<ObjectSpecification> interfaces = interfaces(); for (int i = 0; i < interfaces.size(); i++) { final ObjectSpecification interfaceSpec = interfaces.get(i); if (interfaceSpec == null) { // HACK: shouldn't happen, but occurring on occasion when // running // XATs under JUnit4. Some sort of race condition? continue; } final Q interfaceFacet = interfaceSpec.getFacet(facetType); if (isNotANoopFacet(interfaceFacet)) { return interfaceFacet; } else { if (noopFacet == null) { noopFacet = interfaceFacet; } } } } // search up the inheritance hierarchy final ObjectSpecification superSpec = superclass(); if (superSpec != null) { final Q superClassFacet = superSpec.getFacet(facetType); if (isNotANoopFacet(superClassFacet)) { return superClassFacet; } } return noopFacet; }
DESIGN
true
final ObjectSpecification interfaceSpec = interfaces.get(i); if (interfaceSpec == null) { // HACK: shouldn't happen, but occurring on occasion when // running // XATs under JUnit4. Some sort of race condition? continue; }
if (isNotANoopFacet(facet)) { return facet; } else { noopFacet = facet; } if (interfaces() != null) { final List<ObjectSpecification> interfaces = interfaces(); for (int i = 0; i < interfaces.size(); i++) { final ObjectSpecification interfaceSpec = interfaces.get(i); if (interfaceSpec == null) { // HACK: shouldn't happen, but occurring on occasion when // running // XATs under JUnit4. Some sort of race condition? continue; } final Q interfaceFacet = interfaceSpec.getFacet(facetType); if (isNotANoopFacet(interfaceFacet)) { return interfaceFacet; } else { if (noopFacet == null) { noopFacet = interfaceFacet; } }
@Override public <Q extends Facet> Q getFacet(final Class<Q> facetType) { final Q facet = super.getFacet(facetType); Q noopFacet = null; if (isNotANoopFacet(facet)) { return facet; } else { noopFacet = facet; } if (interfaces() != null) { final List<ObjectSpecification> interfaces = interfaces(); for (int i = 0; i < interfaces.size(); i++) { final ObjectSpecification interfaceSpec = interfaces.get(i); if (interfaceSpec == null) { // HACK: shouldn't happen, but occurring on occasion when // running // XATs under JUnit4. Some sort of race condition? continue; } final Q interfaceFacet = interfaceSpec.getFacet(facetType); if (isNotANoopFacet(interfaceFacet)) { return interfaceFacet; } else { if (noopFacet == null) { noopFacet = interfaceFacet; } } } } // search up the inheritance hierarchy final ObjectSpecification superSpec = superclass(); if (superSpec != null) { final Q superClassFacet = superSpec.getFacet(facetType); if (isNotANoopFacet(superClassFacet)) { return superClassFacet; } }
636
2
// search up the inheritance hierarchy
@Override public <Q extends Facet> Q getFacet(final Class<Q> facetType) { final Q facet = super.getFacet(facetType); Q noopFacet = null; if (isNotANoopFacet(facet)) { return facet; } else { noopFacet = facet; } if (interfaces() != null) { final List<ObjectSpecification> interfaces = interfaces(); for (int i = 0; i < interfaces.size(); i++) { final ObjectSpecification interfaceSpec = interfaces.get(i); if (interfaceSpec == null) { // HACK: shouldn't happen, but occurring on occasion when // running // XATs under JUnit4. Some sort of race condition? continue; } final Q interfaceFacet = interfaceSpec.getFacet(facetType); if (isNotANoopFacet(interfaceFacet)) { return interfaceFacet; } else { if (noopFacet == null) { noopFacet = interfaceFacet; } } } } // search up the inheritance hierarchy final ObjectSpecification superSpec = superclass(); if (superSpec != null) { final Q superClassFacet = superSpec.getFacet(facetType); if (isNotANoopFacet(superClassFacet)) { return superClassFacet; } } return noopFacet; }
NONSATD
true
} } // search up the inheritance hierarchy final ObjectSpecification superSpec = superclass(); if (superSpec != null) {
final Q interfaceFacet = interfaceSpec.getFacet(facetType); if (isNotANoopFacet(interfaceFacet)) { return interfaceFacet; } else { if (noopFacet == null) { noopFacet = interfaceFacet; } } } } // search up the inheritance hierarchy final ObjectSpecification superSpec = superclass(); if (superSpec != null) { final Q superClassFacet = superSpec.getFacet(facetType); if (isNotANoopFacet(superClassFacet)) { return superClassFacet; } } return noopFacet; }
if (interfaces() != null) { final List<ObjectSpecification> interfaces = interfaces(); for (int i = 0; i < interfaces.size(); i++) { final ObjectSpecification interfaceSpec = interfaces.get(i); if (interfaceSpec == null) { // HACK: shouldn't happen, but occurring on occasion when // running // XATs under JUnit4. Some sort of race condition? continue; } final Q interfaceFacet = interfaceSpec.getFacet(facetType); if (isNotANoopFacet(interfaceFacet)) { return interfaceFacet; } else { if (noopFacet == null) { noopFacet = interfaceFacet; } } } } // search up the inheritance hierarchy final ObjectSpecification superSpec = superclass(); if (superSpec != null) { final Q superClassFacet = superSpec.getFacet(facetType); if (isNotANoopFacet(superClassFacet)) { return superClassFacet; } } return noopFacet; }
17,020
0
// TODO: Remove these probing methods, and test through mocked ScriptingContainerDelegate.
String probeGemHomeForTesting() { return this.gemHome; }
IMPLEMENTATION
true
String probeGemHomeForTesting() { return this.gemHome; }
String probeGemHomeForTesting() { return this.gemHome; }
String probeGemHomeForTesting() { return this.gemHome; }
643
0
// ----------------------------------------------------------------------------
protected void blast(T message) { logger.debug("blast called for message: " + message); Map<String,Object> filter = KStringUtil.toMap(message.getFilter()); Long affinityAppId = null; Map<String, Object> data = createPayLoadData(message); List<D> deviceList = getDeviceList(filter, affinityAppId, message.isSandbox()); int sendCount = 0; List<String> blastErrors = new ArrayList<String>(); List<String> deviceIdList = new ArrayList<String>(); for (D device : deviceList) { logger.debug("blast push device: " + device); KPushService.Platform platform = getPushService().getPushPlatform(device.getPlatformName(), device.isSandbox()); String endpoint = device.getPushEndpoint(); if (platform == null || endpoint == null) { continue; } try { getPushService().publish(platform, endpoint, message.getMessage(), data); logger.debug("\n--------------------------\n" + "\npush message:" + "\nplatform: " + platform + "\nendpoint: " + endpoint + "\nmessage: " + message + "\ndata: " + data + "\n--------------------------\n" ); sendCount += 1; deviceIdList.add(device.getId().toString()); } catch (Exception e) { blastErrors.add(e.getMessage()); } } logger.debug("blast: updating sendCount: " + sendCount); if (blastErrors.size() > 0) { logger.warn("Broadcast blast errors" + KStringUtil.join(blastErrors, "\n\n")); } message.setDeviceCount(sendCount); // FIXME: this won't save since it's a blob type and underlying framework needs to support it message.setDevices(KStringUtil.join(deviceIdList,",").getBytes()); update(message); }
NONSATD
true
protected void blast(T message) { logger.debug("blast called for message: " + message); Map<String,Object> filter = KStringUtil.toMap(message.getFilter()); Long affinityAppId = null; Map<String, Object> data = createPayLoadData(message); List<D> deviceList = getDeviceList(filter, affinityAppId, message.isSandbox()); int sendCount = 0; List<String> blastErrors = new ArrayList<String>(); List<String> deviceIdList = new ArrayList<String>(); for (D device : deviceList) { logger.debug("blast push device: " + device); KPushService.Platform platform = getPushService().getPushPlatform(device.getPlatformName(), device.isSandbox()); String endpoint = device.getPushEndpoint(); if (platform == null || endpoint == null) { continue; } try { getPushService().publish(platform, endpoint, message.getMessage(), data); logger.debug("\n--------------------------\n" + "\npush message:" + "\nplatform: " + platform + "\nendpoint: " + endpoint + "\nmessage: " + message + "\ndata: " + data + "\n--------------------------\n" ); sendCount += 1; deviceIdList.add(device.getId().toString()); } catch (Exception e) { blastErrors.add(e.getMessage()); } } logger.debug("blast: updating sendCount: " + sendCount); if (blastErrors.size() > 0) { logger.warn("Broadcast blast errors" + KStringUtil.join(blastErrors, "\n\n")); } message.setDeviceCount(sendCount); // FIXME: this won't save since it's a blob type and underlying framework needs to support it message.setDevices(KStringUtil.join(deviceIdList,",").getBytes()); update(message); }
protected void blast(T message) { logger.debug("blast called for message: " + message); Map<String,Object> filter = KStringUtil.toMap(message.getFilter()); Long affinityAppId = null; Map<String, Object> data = createPayLoadData(message); List<D> deviceList = getDeviceList(filter, affinityAppId, message.isSandbox()); int sendCount = 0; List<String> blastErrors = new ArrayList<String>(); List<String> deviceIdList = new ArrayList<String>(); for (D device : deviceList) { logger.debug("blast push device: " + device); KPushService.Platform platform = getPushService().getPushPlatform(device.getPlatformName(), device.isSandbox()); String endpoint = device.getPushEndpoint(); if (platform == null || endpoint == null) { continue; } try { getPushService().publish(platform, endpoint, message.getMessage(), data); logger.debug("\n--------------------------\n" + "\npush message:" + "\nplatform: " + platform + "\nendpoint: " + endpoint + "\nmessage: " + message + "\ndata: " + data + "\n--------------------------\n" ); sendCount += 1; deviceIdList.add(device.getId().toString()); } catch (Exception e) { blastErrors.add(e.getMessage()); } } logger.debug("blast: updating sendCount: " + sendCount); if (blastErrors.size() > 0) { logger.warn("Broadcast blast errors" + KStringUtil.join(blastErrors, "\n\n")); } message.setDeviceCount(sendCount); // FIXME: this won't save since it's a blob type and underlying framework needs to support it message.setDevices(KStringUtil.join(deviceIdList,",").getBytes()); update(message); }
protected void blast(T message) { logger.debug("blast called for message: " + message); Map<String,Object> filter = KStringUtil.toMap(message.getFilter()); Long affinityAppId = null; Map<String, Object> data = createPayLoadData(message); List<D> deviceList = getDeviceList(filter, affinityAppId, message.isSandbox()); int sendCount = 0; List<String> blastErrors = new ArrayList<String>(); List<String> deviceIdList = new ArrayList<String>(); for (D device : deviceList) { logger.debug("blast push device: " + device); KPushService.Platform platform = getPushService().getPushPlatform(device.getPlatformName(), device.isSandbox()); String endpoint = device.getPushEndpoint(); if (platform == null || endpoint == null) { continue; } try { getPushService().publish(platform, endpoint, message.getMessage(), data); logger.debug("\n--------------------------\n" + "\npush message:" + "\nplatform: " + platform + "\nendpoint: " + endpoint + "\nmessage: " + message + "\ndata: " + data + "\n--------------------------\n" ); sendCount += 1; deviceIdList.add(device.getId().toString()); } catch (Exception e) { blastErrors.add(e.getMessage()); } } logger.debug("blast: updating sendCount: " + sendCount); if (blastErrors.size() > 0) { logger.warn("Broadcast blast errors" + KStringUtil.join(blastErrors, "\n\n")); } message.setDeviceCount(sendCount); // FIXME: this won't save since it's a blob type and underlying framework needs to support it message.setDevices(KStringUtil.join(deviceIdList,",").getBytes()); update(message); }
643
1
// FIXME: this won't save since it's a blob type and underlying framework needs to support it
protected void blast(T message) { logger.debug("blast called for message: " + message); Map<String,Object> filter = KStringUtil.toMap(message.getFilter()); Long affinityAppId = null; Map<String, Object> data = createPayLoadData(message); List<D> deviceList = getDeviceList(filter, affinityAppId, message.isSandbox()); int sendCount = 0; List<String> blastErrors = new ArrayList<String>(); List<String> deviceIdList = new ArrayList<String>(); for (D device : deviceList) { logger.debug("blast push device: " + device); KPushService.Platform platform = getPushService().getPushPlatform(device.getPlatformName(), device.isSandbox()); String endpoint = device.getPushEndpoint(); if (platform == null || endpoint == null) { continue; } try { getPushService().publish(platform, endpoint, message.getMessage(), data); logger.debug("\n--------------------------\n" + "\npush message:" + "\nplatform: " + platform + "\nendpoint: " + endpoint + "\nmessage: " + message + "\ndata: " + data + "\n--------------------------\n" ); sendCount += 1; deviceIdList.add(device.getId().toString()); } catch (Exception e) { blastErrors.add(e.getMessage()); } } logger.debug("blast: updating sendCount: " + sendCount); if (blastErrors.size() > 0) { logger.warn("Broadcast blast errors" + KStringUtil.join(blastErrors, "\n\n")); } message.setDeviceCount(sendCount); // FIXME: this won't save since it's a blob type and underlying framework needs to support it message.setDevices(KStringUtil.join(deviceIdList,",").getBytes()); update(message); }
DEFECT
true
} message.setDeviceCount(sendCount); // FIXME: this won't save since it's a blob type and underlying framework needs to support it message.setDevices(KStringUtil.join(deviceIdList,",").getBytes()); update(message);
deviceIdList.add(device.getId().toString()); } catch (Exception e) { blastErrors.add(e.getMessage()); } } logger.debug("blast: updating sendCount: " + sendCount); if (blastErrors.size() > 0) { logger.warn("Broadcast blast errors" + KStringUtil.join(blastErrors, "\n\n")); } message.setDeviceCount(sendCount); // FIXME: this won't save since it's a blob type and underlying framework needs to support it message.setDevices(KStringUtil.join(deviceIdList,",").getBytes()); update(message); }
getPushService().publish(platform, endpoint, message.getMessage(), data); logger.debug("\n--------------------------\n" + "\npush message:" + "\nplatform: " + platform + "\nendpoint: " + endpoint + "\nmessage: " + message + "\ndata: " + data + "\n--------------------------\n" ); sendCount += 1; deviceIdList.add(device.getId().toString()); } catch (Exception e) { blastErrors.add(e.getMessage()); } } logger.debug("blast: updating sendCount: " + sendCount); if (blastErrors.size() > 0) { logger.warn("Broadcast blast errors" + KStringUtil.join(blastErrors, "\n\n")); } message.setDeviceCount(sendCount); // FIXME: this won't save since it's a blob type and underlying framework needs to support it message.setDevices(KStringUtil.join(deviceIdList,",").getBytes()); update(message); }
25,223
0
/** * Returns the join of the two specified nodes if it exists. * * @param x the first node * @param y the second node * * @return the node which is at the join of the nodes or null if it does not * exist * * @todo this.majorants should return an iterator */
public Node<N> join(Node<N> x, Node<N> y) { // TODO this.majorants should return an iterator SortedSet<Node<N>> xMajorants = new TreeSet<Node<N>>(this.majorants(x)); xMajorants.add(x); SortedSet<Node<N>> yMajorants = new TreeSet<Node<N>>(this.majorants(y)); yMajorants.add(y); xMajorants.retainAll(yMajorants); DAGraph<N, E> graph = this.getSubgraphByNodes(xMajorants); TreeSet<Node> join = new TreeSet<Node>(graph.min()); if (join.size() == 1) { return join.first(); } return null; }
NONSATD
true
public Node<N> join(Node<N> x, Node<N> y) { // TODO this.majorants should return an iterator SortedSet<Node<N>> xMajorants = new TreeSet<Node<N>>(this.majorants(x)); xMajorants.add(x); SortedSet<Node<N>> yMajorants = new TreeSet<Node<N>>(this.majorants(y)); yMajorants.add(y); xMajorants.retainAll(yMajorants); DAGraph<N, E> graph = this.getSubgraphByNodes(xMajorants); TreeSet<Node> join = new TreeSet<Node>(graph.min()); if (join.size() == 1) { return join.first(); } return null; }
public Node<N> join(Node<N> x, Node<N> y) { // TODO this.majorants should return an iterator SortedSet<Node<N>> xMajorants = new TreeSet<Node<N>>(this.majorants(x)); xMajorants.add(x); SortedSet<Node<N>> yMajorants = new TreeSet<Node<N>>(this.majorants(y)); yMajorants.add(y); xMajorants.retainAll(yMajorants); DAGraph<N, E> graph = this.getSubgraphByNodes(xMajorants); TreeSet<Node> join = new TreeSet<Node>(graph.min()); if (join.size() == 1) { return join.first(); } return null; }
public Node<N> join(Node<N> x, Node<N> y) { // TODO this.majorants should return an iterator SortedSet<Node<N>> xMajorants = new TreeSet<Node<N>>(this.majorants(x)); xMajorants.add(x); SortedSet<Node<N>> yMajorants = new TreeSet<Node<N>>(this.majorants(y)); yMajorants.add(y); xMajorants.retainAll(yMajorants); DAGraph<N, E> graph = this.getSubgraphByNodes(xMajorants); TreeSet<Node> join = new TreeSet<Node>(graph.min()); if (join.size() == 1) { return join.first(); } return null; }
25,223
1
// TODO this.majorants should return an iterator
public Node<N> join(Node<N> x, Node<N> y) { // TODO this.majorants should return an iterator SortedSet<Node<N>> xMajorants = new TreeSet<Node<N>>(this.majorants(x)); xMajorants.add(x); SortedSet<Node<N>> yMajorants = new TreeSet<Node<N>>(this.majorants(y)); yMajorants.add(y); xMajorants.retainAll(yMajorants); DAGraph<N, E> graph = this.getSubgraphByNodes(xMajorants); TreeSet<Node> join = new TreeSet<Node>(graph.min()); if (join.size() == 1) { return join.first(); } return null; }
DESIGN
true
public Node<N> join(Node<N> x, Node<N> y) { // TODO this.majorants should return an iterator SortedSet<Node<N>> xMajorants = new TreeSet<Node<N>>(this.majorants(x)); xMajorants.add(x);
public Node<N> join(Node<N> x, Node<N> y) { // TODO this.majorants should return an iterator SortedSet<Node<N>> xMajorants = new TreeSet<Node<N>>(this.majorants(x)); xMajorants.add(x); SortedSet<Node<N>> yMajorants = new TreeSet<Node<N>>(this.majorants(y)); yMajorants.add(y); xMajorants.retainAll(yMajorants); DAGraph<N, E> graph = this.getSubgraphByNodes(xMajorants); TreeSet<Node> join = new TreeSet<Node>(graph.min()); if (join.size() == 1) { return join.first(); }
public Node<N> join(Node<N> x, Node<N> y) { // TODO this.majorants should return an iterator SortedSet<Node<N>> xMajorants = new TreeSet<Node<N>>(this.majorants(x)); xMajorants.add(x); SortedSet<Node<N>> yMajorants = new TreeSet<Node<N>>(this.majorants(y)); yMajorants.add(y); xMajorants.retainAll(yMajorants); DAGraph<N, E> graph = this.getSubgraphByNodes(xMajorants); TreeSet<Node> join = new TreeSet<Node>(graph.min()); if (join.size() == 1) { return join.first(); } return null; }
8,840
0
/** * Reset YACC settings data so that tests can start at a clean slate. * This is sort of hackish... maybe the Atlassian integration test * API has a way to reset all the data? */
public static void resetData(BitbucketTestedProduct stash) { YaccRepoSettingsPage settingsPage = stash.visit(BitbucketLoginPage.class) .loginAsSysAdmin(YaccRepoSettingsPage.class); settingsPage.clickEditYacc() .clearSettings(); settingsPage.clickSubmit(); settingsPage.clickDisable(); YaccGlobalSettingsPage globalSettingsPage = stash.visit(YaccGlobalSettingsPage.class); globalSettingsPage.clearSettings(); globalSettingsPage.clickSubmit(); stash.getTester().getDriver().manage().deleteAllCookies(); }
DESIGN
true
public static void resetData(BitbucketTestedProduct stash) { YaccRepoSettingsPage settingsPage = stash.visit(BitbucketLoginPage.class) .loginAsSysAdmin(YaccRepoSettingsPage.class); settingsPage.clickEditYacc() .clearSettings(); settingsPage.clickSubmit(); settingsPage.clickDisable(); YaccGlobalSettingsPage globalSettingsPage = stash.visit(YaccGlobalSettingsPage.class); globalSettingsPage.clearSettings(); globalSettingsPage.clickSubmit(); stash.getTester().getDriver().manage().deleteAllCookies(); }
public static void resetData(BitbucketTestedProduct stash) { YaccRepoSettingsPage settingsPage = stash.visit(BitbucketLoginPage.class) .loginAsSysAdmin(YaccRepoSettingsPage.class); settingsPage.clickEditYacc() .clearSettings(); settingsPage.clickSubmit(); settingsPage.clickDisable(); YaccGlobalSettingsPage globalSettingsPage = stash.visit(YaccGlobalSettingsPage.class); globalSettingsPage.clearSettings(); globalSettingsPage.clickSubmit(); stash.getTester().getDriver().manage().deleteAllCookies(); }
public static void resetData(BitbucketTestedProduct stash) { YaccRepoSettingsPage settingsPage = stash.visit(BitbucketLoginPage.class) .loginAsSysAdmin(YaccRepoSettingsPage.class); settingsPage.clickEditYacc() .clearSettings(); settingsPage.clickSubmit(); settingsPage.clickDisable(); YaccGlobalSettingsPage globalSettingsPage = stash.visit(YaccGlobalSettingsPage.class); globalSettingsPage.clearSettings(); globalSettingsPage.clickSubmit(); stash.getTester().getDriver().manage().deleteAllCookies(); }
25,228
0
/** * Resets the statspecs to make them consistent for all tests in all * containers with the given test id. Uses a global override, if provided. */
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testId, testContainers); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test with the given test id for (Iterator i = testContainers.iterator(); i.hasNext();) { TestContainer testContainer = (TestContainer)i.next(); List tests = testContainer.getTestsWithId(testId); for (Iterator j = tests.iterator(); j.hasNext();) { Test test = (Test)j.next(); test.resetStatSpecs(statSpecFile); } } } }
NONSATD
true
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testId, testContainers); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test with the given test id for (Iterator i = testContainers.iterator(); i.hasNext();) { TestContainer testContainer = (TestContainer)i.next(); List tests = testContainer.getTestsWithId(testId); for (Iterator j = tests.iterator(); j.hasNext();) { Test test = (Test)j.next(); test.resetStatSpecs(statSpecFile); } } } }
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testId, testContainers); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test with the given test id for (Iterator i = testContainers.iterator(); i.hasNext();) { TestContainer testContainer = (TestContainer)i.next(); List tests = testContainer.getTestsWithId(testId); for (Iterator j = tests.iterator(); j.hasNext();) { Test test = (Test)j.next(); test.resetStatSpecs(statSpecFile); } } } }
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testId, testContainers); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test with the given test id for (Iterator i = testContainers.iterator(); i.hasNext();) { TestContainer testContainer = (TestContainer)i.next(); List tests = testContainer.getTestsWithId(testId); for (Iterator j = tests.iterator(); j.hasNext();) { Test test = (Test)j.next(); test.resetStatSpecs(statSpecFile); } } } }
25,228
1
// special case
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testId, testContainers); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test with the given test id for (Iterator i = testContainers.iterator(); i.hasNext();) { TestContainer testContainer = (TestContainer)i.next(); List tests = testContainer.getTestsWithId(testId); for (Iterator j = tests.iterator(); j.hasNext();) { Test test = (Test)j.next(); test.resetStatSpecs(statSpecFile); } } } }
NONSATD
true
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next();
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testId, testContainers); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test with the given test id for (Iterator i = testContainers.iterator(); i.hasNext();) {
25,228
2
// determine which statspec file to use
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testId, testContainers); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test with the given test id for (Iterator i = testContainers.iterator(); i.hasNext();) { TestContainer testContainer = (TestContainer)i.next(); List tests = testContainer.getTestsWithId(testId); for (Iterator j = tests.iterator(); j.hasNext();) { Test test = (Test)j.next(); test.resetStatSpecs(statSpecFile); } } } }
NONSATD
true
if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) {
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); }
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testId, testContainers); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test with the given test id for (Iterator i = testContainers.iterator(); i.hasNext();) { TestContainer testContainer = (TestContainer)i.next(); List tests = testContainer.getTestsWithId(testId);
25,228
3
// @todo lises support option to use union of all statspecs
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testId, testContainers); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test with the given test id for (Iterator i = testContainers.iterator(); i.hasNext();) { TestContainer testContainer = (TestContainer)i.next(); List tests = testContainer.getTestsWithId(testId); for (Iterator j = tests.iterator(); j.hasNext();) { Test test = (Test)j.next(); test.resetStatSpecs(statSpecFile); } } } }
IMPLEMENTATION
true
if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests();
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) {
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testId, testContainers); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test with the given test id for (Iterator i = testContainers.iterator(); i.hasNext();) { TestContainer testContainer = (TestContainer)i.next(); List tests = testContainer.getTestsWithId(testId); for (Iterator j = tests.iterator(); j.hasNext();) { Test test = (Test)j.next(); test.resetStatSpecs(statSpecFile); }
25,228
4
// reset the statspec file for each test in the container
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testId, testContainers); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test with the given test id for (Iterator i = testContainers.iterator(); i.hasNext();) { TestContainer testContainer = (TestContainer)i.next(); List tests = testContainer.getTestsWithId(testId); for (Iterator j = tests.iterator(); j.hasNext();) { Test test = (Test)j.next(); test.resetStatSpecs(statSpecFile); } } } }
NONSATD
true
statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) {
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testId, testContainers);
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testId, testContainers); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test with the given test id for (Iterator i = testContainers.iterator(); i.hasNext();) { TestContainer testContainer = (TestContainer)i.next(); List tests = testContainer.getTestsWithId(testId); for (Iterator j = tests.iterator(); j.hasNext();) { Test test = (Test)j.next(); test.resetStatSpecs(statSpecFile); } }
25,228
5
// determine which statspec file to use for this test id
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testId, testContainers); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test with the given test id for (Iterator i = testContainers.iterator(); i.hasNext();) { TestContainer testContainer = (TestContainer)i.next(); List tests = testContainer.getTestsWithId(testId); for (Iterator j = tests.iterator(); j.hasNext();) { Test test = (Test)j.next(); test.resetStatSpecs(statSpecFile); } } } }
NONSATD
true
} } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) {
if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testId, testContainers); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test with the given test id for (Iterator i = testContainers.iterator(); i.hasNext();) { TestContainer testContainer = (TestContainer)i.next(); List tests = testContainer.getTestsWithId(testId); for (Iterator j = tests.iterator(); j.hasNext();) { Test test = (Test)j.next();
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testId, testContainers); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test with the given test id for (Iterator i = testContainers.iterator(); i.hasNext();) { TestContainer testContainer = (TestContainer)i.next(); List tests = testContainer.getTestsWithId(testId); for (Iterator j = tests.iterator(); j.hasNext();) { Test test = (Test)j.next(); test.resetStatSpecs(statSpecFile); } } } }
25,228
6
// @todo lises support option to use union of all statspecs
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testId, testContainers); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test with the given test id for (Iterator i = testContainers.iterator(); i.hasNext();) { TestContainer testContainer = (TestContainer)i.next(); List tests = testContainer.getTestsWithId(testId); for (Iterator j = tests.iterator(); j.hasNext();) { Test test = (Test)j.next(); test.resetStatSpecs(statSpecFile); } } } }
IMPLEMENTATION
true
if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests();
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) {
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testId, testContainers); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test with the given test id for (Iterator i = testContainers.iterator(); i.hasNext();) { TestContainer testContainer = (TestContainer)i.next(); List tests = testContainer.getTestsWithId(testId); for (Iterator j = tests.iterator(); j.hasNext();) { Test test = (Test)j.next(); test.resetStatSpecs(statSpecFile); }
25,228
7
// reset the statspec file for each test with the given test id
private static void resetStatSpecs(String testId, List testContainers, String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testId, testContainers); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test with the given test id for (Iterator i = testContainers.iterator(); i.hasNext();) { TestContainer testContainer = (TestContainer)i.next(); List tests = testContainer.getTestsWithId(testId); for (Iterator j = tests.iterator(); j.hasNext();) { Test test = (Test)j.next(); test.resetStatSpecs(statSpecFile); } } } }
NONSATD
true
statSpecFile = getLastStatSpecFile(testId, testContainers); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test with the given test id for (Iterator i = testContainers.iterator(); i.hasNext();) { TestContainer testContainer = (TestContainer)i.next();
for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testId, testContainers); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test with the given test id for (Iterator i = testContainers.iterator(); i.hasNext();) { TestContainer testContainer = (TestContainer)i.next(); List tests = testContainer.getTestsWithId(testId); for (Iterator j = tests.iterator(); j.hasNext();) { Test test = (Test)j.next(); test.resetStatSpecs(statSpecFile); } } } }
String statSpecFileOverride) { if (testContainers.size() == 1) { // special case TestContainer testContainer = (TestContainer)testContainers.get(0); // determine which statspec file to use String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testContainer); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test in the container List tests = testContainer.getTests(); for (Iterator i = tests.iterator(); i.hasNext();) { Test test = (Test)i.next(); test.resetStatSpecs(statSpecFile); } } else { // determine which statspec file to use for this test id String statSpecFile = statSpecFileOverride; if (statSpecFileOverride == null) { statSpecFile = getLastStatSpecFile(testId, testContainers); } // @todo lises support option to use union of all statspecs // reset the statspec file for each test with the given test id for (Iterator i = testContainers.iterator(); i.hasNext();) { TestContainer testContainer = (TestContainer)i.next(); List tests = testContainer.getTestsWithId(testId); for (Iterator j = tests.iterator(); j.hasNext();) { Test test = (Test)j.next(); test.resetStatSpecs(statSpecFile); } } } }
25,229
0
/** * Returns a list of {@link ValueComparator}s for the given test and test * containers with values for relevant statistics. */
private static List buildValueComparators(String testId, List testContainers) { List comparators = new ArrayList(); for (int i = 0; i < testContainers.size(); i++) { TestContainer testContainer = (TestContainer)testContainers.get(i); List tests = testContainer.getTestsWithId(testId); if (tests.size() == 0) { // test is missing from this container comparators.add(null); } else if (tests.size() == 1) { Test test = (Test)tests.get(0); ValueComparator comparator = new ValueComparator(i, test); comparators.add(comparator); } else { // multiple runs of this test are present // @todo lises move this check into ValueComparator, for future // averaging, make ValueComparator accept a list of tests String s = "Not implemented yet: multiple tests in " + testContainer.getTestContainerDir() + " with id=" + testId; throw new UnsupportedOperationException(s); } } // make each instance read its archives for (Iterator i = comparators.iterator(); i.hasNext();) { ValueComparator comparator = (ValueComparator)i.next(); if (comparator != null) { comparator.readArchives(); } } return comparators; }
NONSATD
true
private static List buildValueComparators(String testId, List testContainers) { List comparators = new ArrayList(); for (int i = 0; i < testContainers.size(); i++) { TestContainer testContainer = (TestContainer)testContainers.get(i); List tests = testContainer.getTestsWithId(testId); if (tests.size() == 0) { // test is missing from this container comparators.add(null); } else if (tests.size() == 1) { Test test = (Test)tests.get(0); ValueComparator comparator = new ValueComparator(i, test); comparators.add(comparator); } else { // multiple runs of this test are present // @todo lises move this check into ValueComparator, for future // averaging, make ValueComparator accept a list of tests String s = "Not implemented yet: multiple tests in " + testContainer.getTestContainerDir() + " with id=" + testId; throw new UnsupportedOperationException(s); } } // make each instance read its archives for (Iterator i = comparators.iterator(); i.hasNext();) { ValueComparator comparator = (ValueComparator)i.next(); if (comparator != null) { comparator.readArchives(); } } return comparators; }
private static List buildValueComparators(String testId, List testContainers) { List comparators = new ArrayList(); for (int i = 0; i < testContainers.size(); i++) { TestContainer testContainer = (TestContainer)testContainers.get(i); List tests = testContainer.getTestsWithId(testId); if (tests.size() == 0) { // test is missing from this container comparators.add(null); } else if (tests.size() == 1) { Test test = (Test)tests.get(0); ValueComparator comparator = new ValueComparator(i, test); comparators.add(comparator); } else { // multiple runs of this test are present // @todo lises move this check into ValueComparator, for future // averaging, make ValueComparator accept a list of tests String s = "Not implemented yet: multiple tests in " + testContainer.getTestContainerDir() + " with id=" + testId; throw new UnsupportedOperationException(s); } } // make each instance read its archives for (Iterator i = comparators.iterator(); i.hasNext();) { ValueComparator comparator = (ValueComparator)i.next(); if (comparator != null) { comparator.readArchives(); } } return comparators; }
private static List buildValueComparators(String testId, List testContainers) { List comparators = new ArrayList(); for (int i = 0; i < testContainers.size(); i++) { TestContainer testContainer = (TestContainer)testContainers.get(i); List tests = testContainer.getTestsWithId(testId); if (tests.size() == 0) { // test is missing from this container comparators.add(null); } else if (tests.size() == 1) { Test test = (Test)tests.get(0); ValueComparator comparator = new ValueComparator(i, test); comparators.add(comparator); } else { // multiple runs of this test are present // @todo lises move this check into ValueComparator, for future // averaging, make ValueComparator accept a list of tests String s = "Not implemented yet: multiple tests in " + testContainer.getTestContainerDir() + " with id=" + testId; throw new UnsupportedOperationException(s); } } // make each instance read its archives for (Iterator i = comparators.iterator(); i.hasNext();) { ValueComparator comparator = (ValueComparator)i.next(); if (comparator != null) { comparator.readArchives(); } } return comparators; }
25,229
1
// test is missing from this container
private static List buildValueComparators(String testId, List testContainers) { List comparators = new ArrayList(); for (int i = 0; i < testContainers.size(); i++) { TestContainer testContainer = (TestContainer)testContainers.get(i); List tests = testContainer.getTestsWithId(testId); if (tests.size() == 0) { // test is missing from this container comparators.add(null); } else if (tests.size() == 1) { Test test = (Test)tests.get(0); ValueComparator comparator = new ValueComparator(i, test); comparators.add(comparator); } else { // multiple runs of this test are present // @todo lises move this check into ValueComparator, for future // averaging, make ValueComparator accept a list of tests String s = "Not implemented yet: multiple tests in " + testContainer.getTestContainerDir() + " with id=" + testId; throw new UnsupportedOperationException(s); } } // make each instance read its archives for (Iterator i = comparators.iterator(); i.hasNext();) { ValueComparator comparator = (ValueComparator)i.next(); if (comparator != null) { comparator.readArchives(); } } return comparators; }
NONSATD
true
TestContainer testContainer = (TestContainer)testContainers.get(i); List tests = testContainer.getTestsWithId(testId); if (tests.size() == 0) { // test is missing from this container comparators.add(null); } else if (tests.size() == 1) {
private static List buildValueComparators(String testId, List testContainers) { List comparators = new ArrayList(); for (int i = 0; i < testContainers.size(); i++) { TestContainer testContainer = (TestContainer)testContainers.get(i); List tests = testContainer.getTestsWithId(testId); if (tests.size() == 0) { // test is missing from this container comparators.add(null); } else if (tests.size() == 1) { Test test = (Test)tests.get(0); ValueComparator comparator = new ValueComparator(i, test); comparators.add(comparator); } else { // multiple runs of this test are present // @todo lises move this check into ValueComparator, for future // averaging, make ValueComparator accept a list of tests String s = "Not implemented yet: multiple tests in " + testContainer.getTestContainerDir() + " with id=" + testId;
private static List buildValueComparators(String testId, List testContainers) { List comparators = new ArrayList(); for (int i = 0; i < testContainers.size(); i++) { TestContainer testContainer = (TestContainer)testContainers.get(i); List tests = testContainer.getTestsWithId(testId); if (tests.size() == 0) { // test is missing from this container comparators.add(null); } else if (tests.size() == 1) { Test test = (Test)tests.get(0); ValueComparator comparator = new ValueComparator(i, test); comparators.add(comparator); } else { // multiple runs of this test are present // @todo lises move this check into ValueComparator, for future // averaging, make ValueComparator accept a list of tests String s = "Not implemented yet: multiple tests in " + testContainer.getTestContainerDir() + " with id=" + testId; throw new UnsupportedOperationException(s); } } // make each instance read its archives for (Iterator i = comparators.iterator(); i.hasNext();) { ValueComparator comparator = (ValueComparator)i.next(); if (comparator != null) { comparator.readArchives(); } }
25,229
2
// multiple runs of this test are present
private static List buildValueComparators(String testId, List testContainers) { List comparators = new ArrayList(); for (int i = 0; i < testContainers.size(); i++) { TestContainer testContainer = (TestContainer)testContainers.get(i); List tests = testContainer.getTestsWithId(testId); if (tests.size() == 0) { // test is missing from this container comparators.add(null); } else if (tests.size() == 1) { Test test = (Test)tests.get(0); ValueComparator comparator = new ValueComparator(i, test); comparators.add(comparator); } else { // multiple runs of this test are present // @todo lises move this check into ValueComparator, for future // averaging, make ValueComparator accept a list of tests String s = "Not implemented yet: multiple tests in " + testContainer.getTestContainerDir() + " with id=" + testId; throw new UnsupportedOperationException(s); } } // make each instance read its archives for (Iterator i = comparators.iterator(); i.hasNext();) { ValueComparator comparator = (ValueComparator)i.next(); if (comparator != null) { comparator.readArchives(); } } return comparators; }
NONSATD
true
ValueComparator comparator = new ValueComparator(i, test); comparators.add(comparator); } else { // multiple runs of this test are present // @todo lises move this check into ValueComparator, for future // averaging, make ValueComparator accept a list of tests
List comparators = new ArrayList(); for (int i = 0; i < testContainers.size(); i++) { TestContainer testContainer = (TestContainer)testContainers.get(i); List tests = testContainer.getTestsWithId(testId); if (tests.size() == 0) { // test is missing from this container comparators.add(null); } else if (tests.size() == 1) { Test test = (Test)tests.get(0); ValueComparator comparator = new ValueComparator(i, test); comparators.add(comparator); } else { // multiple runs of this test are present // @todo lises move this check into ValueComparator, for future // averaging, make ValueComparator accept a list of tests String s = "Not implemented yet: multiple tests in " + testContainer.getTestContainerDir() + " with id=" + testId; throw new UnsupportedOperationException(s); } } // make each instance read its archives for (Iterator i = comparators.iterator(); i.hasNext();) { ValueComparator comparator = (ValueComparator)i.next();
private static List buildValueComparators(String testId, List testContainers) { List comparators = new ArrayList(); for (int i = 0; i < testContainers.size(); i++) { TestContainer testContainer = (TestContainer)testContainers.get(i); List tests = testContainer.getTestsWithId(testId); if (tests.size() == 0) { // test is missing from this container comparators.add(null); } else if (tests.size() == 1) { Test test = (Test)tests.get(0); ValueComparator comparator = new ValueComparator(i, test); comparators.add(comparator); } else { // multiple runs of this test are present // @todo lises move this check into ValueComparator, for future // averaging, make ValueComparator accept a list of tests String s = "Not implemented yet: multiple tests in " + testContainer.getTestContainerDir() + " with id=" + testId; throw new UnsupportedOperationException(s); } } // make each instance read its archives for (Iterator i = comparators.iterator(); i.hasNext();) { ValueComparator comparator = (ValueComparator)i.next(); if (comparator != null) { comparator.readArchives(); } } return comparators; }
25,229
3
// @todo lises move this check into ValueComparator, for future // averaging, make ValueComparator accept a list of tests
private static List buildValueComparators(String testId, List testContainers) { List comparators = new ArrayList(); for (int i = 0; i < testContainers.size(); i++) { TestContainer testContainer = (TestContainer)testContainers.get(i); List tests = testContainer.getTestsWithId(testId); if (tests.size() == 0) { // test is missing from this container comparators.add(null); } else if (tests.size() == 1) { Test test = (Test)tests.get(0); ValueComparator comparator = new ValueComparator(i, test); comparators.add(comparator); } else { // multiple runs of this test are present // @todo lises move this check into ValueComparator, for future // averaging, make ValueComparator accept a list of tests String s = "Not implemented yet: multiple tests in " + testContainer.getTestContainerDir() + " with id=" + testId; throw new UnsupportedOperationException(s); } } // make each instance read its archives for (Iterator i = comparators.iterator(); i.hasNext();) { ValueComparator comparator = (ValueComparator)i.next(); if (comparator != null) { comparator.readArchives(); } } return comparators; }
IMPLEMENTATION
true
comparators.add(comparator); } else { // multiple runs of this test are present // @todo lises move this check into ValueComparator, for future // averaging, make ValueComparator accept a list of tests String s = "Not implemented yet: multiple tests in " + testContainer.getTestContainerDir() + " with id=" + testId;
for (int i = 0; i < testContainers.size(); i++) { TestContainer testContainer = (TestContainer)testContainers.get(i); List tests = testContainer.getTestsWithId(testId); if (tests.size() == 0) { // test is missing from this container comparators.add(null); } else if (tests.size() == 1) { Test test = (Test)tests.get(0); ValueComparator comparator = new ValueComparator(i, test); comparators.add(comparator); } else { // multiple runs of this test are present // @todo lises move this check into ValueComparator, for future // averaging, make ValueComparator accept a list of tests String s = "Not implemented yet: multiple tests in " + testContainer.getTestContainerDir() + " with id=" + testId; throw new UnsupportedOperationException(s); } } // make each instance read its archives for (Iterator i = comparators.iterator(); i.hasNext();) { ValueComparator comparator = (ValueComparator)i.next(); if (comparator != null) { comparator.readArchives();
private static List buildValueComparators(String testId, List testContainers) { List comparators = new ArrayList(); for (int i = 0; i < testContainers.size(); i++) { TestContainer testContainer = (TestContainer)testContainers.get(i); List tests = testContainer.getTestsWithId(testId); if (tests.size() == 0) { // test is missing from this container comparators.add(null); } else if (tests.size() == 1) { Test test = (Test)tests.get(0); ValueComparator comparator = new ValueComparator(i, test); comparators.add(comparator); } else { // multiple runs of this test are present // @todo lises move this check into ValueComparator, for future // averaging, make ValueComparator accept a list of tests String s = "Not implemented yet: multiple tests in " + testContainer.getTestContainerDir() + " with id=" + testId; throw new UnsupportedOperationException(s); } } // make each instance read its archives for (Iterator i = comparators.iterator(); i.hasNext();) { ValueComparator comparator = (ValueComparator)i.next(); if (comparator != null) { comparator.readArchives(); } } return comparators; }
25,229
4
// make each instance read its archives
private static List buildValueComparators(String testId, List testContainers) { List comparators = new ArrayList(); for (int i = 0; i < testContainers.size(); i++) { TestContainer testContainer = (TestContainer)testContainers.get(i); List tests = testContainer.getTestsWithId(testId); if (tests.size() == 0) { // test is missing from this container comparators.add(null); } else if (tests.size() == 1) { Test test = (Test)tests.get(0); ValueComparator comparator = new ValueComparator(i, test); comparators.add(comparator); } else { // multiple runs of this test are present // @todo lises move this check into ValueComparator, for future // averaging, make ValueComparator accept a list of tests String s = "Not implemented yet: multiple tests in " + testContainer.getTestContainerDir() + " with id=" + testId; throw new UnsupportedOperationException(s); } } // make each instance read its archives for (Iterator i = comparators.iterator(); i.hasNext();) { ValueComparator comparator = (ValueComparator)i.next(); if (comparator != null) { comparator.readArchives(); } } return comparators; }
NONSATD
true
} } // make each instance read its archives for (Iterator i = comparators.iterator(); i.hasNext();) { ValueComparator comparator = (ValueComparator)i.next();
ValueComparator comparator = new ValueComparator(i, test); comparators.add(comparator); } else { // multiple runs of this test are present // @todo lises move this check into ValueComparator, for future // averaging, make ValueComparator accept a list of tests String s = "Not implemented yet: multiple tests in " + testContainer.getTestContainerDir() + " with id=" + testId; throw new UnsupportedOperationException(s); } } // make each instance read its archives for (Iterator i = comparators.iterator(); i.hasNext();) { ValueComparator comparator = (ValueComparator)i.next(); if (comparator != null) { comparator.readArchives(); } } return comparators; }
private static List buildValueComparators(String testId, List testContainers) { List comparators = new ArrayList(); for (int i = 0; i < testContainers.size(); i++) { TestContainer testContainer = (TestContainer)testContainers.get(i); List tests = testContainer.getTestsWithId(testId); if (tests.size() == 0) { // test is missing from this container comparators.add(null); } else if (tests.size() == 1) { Test test = (Test)tests.get(0); ValueComparator comparator = new ValueComparator(i, test); comparators.add(comparator); } else { // multiple runs of this test are present // @todo lises move this check into ValueComparator, for future // averaging, make ValueComparator accept a list of tests String s = "Not implemented yet: multiple tests in " + testContainer.getTestContainerDir() + " with id=" + testId; throw new UnsupportedOperationException(s); } } // make each instance read its archives for (Iterator i = comparators.iterator(); i.hasNext();) { ValueComparator comparator = (ValueComparator)i.next(); if (comparator != null) { comparator.readArchives(); } } return comparators; }