auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static BitmapDrawable scaleBitmapToFitDisplay(Bitmap image) { final Display display = ((WindowManager) cgeoapplication.getInstance().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); final int maxWidth = display.getWidth() - 25; final int maxHeight = display.getHeight() - 25; final int imgWidth = image.getWidth(); final int imgHeight = image.getHeight(); int width; int height; Bitmap result = null; if (imgWidth > maxWidth || imgHeight > maxHeight) { final double ratio = Math.min((double) maxHeight / (double) imgHeight, (double) maxWidth / (double) imgWidth); width = (int) Math.ceil(imgWidth * ratio); height = (int) Math.ceil(imgHeight * ratio); try { result = Bitmap.createScaledBitmap(image, width, height, true); } catch (Exception e) { Log.d("ImageHelper.scaleBitmapToFitDisplay: Failed to scale image"); return null; } } else { result = image; width = imgWidth; height = imgHeight; } BitmapDrawable resultDrawable = new BitmapDrawable(cgeoapplication.getInstance().getResources(), result); resultDrawable.setBounds(new Rect(0, 0, width, height)); return resultDrawable; }

Target:
public static BitmapDrawable scaleBitmapToFitDisplay(Bitmap image) { if (image == null) { return null; } final Display display = ((WindowManager) cgeoapplication.getInstance().getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay(); final int maxWidth = display.getWidth() - 25; final int maxHeight = display.getHeight() - 25; final int imgWidth = image.getWidth(); final int imgHeight = image.getHeight(); int width; int height; Bitmap result; if (imgWidth > maxWidth || imgHeight > maxHeight) { final double ratio = Math.min((double) maxHeight / (double) imgHeight, (double) maxWidth / (double) imgWidth); width = (int) Math.ceil(imgWidth * ratio); height = (int) Math.ceil(imgHeight * ratio); result = Bitmap.createScaledBitmap(image, width, height, true); } else { result = image; width = imgWidth; height = imgHeight; } BitmapDrawable resultDrawable = new BitmapDrawable(cgeoapplication.getInstance().getResources(), result); resultDrawable.setBounds(new Rect(0, 0, width, height)); return resultDrawable; }
Source:
private static ProgramState handlePlusMinus(ProgramState previousState, ProgramState currentState) { List<SymbolicValue> operands = previousState.peekValues(2); SymbolicValue result = currentState.peekValue(); SymbolicValue op1 = operands.get(0); SymbolicValue op2 = operands.get(1); boolean op1Zero = isZero(currentState, op1); boolean op2Zero = isZero(currentState, op2); if (op1Zero && op2Zero) { return currentState.unstackValue(1).state.stackValue(op1); } else if (op1Zero) { return currentState.unstackValue(1).state.stackValue(op2); } else if (op2Zero) { return currentState.unstackValue(1).state.stackValue(op1); } return currentState.removeConstraintsOnDomain(result, BooleanConstraint.class); }

Target:
private static ProgramState handlePlusMinus(ProgramState previousState, ProgramState currentState) { List<SymbolicValue> operands = previousState.peekValues(2); SymbolicValue result = currentState.peekValue(); SymbolicValue op1 = operands.get(0); SymbolicValue op2 = operands.get(1); boolean op1Zero = isZero(currentState, op1); boolean op2Zero = isZero(currentState, op2); if (op2Zero) { return currentState.unstackValue(1).state.stackValue(op1); } else if (op1Zero) { return currentState.unstackValue(1).state.stackValue(op2); } return currentState.removeConstraintsOnDomain(result, BooleanConstraint.class); }
Source:
public void integerType() { final JsonSchemaValidator validator = factory.newInstance(jsonFactory.createObjectBuilder() .add("type", "object") .add("properties", jsonFactory.createObjectBuilder() .add("age", jsonFactory.createObjectBuilder() .add("type", "integer") .build()) .build()) .build()); assertTrue(validator.apply(jsonFactory.createObjectBuilder().build()).isSuccess()); assertTrue(validator.apply(jsonFactory.createObjectBuilder().add("age", 30).build()).isSuccess()); assertFalse(validator.apply(jsonFactory.createObjectBuilder() .add("age", 30.3) .build()).isSuccess()); validator.close(); }

Target:
public void integerType() { final JsonSchemaValidator validator = factory.newInstance(jsonFactory.createObjectBuilder() .add("type", "object") .add("properties", jsonFactory.createObjectBuilder() .add("age", jsonFactory.createObjectBuilder() .add("type", "integer") .build()) .build()) .build()); assertTrue(validator.apply(jsonFactory.createObjectBuilder().build()).isSuccess()); assertTrue(validator.apply(jsonFactory.createObjectBuilder().add("age", 30).build()).isSuccess()); assertTrue(validator.apply(jsonFactory.createObjectBuilder().add("age", -10).build()).isSuccess()); assertTrue(validator.apply(jsonFactory.createObjectBuilder().add("age", BigInteger.valueOf(50)).build()).isSuccess()); assertFalse(validator.apply(jsonFactory.createObjectBuilder() .add("age", 30.3f) .build()).isSuccess()); assertFalse(validator.apply(jsonFactory.createObjectBuilder() .add("age", -7.4d) .build()).isSuccess()); assertFalse(validator.apply(jsonFactory.createObjectBuilder() .add("age", BigDecimal.valueOf(50.35613d)).build()).isSuccess()); validator.close(); }
Source:
public OrderedRealmCollectionSnapshot<E> createSnapshot() { if (className != null) { return new OrderedRealmCollectionSnapshot<E>(realm, collection, className); } else { assert classSpec != null; return new OrderedRealmCollectionSnapshot<E>(realm, collection, classSpec); } }

Target:
public OrderedRealmCollectionSnapshot<E> createSnapshot() { if (className != null) { return new OrderedRealmCollectionSnapshot<E>(realm, collection, className); } else { return new OrderedRealmCollectionSnapshot<E>(realm, collection, classSpec); } }
Source:
public boolean execute(short a, BlockComponentHolder b) { try { for (Component c : b.values()) { c.onAttached(); } } catch (Exception e) { Spout.getLogger().log(Level.SEVERE, "Unhandled exception attaching block component", e); } return true; }

Target:
public boolean execute(short a, BlockComponentHolder b) { for (Component c : b.values()) { try { c.onAttached(); } catch (Exception e) { Spout.getLogger().log(Level.SEVERE, "Unhandled exception attaching block component", e); } } return true; }
Source:
public AvroRpcWorkflowManager(int port){ logger.info("Starting workflow manager on port: as {}", port, System.getProperty("user.name", "unknown")); Preconditions.checkArgument(port > 0, "Must specify a port greater than 0"); logger.debug("Getting workflow engine"); engine = getWorkflowEngineFromProperty(); if(engine == null){ throw new IllegalStateException("Null engine"); } URL workflowManagerUrl = safeGetUrlFromString("http://localhost" + ":" + port); if(workflowManagerUrl == null){ throw new IllegalStateException("Null workflow manager URL"); } logger.debug("Setting workflow engine url: {}", workflowManagerUrl.toString()); engine.setWorkflowManagerUrl(safeGetUrlFromString("http://localhost" + ":" + port)); repo = getWorkflowRepositoryFromProperty(); logger.debug("Starting Http Server..."); try { server = new HttpServer(new SpecificResponder( org.apache.oodt.cas.workflow.struct.avrotypes.WorkflowManager.class,this), port); } catch (IOException e) { logger.error("Unable to create http server on port: {}", e); throw new IllegalStateException("Unable to start http server on port: " + port, e); } logger.debug("Server created. Starting ..."); server.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { shutdown(); } }); logger.info("Workflow Manager started by for url: {}", System.getProperty("user.name", "unknown"), workflowManagerUrl); }

