@Override
public BundleVersion createBundleVersionInternal(Bundle bundle, String name, String version, String description,
String recipe, ConfigurationDefinition configurationDefinition) throws Exception {
// ensure we have a version
version = getVersion(version, bundle);
ComparableVersion comparableVersion = new ComparableVersion(version);
Query q = entityManager.createNamedQuery(BundleVersion.QUERY_FIND_VERSION_INFO_BY_BUNDLE_ID);
q.setParameter("bundleId", bundle.getId());
@SuppressWarnings("unchecked")
List<Object[]> list = (List<Object[]>) q.getResultList();
int versionOrder = list.size();
boolean needToUpdateOrder = false;
// find out where in the order of versions this new version should be placed (e.g. 2.0 is after 1.0).
// the query returns a list of arrays - first element in array is version; second is versionOrder
// the query returns list in desc order - since the normal case is we are creating the latest, highest version,
// starting at the current highest version is the most efficient (we'll break the for loop after 1 iteration).
for (Object[] bv : list) {
ComparableVersion bvv = new ComparableVersion(bv[0].toString());
int comparison = comparableVersion.compareTo(bvv);
if (comparison == 0) {
throw new RuntimeException("Cannot create bundle with version [" + version + "], it already exists");
} else if (comparison < 0) {
versionOrder = ((Number) bv[1]).intValue();