Target:
public AvroRpcWorkflowManager(int port){ logger.info("Starting workflow manager on port: as {}", port, System.getProperty("user.name", "unknown")); Preconditions.checkArgument(port > 0, "Must specify a port greater than 0"); logger.debug("Getting workflow engine"); engine = getWorkflowEngineFromProperty(); if(engine == null){ throw new IllegalStateException("Null engine"); } URL workflowManagerUrl = safeGetUrlFromString("http://" + getHostname() + ":" + port); if(workflowManagerUrl == null){ throw new IllegalStateException("Null workflow manager URL"); } logger.debug("Setting workflow engine url: {}", workflowManagerUrl.toString()); engine.setWorkflowManagerUrl(safeGetUrlFromString("http://" + getHostname() + ":" + port)); repo = getWorkflowRepositoryFromProperty(); logger.debug("Starting Http Server..."); try { server = new HttpServer(new SpecificResponder( org.apache.oodt.cas.workflow.struct.avrotypes.WorkflowManager.class,this), port); } catch (IOException e) { logger.error("Unable to create http server on port: {}", e); throw new IllegalStateException("Unable to start http server on port: " + port, e); } logger.debug("Server created. Starting ..."); server.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { shutdown(); } }); logger.info("Workflow Manager started by for url: {}", System.getProperty("user.name", "unknown"), workflowManagerUrl); }
Source:
public void patchJavaParameters(@Nullable Module module, @NotNull JavaParameters javaParameters) { if (module == null) { return; } AndroidFacet androidFacet = AndroidFacet.getInstance(module); if (androidFacet == null) { return; } IdeaAndroidProject ideaAndroidProject = androidFacet.getIdeaAndroidProject(); if (ideaAndroidProject == null) { return; } BaseArtifact testArtifact = ideaAndroidProject.findSelectedTestArtifactInSelectedVariant(); if (testArtifact == null) { return; } if (!AndroidProject.ARTIFACT_UNIT_TEST.equals(testArtifact.getName()) || !(testArtifact instanceof JavaArtifact)) { return; } PathsList classPath = javaParameters.getClassPath(); AndroidPlatform platform = AndroidPlatform.getInstance(module); if (platform == null) { return; } String originalClassPath = classPath.getPathsString(); try { handlePlatformJar(classPath, platform, (JavaArtifact)testArtifact); handleJavaResources(module, ideaAndroidProject, classPath); } catch (Exception e) { throw new RuntimeException("Error patching the JUnit class path. Original class path: " + originalClassPath, e); } }

Target:
public void patchJavaParameters(@Nullable Module module, @NotNull JavaParameters javaParameters) { if (module == null) { return; } AndroidFacet androidFacet = AndroidFacet.getInstance(module); if (androidFacet == null) { return; } IdeaAndroidProject ideaAndroidProject = androidFacet.getIdeaAndroidProject(); if (ideaAndroidProject == null) { return; } BaseArtifact testArtifact = ideaAndroidProject.findSelectedTestArtifactInSelectedVariant(); if (testArtifact == null) { return; } if (!AndroidProject.ARTIFACT_UNIT_TEST.equals(testArtifact.getName()) || !(testArtifact instanceof JavaArtifact)) { return; } PathsList classPath = javaParameters.getClassPath(); AndroidPlatform platform = AndroidPlatform.getInstance(module); if (platform == null) { return; } String originalClassPath = classPath.getPathsString(); try { handlePlatformJar(classPath, platform, (JavaArtifact)testArtifact); handleJavaResources(module, ideaAndroidProject, classPath); } catch (Exception e) { throw new RuntimeException(String.format("Error patching the JUnit class path. Original class path:%n%s", originalClassPath), e); } }
Source:
private static String getCertificateExpiration(String certificate) { String certWithoutBegin = certificate.replaceFirst("-----BEGIN CERTIFICATE-----", ""); String rawCert = certWithoutBegin.replaceFirst("-----END CERTIFICATE-----", ""); try (ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decodeBase64(rawCert.getBytes()))) { CertificateFactory certFact = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate)certFact.generateCertificate(bis); DateFormat dateFormat = DateFormat.getDateInstance(); return dateFormat.format(cert.getNotAfter()); } catch (IllegalArgumentException e) { throw new ConsistencyErrorException("Certificate is not in base64 format!", e); } catch (IOException | CertificateException e) { throw new InternalError(e); } }

Target:
private static String getCertificateExpiration(String certificate) { Utils.notNull(certificate, "certificate"); String certWithoutBegin = certificate.replaceFirst("-----BEGIN CERTIFICATE-----", ""); String rawCert = certWithoutBegin.replaceFirst("-----END CERTIFICATE-----", ""); try (ByteArrayInputStream bis = new ByteArrayInputStream(Base64.decodeBase64(rawCert.getBytes()))) { CertificateFactory certFact = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate)certFact.generateCertificate(bis); DateFormat dateFormat = DateFormat.getDateInstance(); return dateFormat.format(cert.getNotAfter()); } catch (IllegalArgumentException e) { throw new ConsistencyErrorException("Certificate is not in base64 format!", e); } catch (IOException | CertificateException e) { throw new InternalError(e); } }
Source:
public static org.ovirt.engine.core.common.businessentities.VmBackupPhase map(BackupPhase action) { switch (action) { case INITIALIZING: return org.ovirt.engine.core.common.businessentities.VmBackupPhase.Initializing; case STARTING: return org.ovirt.engine.core.common.businessentities.VmBackupPhase.Starting; case READY: return org.ovirt.engine.core.common.businessentities.VmBackupPhase.Ready; case FINALIZING: return org.ovirt.engine.core.common.businessentities.VmBackupPhase.Finalizing; default: return null; } }

Target:
public static org.ovirt.engine.core.common.businessentities.VmBackupPhase map(BackupPhase action) { switch (action) { case INITIALIZING: return org.ovirt.engine.core.common.businessentities.VmBackupPhase.INITIALIZING; case STARTING: return org.ovirt.engine.core.common.businessentities.VmBackupPhase.STARTING; case READY: return org.ovirt.engine.core.common.businessentities.VmBackupPhase.READY; case FINALIZING: return org.ovirt.engine.core.common.businessentities.VmBackupPhase.FINALIZING; default: return null; } }
Source:
private String getStackTrace(Throwable throwable) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); throwable.printStackTrace(pw); return sw.getBuffer().toString(); }

Target:
private String getStackTrace(Throwable throwable) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); throwable.printStackTrace(pw); return sw.toString(); }
Source:
private void launchEditTagsDialog(final Context context, final Pojo app) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(context.getResources().getString(R.string.tags_add_title)); final EditText tag = new EditText(context); tag.setInputType(InputType.TYPE_CLASS_TEXT); tag.setText(app.tags); builder.setView(tag); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { KissApplication.getTagsHandler(context).setTags(app.id, tag.getText().toString()); app.tags = tag.getText().toString(); app.displayTags = app.tags; String msg = context.getResources().getString(R.string.tags_confirmation_added); Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); } }); builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); }

Target:
private void launchEditTagsDialog(final Context context, final Pojo app) { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle(context.getResources().getString(R.string.tags_add_title)); final EditText tag = new EditText(context); tag.setInputType(InputType.TYPE_CLASS_TEXT); tag.setText(app.tags); builder.setView(tag); builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { KissApplication.getDataHandler(context).getTagsHandler().setTags(app.id, tag.getText().toString()); app.tags = tag.getText().toString(); app.displayTags = app.tags; String msg = context.getResources().getString(R.string.tags_confirmation_added); Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); } }); builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); builder.show(); }
Source:
public boolean initialize(List<StorageDomain> sds, StoragePool dc, String okCommandName, String cancelCommandName, ICommandTarget target) { List<StorageDomain> sdsToUpgrade = sds.stream().filter(getComparePredicate(dc)).collect(Collectors.toList()); if (sdsToUpgrade.isEmpty()) { return false; } UICommand okCommand = UICommand.createDefaultOkUiCommand(okCommandName, target); UICommand cancelCommand = UICommand.createCancelUiCommand(cancelCommandName, target); getCommands().add(okCommand); getCommands().add(cancelCommand); setTitle(ConstantsManager.getInstance().getConstants().areYouSureTitle()); if (sdsToUpgrade.size() > 1) { setMessage(ConstantsManager.getInstance() .getMessages() .compareMultipleStorageFormatsToDataCenterWarningMessage( dc.getName(), sdsToUpgrade.stream() .map(StorageDomain::getName) .collect(Collectors.joining(", ")))); } else { setMessage(ConstantsManager.getInstance() .getMessages() .compareStorageFormatToDataCenterWarningMessage( dc.getName(), sdsToUpgrade.get(0).getName(), sdsToUpgrade.get(0).getStorageFormat().getValue(), dc.getStoragePoolFormatType().getValue())); } return true; }

Target:
public boolean initialize(List<StorageDomain> sds, StoragePool dc, String okCommandName, String cancelCommandName, ICommandTarget target) { List<StorageDomain> sdsToUpgrade = sds.stream().filter(getComparePredicate(dc)).collect(Collectors.toList()); if (sdsToUpgrade.isEmpty()) { return false; } UICommand okCommand = UICommand.createDefaultOkUiCommand(okCommandName, target); UICommand cancelCommand = UICommand.createCancelUiCommand(cancelCommandName, target); getCommands().add(okCommand); getCommands().add(cancelCommand); setTitle(ConstantsManager.getInstance().getConstants().updatingStorageDomainTitle()); setMessage(getFormatWarningMessage(dc,sdsToUpgrade)); setHelpTag(HelpTag.attach_storage_domain_confirmation); setHashName("attach_storage_domain_confirmation"); return true; }
Source:
public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof SimpleLawJournalEntry)) return false; SimpleLawJournalEntry other = (SimpleLawJournalEntry) obj; if (entry != other.entry) return false; if (id != other.id) return false; if (journalNo != other.journalNo) return false; if (title == null) { if (other.title != null) return false; } else if (!title.equals(other.title)) return false; if (year != other.year) return false; return true; }

Target:
public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final SimpleLawJournalEntry other = (SimpleLawJournalEntry) obj; return Objects.equals(this.id, other.id) && Objects.equals(this.year, other.year) && Objects.equals(this.journalNo, other.journalNo) && Objects.equals(this.entry, other.entry) && Objects.equals(this.title, other.title); }
Source:
public static Matcher<? super View> withUsageHintOnClick(@StringRes final int resourceId) { return new TypeSafeMatcher<View>() { private String resourceName = null; private String expectedText = null; @Override protected boolean matchesSafely(View view) { if (!view.isClickable()) { return false; } if (null == this.expectedText) { try { expectedText = view.getResources().getString(resourceId); resourceName = view.getResources().getResourceEntryName(resourceId); } catch (Resources.NotFoundException ignored) { } } if (null != expectedText) { AccessibilityNodeInfo accessibilityNodeInfo = view.createAccessibilityNodeInfo(); AccessibilityNodeInfo.AccessibilityAction clickAction = findAction(accessibilityNodeInfo, AccessibilityNodeInfo.ACTION_CLICK); return expectedText.equals(clickAction.getLabel()); } else { return false; } } @Override public void describeTo(Description description) { description.appendText("is clickable and has custom usage hint for ACTION_CLICK from resource id: "); description.appendValue(resourceId); if (null != this.resourceName) { description.appendText("["); description.appendText(resourceName); description.appendText("]"); } if (null != this.expectedText) { description.appendText(" value: "); description.appendText(expectedText); } } }; }

Target:
public static Matcher<? super View> withUsageHintOnClick(@StringRes final int resourceId) { return new TypeSafeMatcher<View>() { private String resourceName; private String expectedText; @Override protected boolean matchesSafely(View view) { if (!view.isClickable()) { return false; } expectedText = view.getResources().getString(resourceId); resourceName = view.getResources().getResourceEntryName(resourceId); if (expectedText == null) { return false; } AccessibilityNodeInfo.AccessibilityAction clickAction = findAction(view, AccessibilityNodeInfo.ACTION_CLICK); return expectedText.equals(clickAction.getLabel()); } @Override public void describeTo(Description description) { description.appendText("is clickable and has custom usage hint for ACTION_CLICK from resource id: ").appendValue(resourceId); appendResourceNameAndExpectedTextToDescription(description, resourceName, expectedText); } }; }
Source:
public void setMinValue(final BigDecimal minValue) { BigDecimal currMin = getMinValue(); if ((minValue != null && currMin == null) || (currMin != null && (minValue == null || !(currMin.compareTo(minValue) == 0)))) { getOrCreateComponentModel().minValue = minValue; } }

Target:
public void setMinValue(final BigDecimal minValue) { BigDecimal currMin = getMinValue(); if (!Objects.equals(minValue, currMin)) { getOrCreateComponentModel().minValue = minValue; } }
Source:
public void aggregate(int length, AggregationResultHolder aggregationResultHolder, Map<TransformExpressionTree, BlockValSet> blockValSetMap) { HyperLogLog hyperLogLog = getDefaultHyperLogLog(aggregationResultHolder, _log2M); BlockValSet blockValSet = blockValSetMap.get(_expression); DataType valueType = blockValSet.getValueType(); switch (valueType) { case INT: int[][] intValuesArray = blockValSet.getIntValuesMV(); for (int i = 0; i < length; i++) { for (int value : intValuesArray[i]) { hyperLogLog.offer(value); } } break; case LONG: long[][] longValuesArray = blockValSet.getLongValuesMV(); for (int i = 0; i < length; i++) { for (long value : longValuesArray[i]) { hyperLogLog.offer(value); } } break; case FLOAT: float[][] floatValuesArray = blockValSet.getFloatValuesMV(); for (int i = 0; i < length; i++) { for (float value : floatValuesArray[i]) { hyperLogLog.offer(value); } } break; case DOUBLE: double[][] doubleValuesArray = blockValSet.getDoubleValuesMV(); for (int i = 0; i < length; i++) { for (double value : doubleValuesArray[i]) { hyperLogLog.offer(value); } } break; case STRING: String[][] stringValuesArray = blockValSet.getStringValuesMV(); for (int i = 0; i < length; i++) { for (String value : stringValuesArray[i]) { hyperLogLog.offer(value); } } break; default: throw new IllegalStateException( "Illegal data type for DISTINCT_COUNT_HLL_MV aggregation function: " + valueType); } }

Target:
public void aggregate(int length, AggregationResultHolder aggregationResultHolder, Map<TransformExpressionTree, BlockValSet> blockValSetMap) { HyperLogLog hyperLogLog = getDefaultHyperLogLog(aggregationResultHolder); BlockValSet blockValSet = blockValSetMap.get(_expression); DataType valueType = blockValSet.getValueType(); switch (valueType) { case INT: int[][] intValuesArray = blockValSet.getIntValuesMV(); for (int i = 0; i < length; i++) { for (int value : intValuesArray[i]) { hyperLogLog.offer(value); } } break; case LONG: long[][] longValuesArray = blockValSet.getLongValuesMV(); for (int i = 0; i < length; i++) { for (long value : longValuesArray[i]) { hyperLogLog.offer(value); } } break; case FLOAT: float[][] floatValuesArray = blockValSet.getFloatValuesMV(); for (int i = 0; i < length; i++) { for (float value : floatValuesArray[i]) { hyperLogLog.offer(value); } } break; case DOUBLE: double[][] doubleValuesArray = blockValSet.getDoubleValuesMV(); for (int i = 0; i < length; i++) { for (double value : doubleValuesArray[i]) { hyperLogLog.offer(value); } } break; case STRING: String[][] stringValuesArray = blockValSet.getStringValuesMV(); for (int i = 0; i < length; i++) { for (String value : stringValuesArray[i]) { hyperLogLog.offer(value); } } break; default: throw new IllegalStateException( "Illegal data type for DISTINCT_COUNT_HLL_MV aggregation function: " + valueType); } }
Source:
public void addMember(PerunSession sess, Group group, Member member) throws InternalErrorException, MemberNotExistsException, PrivilegeException, AlreadyMemberException, GroupNotExistsException, WrongAttributeValueException, WrongReferenceAttributeValueException, NotMemberOfParentGroupException, WrongAttributeAssignmentException, AttributeNotExistsException, ExternalyManagedException { Utils.checkPerunSession(sess); getGroupsManagerBl().checkGroupExists(sess, group); getPerunBl().getMembersManagerBl().checkMemberExists(sess, member); Attribute attrSynchronizeEnabled = getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPSYNCHROENABLED_ATTRNAME); if (attrSynchronizeEnabled.getValue() != null) { String synchronizeEnabled = (String) attrSynchronizeEnabled.getValue(); if (synchronizeEnabled.equals("true")) { throw new ExternalyManagedException("Adding of member is not allowed. Group is externaly managed."); } } if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, group) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, group)) { throw new PrivilegeException(sess, "addMember"); } if (member.getVoId() != (group.getVoId())) { throw new MembershipMismatchException("Member and group are form the different VO"); } getGroupsManagerBl().addMember(sess, group, member); }

Target:
public void addMember(PerunSession sess, Group group, Member member) throws InternalErrorException, MemberNotExistsException, PrivilegeException, AlreadyMemberException, GroupNotExistsException, WrongAttributeValueException, WrongReferenceAttributeValueException, NotMemberOfParentGroupException, WrongAttributeAssignmentException, AttributeNotExistsException, ExternallyManagedException { Utils.checkPerunSession(sess); getGroupsManagerBl().checkGroupExists(sess, group); getPerunBl().getMembersManagerBl().checkMemberExists(sess, member); if (!AuthzResolver.isAuthorized(sess, Role.VOADMIN, group) && !AuthzResolver.isAuthorized(sess, Role.GROUPADMIN, group)) { throw new PrivilegeException(sess, "addMember"); } if (member.getVoId() != (group.getVoId())) { throw new MembershipMismatchException("Member and group are form the different VO"); } Attribute attrSynchronizeEnabled = getPerunBl().getAttributesManagerBl().getAttribute(sess, group, GROUPSYNCHROENABLED_ATTRNAME); if (Objects.equals("true", (String) attrSynchronizeEnabled.getValue())) { throw new ExternallyManagedException("Adding of member is not allowed. Group is externally managed."); } getGroupsManagerBl().addMember(sess, group, member); }
Source:
private void scheduleExpiryTimerAfterSessionTimeout() { if (_timer == null) { _timer = new Timer(true); } TimerTask timerTask = new TimerTask() { public void run() { if (resetSession.get()) { onSessionExpired(); } } }; _timer.schedule(timerTask, _sessionTimeoutMs); }

Target:
private void scheduleExpiryTimerAfterSessionTimeout() { _zkSessionExpiryFuture = _scheduledExecutorService.schedule(ZkAdapter.this::onSessionExpired, _sessionTimeoutMs, TimeUnit.MILLISECONDS); }
Source:
public HailStorm(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{1}{G}{G}"); this.getSpellAbility().addEffect(new DamageAllEffect(2, new FilterAttackingCreature())); this.getSpellAbility().addEffect(new DamageControllerEffect(1)); this.getSpellAbility().addEffect(new DamageAllEffect(1, filter)); }

Target:
public HailStorm(UUID ownerId, CardSetInfo setInfo) { super(ownerId,setInfo,new CardType[]{CardType.INSTANT},"{1}{G}{G}"); this.getSpellAbility().addEffect(new DamageAllEffect(2, new FilterAttackingCreature())); this.getSpellAbility().addEffect(new DamageControllerEffect(1).setText("and 1 damage to you ")); this.getSpellAbility().addEffect(new DamageAllEffect(1, filter).setText("and each creature you control.")); }
Source:
private void logMetrics() { try { Thread.sleep(METRIC_INIT_DELAY_MS); while (true) { Thread.sleep(metricsWindowMs); final double totalPullTimeSec = getTotalProcTimeSec(pullStats); final double totalPushTime = getTotalProcTimeSec(pushStats); final double totalReqProcTime = getTotalProcTimeSec(requestStats); final int totalPullCount = getTotalProcCount(pullStats); final int totalPushCount = getTotalProcCount(pushStats); final int totalReqCount = getTotalProcCount(requestStats); resetStats(); final ServerMetrics metricsMessage = ServerMetrics.newBuilder() .setWindowIndex(windowIndex) .setNumModelBlocks(0) .setMetricWindowMs(metricsWindowMs) .setTotalPullProcessingTimeSec(totalPullTimeSec) .setTotalPushProcessingTimeSec(totalPushTime) .setTotalReqProcessingTimeSec(totalReqProcTime) .setTotalPullProcessed(totalPullCount) .setTotalPushProcessed(totalPushCount) .setTotalReqProcessed(totalReqCount) .build(); LOG.log(Level.FINE, "ServerMetrics {0}", metricsMessage); windowIndex++; } } catch (final InterruptedException e) { LOG.log(Level.SEVERE, "Exception Occurred", e); throw new RuntimeException(e); } }

Target:
private void logMetrics() { try { Thread.sleep(METRIC_INIT_DELAY_MS); while (true) { Thread.sleep(metricsWindowMs); final double totalPullTimeSec = getTotalProcTimeSec(pullStats); final double totalPushTimeSec = getTotalProcTimeSec(pushStats); final double totalReqProcTimeSec = getTotalProcTimeSec(requestStats); final int totalPullCount = getTotalProcCount(pullStats); final int totalPushCount = getTotalProcCount(pushStats); final int totalReqCount = getTotalProcCount(requestStats); resetStats(); final ServerMetrics metricsMessage = ServerMetrics.newBuilder() .setWindowIndex(windowIndex) .setNumModelBlocks(0) .setMetricWindowMs(metricsWindowMs) .setTotalPullProcessingTimeSec(totalPullTimeSec) .setTotalPushProcessingTimeSec(totalPushTimeSec) .setTotalReqProcessingTimeSec(totalReqProcTimeSec) .setTotalPullProcessed(totalPullCount) .setTotalPushProcessed(totalPushCount) .setTotalReqProcessed(totalReqCount) .build(); LOG.log(Level.FINE, "ServerMetrics {0}", metricsMessage); windowIndex++; } } catch (final InterruptedException e) { LOG.log(Level.SEVERE, "Exception Occurred", e); throw new RuntimeException(e); } }
Source:
protected Object doWork() { final String sampleName = SegmentUtils.getSampleNameForCLIsFromSegmentFile(segmentsFile); Utils.regularReadableUserFile(snpCountsFile); Utils.regularReadableUserFile(coverageFile); Utils.regularReadableUserFile(segmentsFile); ACNVPlotter.writeSegmentedAlleleFractionPlot(sampleName, snpCountsFile, coverageFile, segmentsFile, outputDir, useSexChromosomes); ACNVPlotter.writeSegmentedAlleleFractionPlotPerSeg(sampleName, snpCountsFile, coverageFile, segmentsFile, outputDir, useSexChromosomes); return "SUCCESS"; }

Target:
protected Object doWork() { final String sampleName = SegmentUtils.getSampleNameForCLIsFromSegmentFile(segmentsFile); Utils.regularReadableUserFile(snpCountsFile); Utils.regularReadableUserFile(coverageFile); Utils.regularReadableUserFile(segmentsFile); ACNVPlotter.writeSegmentedAlleleFractionPlot(sampleName, snpCountsFile, coverageFile, segmentsFile, outputDir, outputPrefix, useSexChromosomes); ACNVPlotter.writeSegmentedAlleleFractionPlotPerSeg(sampleName, snpCountsFile, coverageFile, segmentsFile, outputDir, outputPrefix, useSexChromosomes); return "SUCCESS"; }
Source:
public void testExceptionPropagation(boolean isOwner, WriteMethod method) { Object key = getKey(isOwner); try { method.action.eval(key, wo, rw, (Function<ReadEntryView<Object, String>, Void> & Serializable) view -> null, (BiConsumer<WriteEntryView<String>, Void> & Serializable) (view, nil) -> { throw new TestException(); }, getClass()); fail("Should throw [CompletionException:]CacheException:TestException"); } catch (CacheException | CompletionException e) { Throwable t = e; if (Boolean.TRUE.equals(transactional) && t.getCause() instanceof RollbackException) { Throwable[] suppressed = t.getCause().getSuppressed(); if (suppressed != null && suppressed.length > 0) { t = suppressed[0]; assertEquals(XAException.class, t.getClass()); t = t.getCause(); } } while (t.getCause() instanceof RemoteException && t != t.getCause()) { t = t.getCause(); } if (t instanceof CompletionException) { t = t.getCause(); } assertEquals(t.getCause().getClass(), TestException.class); } }

Target:
public void testExceptionPropagation(boolean isOwner, WriteMethod method) { Object key = getKey(isOwner); try { method.action.eval(key, wo, rw, (Function<ReadEntryView<Object, String>, Void> & Serializable) view -> null, (BiConsumer<WriteEntryView<String>, Void> & Serializable) (view, nil) -> { throw new TestException(); }, getClass()); fail("Should throw CompletionException:CacheException:[RemoteException:]*TestException"); } catch (CacheException | CompletionException e) { Throwable t = e; if (Boolean.TRUE.equals(transactional) && t.getCause() instanceof RollbackException) { Throwable[] suppressed = t.getCause().getSuppressed(); if (suppressed != null && suppressed.length > 0) { t = suppressed[0]; assertEquals(XAException.class, t.getClass()); t = t.getCause(); } } assertException(CompletionException.class, t); t = t.getCause(); assertExceptionNonStrict(CacheException.class, t); while (t.getCause() instanceof RemoteException && t != t.getCause()) { t = t.getCause(); } assertException(TestException.class, t.getCause()); } }
Source:
public void createTopic(String topic, int partitions, short replicationFactor) { log.info("Creating topic: " + topic + ", partitions: " + partitions + ", replications: " + replicationFactor); CreateTopicsResult ret = adminClient.createTopics( Collections.singletonList(new NewTopic(topic, partitions, replicationFactor))); try { ret.all().get(5, TimeUnit.MINUTES); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new StreamRuntimeException(e); } catch (ExecutionException e) { if ((e.getCause() instanceof TopicExistsException)) { log.info("topic: " + topic + " exists"); } else { throw new StreamRuntimeException(e); } } catch (TimeoutException e) { throw new StreamRuntimeException("Unable to create topics " + topic + " within the timeout", e); } }

Target:
public void createTopic(String topic, int partitions, short replicationFactor) { log.info("Creating topic: " + topic + ", partitions: " + partitions + ", replications: " + replicationFactor); CreateTopicsResult ret = adminClient.createTopics( Collections.singletonList(new NewTopic(topic, partitions, replicationFactor))); try { ret.all().get(5, TimeUnit.MINUTES); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new StreamRuntimeException(e); } catch (ExecutionException e) { if (e.getCause() instanceof TopicExistsException) { log.info("topic: " + topic + " exists"); } else { throw new StreamRuntimeException(e); } } catch (TimeoutException e) { throw new StreamRuntimeException("Unable to create topics " + topic + " within the timeout", e); } }
Source:
public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.menu_item_removeWatched: android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getActivity()); builder.setMessage(R.string.remove_watched_popup_warning) .setTitle(R.string.remove_watched_popup_title) .setPositiveButton(R.string.remove_watched_popup_yes, (DialogInterface d, int id) -> removeWatchedStreams(false)) .setNeutralButton( R.string.remove_watched_popup_yes_and_partially_watched_videos, (DialogInterface d, int id) -> removeWatchedStreams(true)) .setNegativeButton(R.string.remove_watched_popup_cancel, (DialogInterface d, int id) -> d.cancel()); builder.create().show(); break; default: return super.onOptionsItemSelected(item); } return true; }

Target:
public boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.menu_item_remove_watched: if (!isRemovingWatched) { new AlertDialog.Builder(requireContext()) .setMessage(R.string.remove_watched_popup_warning) .setTitle(R.string.remove_watched_popup_title) .setPositiveButton(R.string.yes, (DialogInterface d, int id) -> removeWatchedStreams(false)) .setNeutralButton( R.string.remove_watched_popup_yes_and_partially_watched_videos, (DialogInterface d, int id) -> removeWatchedStreams(true)) .setNegativeButton(R.string.cancel, (DialogInterface d, int id) -> d.cancel()) .create() .show(); } break; default: return super.onOptionsItemSelected(item); } return true; }
Source:
public void releaseWhenMergeCumulateThrows() { WriteFailingByteBuf oldCumulation = new WriteFailingByteBuf(1, 64); ByteBuf in = Unpooled.buffer().writeZero(12); Throwable thrown = null; try { ByteToMessageDecoder.MERGE_CUMULATOR.cumulate(UnpooledByteBufAllocator.DEFAULT, oldCumulation, in); } catch (Throwable t) { thrown = t; } assertSame(oldCumulation.writeError(), thrown); assertEquals(0, in.refCnt()); assertEquals(1, oldCumulation.refCnt()); }

Target:
public void releaseWhenMergeCumulateThrows() { WriteFailingByteBuf oldCumulation = new WriteFailingByteBuf(1, 64); ByteBuf in = Unpooled.buffer().writeZero(12); Throwable thrown = null; try { ByteToMessageDecoder.MERGE_CUMULATOR.cumulate(UnpooledByteBufAllocator.DEFAULT, oldCumulation, in); } catch (Throwable t) { thrown = t; } assertSame(oldCumulation.writeError(), thrown); assertEquals(0, in.refCnt()); assertEquals(1, oldCumulation.refCnt()); oldCumulation.release(); }
Source:
public void test_matching() { when(discovery.getServices()).thenReturn(Collections.singletonList("service")); when(discovery.getInstances("service")).thenReturn(Collections.singletonList( (ServiceInstance) new DefaultServiceInstance("service", "localhost", 80, false))); listener.setMatchingServices(Collections.singleton("notService")); listener.onInstanceRegistered(new InstanceRegisteredEvent<>(new Object(), null)); assertEquals(0, registry.getApplications().size()); }

Target:
public void test_matching() { when(discovery.getServices()).thenReturn(Collections.singletonList("service")); when(discovery.getInstances("service")).thenReturn(Collections.singletonList( (ServiceInstance) new DefaultServiceInstance("service", "localhost", 80, false))); listener.setServices(singleton("notService")); listener.onInstanceRegistered(new InstanceRegisteredEvent<>(new Object(), null)); assertEquals(0, registry.getApplications().size()); }
Source:
public TestResult invoke(File ws, VirtualChannel channel) throws IOException { final long nowSlave = System.currentTimeMillis(); FileSet fs = Util.createFileSet(ws, testResults); DirectoryScanner ds = fs.getDirectoryScanner(); String[] files = ds.getIncludedFiles(); if (files.length == 0) { throw new AbortException(Messages.JUnitResultArchiver_NoTestReportFound()); } TestResult result = new TestResult(buildTime + (nowSlave - nowMaster), ds, keepLongStdio, listener); result.tally(); return result; }

Target:
public TestResult invoke(File ws, VirtualChannel channel) throws IOException { final long nowSlave = System.currentTimeMillis(); FileSet fs = Util.createFileSet(ws, testResults); DirectoryScanner ds = fs.getDirectoryScanner(); String[] files = ds.getIncludedFiles(); if (files.length == 0) { throw new AbortException(Messages.JUnitResultArchiver_NoTestReportFound()); } TestResult result = new TestResult(buildTime + (nowSlave - nowMaster), ds, keepLongStdio); result.tally(); return result; }
Source:
public void testExpiredCheckpointExceedsTolerableFailureNumber() { ExecutionVertex vertex1 = mockExecutionVertex(new ExecutionAttemptID()); ExecutionVertex vertex2 = mockExecutionVertex(new ExecutionAttemptID()); final String errorMsg = "Exceeded checkpoint failure tolerance number!"; CheckpointFailureManager checkpointFailureManager = getCheckpointFailureManager(errorMsg); CheckpointCoordinator coord = getCheckpointCoordinator(new JobID(), vertex1, vertex2, checkpointFailureManager); try { final CompletableFuture<CompletedCheckpoint> checkPointFuture = coord.triggerCheckpoint(false); manuallyTriggeredScheduledExecutor.triggerAll(); assertFalse(checkPointFuture.isCompletedExceptionally()); coord.abortPendingCheckpoints(new CheckpointException(CHECKPOINT_EXPIRED)); fail("Test failed."); } catch (Exception e) { assertTrue(e instanceof RuntimeException); assertEquals(errorMsg, e.getMessage()); } finally { try { coord.shutdown(JobStatus.FINISHED); } catch (Exception e) { e.printStackTrace(); fail(e.getMessage()); } } }

Target:
public void testExpiredCheckpointExceedsTolerableFailureNumber() throws Exception { ExecutionVertex vertex1 = mockExecutionVertex(new ExecutionAttemptID()); ExecutionVertex vertex2 = mockExecutionVertex(new ExecutionAttemptID()); final String errorMsg = "Exceeded checkpoint failure tolerance number!"; CheckpointFailureManager checkpointFailureManager = getCheckpointFailureManager(errorMsg); CheckpointCoordinator coord = getCheckpointCoordinator(new JobID(), vertex1, vertex2, checkpointFailureManager); try { coord.triggerCheckpoint(false); manuallyTriggeredScheduledExecutor.triggerAll(); coord.abortPendingCheckpoints(new CheckpointException(CHECKPOINT_EXPIRED)); fail("Test failed."); } catch (Exception e) { assertTrue(e instanceof RuntimeException); assertEquals(errorMsg, e.getMessage()); } finally { coord.shutdown(JobStatus.FINISHED); } }
Source:
public SpatialJoinOperator( OperatorContext operatorContext, JoinNode.Type joinType, List<Type> probeTypes, List<Integer> probeOutputChannels, int probeGeometryChannel, PagesSpatialIndexFactory pagesSpatialIndexFactory) { this.operatorContext = operatorContext; this.localUserMemoryContext = operatorContext.localUserMemoryContext(); this.joinType = joinType; this.probeTypes = ImmutableList.copyOf(probeTypes); this.probeOutputChannels = ImmutableList.copyOf(probeOutputChannels); this.probeGeometryChannel = probeGeometryChannel; this.pagesSpatialIndexFactory = pagesSpatialIndexFactory; this.pagesSpatialIndexFuture = pagesSpatialIndexFactory.createPagesSpatialIndex(); this.pageBuilder = new PageBuilder(ImmutableList.<Type>builder() .addAll(probeOutputChannels.stream() .map(probeTypes::get) .collect(toImmutableList())) .addAll(pagesSpatialIndexFactory.getOutputTypes()) .build()); }

Target:
public SpatialJoinOperator( OperatorContext operatorContext, JoinNode.Type joinType, List<Type> probeTypes, List<Integer> probeOutputChannels, int probeGeometryChannel, PagesSpatialIndexFactory pagesSpatialIndexFactory) { this.operatorContext = operatorContext; this.localUserMemoryContext = operatorContext.localUserMemoryContext(); this.joinType = joinType; this.probeTypes = ImmutableList.copyOf(probeTypes); this.probeOutputChannels = ImmutableList.copyOf(probeOutputChannels); this.probeGeometryChannel = probeGeometryChannel; this.pagesSpatialIndexFactory = pagesSpatialIndexFactory; this.pagesSpatialIndexFuture = pagesSpatialIndexFactory.createPagesSpatialIndex(); this.pageBuilder = new PageBuilder(ImmutableList.<Type>builder() .addAll(probeOutputChannels.stream() .map(probeTypes::get) .iterator()) .addAll(pagesSpatialIndexFactory.getOutputTypes()) .build()); }
Source:
public Ds3NameMapperParserImpl() throws IOException { this.objectMapper = initDs3NameMapper(); }

Target:
public Ds3NameMapperParserImpl() { this.objectMapper = initDs3NameMapper(); }
Source:
private void setupFocusHandling() { focusListener = new IWindowListener() { void updateUiState() { Display.getCurrent().asyncExec(new Runnable() { public void run() { uiIsActive = Display.getCurrent().getActiveShell() != null; } }); } public void windowOpened(IWorkbenchWindow window) { updateUiState(); } public void windowDeactivated(IWorkbenchWindow window) { updateUiState(); } public void windowClosed(IWorkbenchWindow window) { updateUiState(); } public void windowActivated(IWorkbenchWindow window) { updateUiState(); if (rcs.doReschedule) rcs.schedule(); refreshJob.triggerRefresh(); } }; Job job = new Job(UIText.Activator_setupFocusListener) { @Override protected IStatus run(IProgressMonitor monitor) { if (PlatformUI.isWorkbenchRunning()) PlatformUI.getWorkbench().addWindowListener(focusListener); else schedule(1000L); return Status.OK_STATUS; } }; job.schedule(); }

Target:
private void setupFocusHandling() { focusListener = new IWindowListener() { private void updateUiState() { Display.getCurrent().asyncExec(new Runnable() { public void run() { uiIsActive = Display.getCurrent().getActiveShell() != null; } }); } public void windowOpened(IWorkbenchWindow window) { updateUiState(); } public void windowDeactivated(IWorkbenchWindow window) { updateUiState(); } public void windowClosed(IWorkbenchWindow window) { updateUiState(); } public void windowActivated(IWorkbenchWindow window) { updateUiState(); if (rcs.doReschedule) rcs.schedule(); refreshJob.triggerRefresh(); } }; Job job = new Job(UIText.Activator_setupFocusListener) { @Override protected IStatus run(IProgressMonitor monitor) { if (PlatformUI.isWorkbenchRunning()) PlatformUI.getWorkbench().addWindowListener(focusListener); else schedule(1000L); return Status.OK_STATUS; } }; job.schedule(); }
Source:
public void migrationException_realmListChanged() throws IOException { RealmConfiguration config = configFactory.createConfiguration(); Realm.getInstance(configFactory.createConfiguration()).close(); DynamicRealm dynamicRealm = DynamicRealm.getInstance(config); dynamicRealm.beginTransaction(); RealmObjectSchema dogSchema = dynamicRealm.getSchema().get(Dog.CLASS_NAME); RealmObjectSchema ownerSchema = dynamicRealm.getSchema().get(CatOwner.CLASS_NAME); ownerSchema.removeField(CatOwner.FIELD_CATS); ownerSchema.addRealmListField(CatOwner.FIELD_CATS, dogSchema); dynamicRealm.commitTransaction(); dynamicRealm.close(); try { realm = Realm.getInstance(config); fail(); } catch (RealmMigrationNeededException ignored) { assertThat(ignored.getMessage(), CoreMatchers.containsString("Property 'CatOwner.cats' has been changed from 'array' to 'array'")); } }

Target:
public void migrationException_realmListChanged() throws IOException { RealmConfiguration config = configFactory.createConfiguration(); Realm.getInstance(configFactory.createConfiguration()).close(); DynamicRealm dynamicRealm = DynamicRealm.getInstance(config); dynamicRealm.beginTransaction(); RealmObjectSchema dogSchema = dynamicRealm.getSchema().get(Dog.CLASS_NAME); RealmObjectSchema ownerSchema = dynamicRealm.getSchema().get(CatOwner.CLASS_NAME); ownerSchema.removeField(CatOwner.FIELD_CATS); ownerSchema.addRealmListField(CatOwner.FIELD_CATS, dogSchema); dynamicRealm.commitTransaction(); dynamicRealm.close(); try { realm = Realm.getInstance(config); fail(); } catch (RealmMigrationNeededException ignored) { assertThat(ignored.getMessage(), CoreMatchers.containsString("Property 'CatOwner.cats' has been changed from 'array<Dog>' to 'array<Cat>'")); } }
Source:
public ContainerEntity findContainerByName(String name) { try { return entityManager.get().createQuery("SELECT c FROM " + entityClass.getName() + " c WHERE c.name = :name", entityClass) .setParameter("name", name) .getSingleResult(); } catch (PersistenceException e) { return null; } }

Target:
public ContainerEntity findContainerByName(String name) { try { return entityManager.get().createQuery("SELECT c FROM " + entityClass.getName() + " c WHERE c.name = :name", entityClass) .setParameter("name", name) .getSingleResult(); } catch (NoResultException e) { return null; } }