auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void writeAssets(final XMLStreamWriter stream, final Resource assetFolder, final ResourceResolver resolver) throws XMLStreamException { for (Iterator<Resource> children = assetFolder.listChildren(); children.hasNext();) { Resource assetFolderChild = children.next(); if (assetFolderChild.isResourceType("dam:Asset")) { Asset asset = assetFolderChild.adaptTo(Asset.class); <START> if (damAssetTypes.contains(asset.getMimeType())) { <END> writeAsset(asset, stream, resolver); } } } }</code><technical_language>WDYT making this a bit more flexible I image/\* (for image mimetypes) ? I guess add totally compatible</technical_language>

Target:
private void writeAssets(final XMLStreamWriter stream, final Resource assetFolder, final ResourceResolver resolver) throws XMLStreamException { for (Iterator<Resource> children = assetFolder.listChildren(); children.hasNext();) { Resource assetFolderChild = children.next(); if (assetFolderChild.isResourceType("dam:Asset")) { Asset asset = assetFolderChild.adaptTo(Asset.class); if (damAssetTypes.contains(asset.getMimeType())) { writeAsset(asset, stream, resolver); } } else { writeAssets(stream, assetFolderChild, resolver); } } }
Source:
<code>public JoinerType flip() { <START> switch (this) { <END> case LESS_THAN: return GREATER_THAN; case LESS_THAN_OR_EQUAL: return GREATER_THAN_OR_EQUAL; case GREATER_THAN: return LESS_THAN; case GREATER_THAN_OR_EQUAL: return LESS_THAN_OR_EQUAL; default: throw new IllegalStateException("The joinerType (" + this + ") is not supported."); } }</code><technical_language>INTERSECTING DISJOINT</technical_language>

Target:
public JoinerType flip() { switch (this) { case LESS_THAN: return GREATER_THAN; case LESS_THAN_OR_EQUAL: return GREATER_THAN_OR_EQUAL; case GREATER_THAN: return LESS_THAN; case GREATER_THAN_OR_EQUAL: return LESS_THAN_OR_EQUAL; default: throw new IllegalStateException("The joinerType (" + this + ") cannot be flipped."); } }
Source:
<code>public UploadPack create(HttpServletRequest req, Repository repo) throws ServiceNotEnabledException, ServiceNotAuthorizedException { final ProjectControl pc = getProjectControl(req); <START> if (!pc.canPerformPackAction(uploadGroup)) { <END> throw new ServiceNotAuthorizedException(); } UploadPack up = new UploadPack(repo); if (!pc.allRefsAreVisible()) { up.setRefFilter(new VisibleRefFilter(repo, pc, db.get())); } return up; }</code><technical_language>uploadGroup reference of ProjectControl, servlet code</technical_language>

Target:
public UploadPack create(HttpServletRequest req, Repository repo) throws ServiceNotEnabledException, ServiceNotAuthorizedException { ProjectControl pc = getProjectControl(req); if (!pc.canRunUploadPack()) { throw new ServiceNotAuthorizedException(); } UploadPack up = new UploadPack(repo); up.setPackConfig(packConfig); if (!pc.allRefsAreVisible()) { up.setRefFilter(new VisibleRefFilter(repo, pc, db.get())); } return up; }
Source:
<code><START> public HelixDataAccessorWrapper(ZKHelixDataAccessor dataAccessor) { <END> super(dataAccessor); _restClient = CustomRestClientFactory.get(); }</code><technical_language>mark this deprecated</technical_language>

Target:
public HelixDataAccessorWrapper(ZKHelixDataAccessor dataAccessor) { this(dataAccessor, CustomRestClientFactory.get(), HelixRestNamespace.DEFAULT_NAMESPACE_NAME); }
Source:
<code>private static void fillSwaggerAuthentication(Definition definition, Swagger swagger) { <START> Map<String, SecuritySchemeDefinition> securitySchemes = new HashMap<>(); <END> String httpBasic = ChallengeScheme.HTTP_BASIC.getName(); for (Endpoint endpoint : definition.getEndpoints()) { if (httpBasic.equals(endpoint.getAuthenticationProtocol())) { securitySchemes.put(httpBasic, new BasicAuthDefinition()); } } swagger.setSecurityDefinitions(securitySchemes.isEmpty() ? null : securitySchemes); }</code><technical_language>do HashMap LinkedHashMap preserve order</technical_language>

Target:
private static void fillSwaggerAuthentication(Definition definition, Swagger swagger) { Map<String, SecuritySchemeDefinition> securitySchemes = new LinkedHashMap<>(); String httpBasic = ChallengeScheme.HTTP_BASIC.getName(); for (Endpoint endpoint : definition.getEndpoints()) { if (httpBasic.equals(endpoint.getAuthenticationProtocol())) { securitySchemes.put(httpBasic, new BasicAuthDefinition()); } } swagger.setSecurityDefinitions(securitySchemes.isEmpty() ? null : securitySchemes); }
Source:
<code>static String transformXmlByXslt(URI xmlFile, URI xslFile) throws TransformerException, IOException { FileManagementInterface fileManagementModule = new KitodoServiceLoader<FileManagementInterface>( FileManagementInterface.class).loadModule(); <START> StreamSource source = new StreamSource(fileManagementModule.getFile(xmlFile).toURI().toString()); <END> StreamSource styleSource = new StreamSource(xslFile.getPath()); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(styleSource); try (StringWriter stringWriter = new StringWriter()) { StreamResult result = new StreamResult(stringWriter); transformer.transform(source, result); return stringWriter.toString(); } }</code><technical_language>FileManagement open InputStream. URI a schema understood FileManagement (that is, data is in repository). this (I reordered lines do try-with-resources statement): TransformerFactory factory = TransformerFactory.newInstance(); StreamSource styleSource = new StreamSource(xslFile.getPath()); Transformer transformer = factory.newTransformer(styleSource); try (InputStream inputStream = fileManagementModule.read(xmlFile); StringWriter stringWriter = new StringWriter()) { StreamSource source = new StreamSource(inputStream); StreamResult result = new StreamResult(stringWriter); transformer.transform(source, result); return stringWriter.toString(); }</technical_language>

Target:
static String transformXmlByXslt(URI xmlFile, URI xslFile) throws TransformerException, IOException { FileManagementInterface fileManagementModule = new KitodoServiceLoader<FileManagementInterface>( FileManagementInterface.class).loadModule(); TransformerFactory factory = TransformerFactory.newInstance(); StreamSource styleSource = new StreamSource(xslFile.getPath()); Transformer transformer = factory.newTransformer(styleSource); try (InputStream inputStream = fileManagementModule.read(xmlFile); StringWriter stringWriter = new StringWriter()) { StreamSource source = new StreamSource(inputStream); StreamResult result = new StreamResult(stringWriter); transformer.transform(source, result); return stringWriter.toString(); } }
Source:
<code><START> private void assertJtsEnvelope(String wkt, Envelope expected) <END> { OGCGeometry geometry = OGCGeometry.fromText(wkt); Envelope calculated = GeometryUtils.getJtsEnvelope(geometry); assertEquals(calculated, expected); }</code><technical_language>private methods public methods; please, move this end of class</technical_language>

Target:
private void assertJtsEnvelope(String wkt, Envelope expected) { Envelope calculated = GeometryUtils.getJtsEnvelope(OGCGeometry.fromText(wkt)); assertEquals(calculated, expected); }
Source:
<code>public SolenoidExtend(SolenoidSubsystem system, BooleanSupplier... booleanSuppliers) { <START> super("Extending " + system.getName(), system, SolenoidState.EXTEND, booleanSuppliers); <END> }</code><technical_language>replace super this</technical_language>

Target:
public SolenoidExtend(SolenoidSubsystem system, BooleanSupplier... booleanSuppliers) { this("Extending " + system.getName(), system, booleanSuppliers); }
Source:
<code>public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == ApplicationConstants.RequestCodes.IMAGE_REQUEST) { if (resultCode == Activity.RESULT_OK) { Uri sourceUri = Uri.fromFile(output); openCropActivity(sourceUri, sourceUri); } else { output = null; } } else if (requestCode == ApplicationConstants.RequestCodes.GALLERY_IMAGE_REQUEST) { if (resultCode == Activity.RESULT_OK) { Uri sourceUri = data.getData(); File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); output = new File(dir, getUniqueImageFileName()); Uri destinationUri = Uri.fromFile(output); <START> openCropActivity(sourceUri, destinationUri); <END> } } else if (requestCode == UCrop.REQUEST_CROP) { if (resultCode == Activity.RESULT_OK) { patientPhoto = getResizedPortraitImage(output.getPath()); Bitmap bitmap = ThumbnailUtils.extractThumbnail(patientPhoto, patientImageView.getWidth(), patientImageView.getHeight()); patientImageView.setImageBitmap(bitmap); patientImageView.invalidate(); } else { output = null; } } else if (requestCode == UCrop.RESULT_ERROR) { ToastUtil.error(String.valueOf(UCrop.getError(data))); } }</code><technical_language>Change line 733-735 java Bitmap bitmap = ThumbnailUtils.extractThumbnail(patientPhoto, binding.patientPhoto.getWidth(), binding.patientPhoto.getHeight()); binding.patientPhoto.setImageBitmap(bitmap); binding.patientPhoto.invalidate();</technical_language>

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == ApplicationConstants.RequestCodes.IMAGE_REQUEST) { if (resultCode == Activity.RESULT_OK) { Uri sourceUri = Uri.fromFile(output); openCropActivity(sourceUri, sourceUri); } else { output = null; } } else if (requestCode == ApplicationConstants.RequestCodes.GALLERY_IMAGE_REQUEST) { if(resultCode == Activity.RESULT_OK) { Uri sourceUri = data.getData(); File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM); output = new File(dir, getUniqueImageFileName()); Uri destinationUri = Uri.fromFile(output); openCropActivity(sourceUri, destinationUri); } else { output= null; } } else if (requestCode == UCrop.REQUEST_CROP) { if (resultCode == Activity.RESULT_OK) { patientPhoto = getResizedPortraitImage(output.getPath()); Bitmap bitmap = ThumbnailUtils.extractThumbnail(patientPhoto, binding.patientPhoto.getWidth(), binding.patientPhoto.getHeight()); binding.patientPhoto.setImageBitmap(bitmap); binding.patientPhoto.invalidate(); } else { output = null; } } else if (requestCode == UCrop.RESULT_ERROR) { ToastUtil.error(String.valueOf(UCrop.getError(data))); } }
Source:
<code>public static org.ovirt.engine.core.common.businessentities.VmPool map(VmPool model, org.ovirt.engine.core.common.businessentities.VmPool template) { org.ovirt.engine.core.common.businessentities.VmPool entity = template != null ? template : new org.ovirt.engine.core.common.businessentities.VmPool(); if (model.isSetId()) { entity.setVmPoolId(GuidUtils.asGuid(model.getId())); } if (model.isSetName()) { entity.setName(model.getName()); } if (model.isSetDescription()) { entity.setVmPoolDescription(model.getDescription()); } if (model.isSetComment()) { entity.setComment(model.getComment()); } if (model.isSetSize()) { entity.setAssignedVmsCount(model.getSize()); } if (model.isSetCluster()) { if (model.getCluster().isSetId()) { entity.setClusterId(GuidUtils.asGuid(model.getCluster().getId())); } else if (model.getCluster().isSetName()) { entity.setClusterName(model.getCluster().getName()); } } if (model.isSetPrestartedVms()) { entity.setPrestartedVms(model.getPrestartedVms()); } if (model.isSetMaxUserVms()) { entity.setMaxAssignedVmsPerUser(model.getMaxUserVms()); } if (model.isSetDisplay() && model.getDisplay().isSetProxy()) { entity.setSpiceProxy("".equals(model.getDisplay().getProxy()) ? null : model.getDisplay().getProxy()); } if (model.isSetType()) { entity.setVmPoolType(map(model.getType(), null)); } if (model.isSetStateful()) { entity.setStateful(model.isStateful()); } if <START> (model.isAutoStorageSelect()) <END> { entity.setAutoStorageSelect(model.isAutoStorageSelect()); } return entity; }</code><technical_language>This 'isSetAutoStorageSelect' ..</technical_language>

Target:
public static org.ovirt.engine.core.common.businessentities.VmPool map(VmPool model, org.ovirt.engine.core.common.businessentities.VmPool template) { org.ovirt.engine.core.common.businessentities.VmPool entity = template != null ? template : new org.ovirt.engine.core.common.businessentities.VmPool(); if (model.isSetId()) { entity.setVmPoolId(GuidUtils.asGuid(model.getId())); } if (model.isSetName()) { entity.setName(model.getName()); } if (model.isSetDescription()) { entity.setVmPoolDescription(model.getDescription()); } if (model.isSetComment()) { entity.setComment(model.getComment()); } if (model.isSetSize()) { entity.setAssignedVmsCount(model.getSize()); } if (model.isSetCluster()) { if (model.getCluster().isSetId()) { entity.setClusterId(GuidUtils.asGuid(model.getCluster().getId())); } else if (model.getCluster().isSetName()) { entity.setClusterName(model.getCluster().getName()); } } if (model.isSetPrestartedVms()) { entity.setPrestartedVms(model.getPrestartedVms()); } if (model.isSetMaxUserVms()) { entity.setMaxAssignedVmsPerUser(model.getMaxUserVms()); } if (model.isSetDisplay() && model.getDisplay().isSetProxy()) { entity.setSpiceProxy("".equals(model.getDisplay().getProxy()) ? null : model.getDisplay().getProxy()); } if (model.isSetType()) { entity.setVmPoolType(map(model.getType(), null)); } if (model.isSetStateful()) { entity.setStateful(model.isStateful()); } if (model.isSetAutoStorageSelect()) { entity.setAutoStorageSelect(model.isAutoStorageSelect()); } return entity; }
Source:
<code>private void kill(String cluster, String jobId, String rangeType, String scope) throws FalconException { try { <START> OozieClientFactory.get(cluster).kill(jobId, rangeType, scope); <END> assertStatus(cluster, jobId, Status.KILLED, Status.SUCCEEDED, Status.FAILED); LOG.info("Killed job for instances on cluster {}", jobId, scope, cluster); } catch (OozieClientException e) { throw new FalconException(e); } }</code><technical_language>miss attach LocalOozieCoordClientProxy class</technical_language>

Target:
private void kill(String cluster, String jobId, String rangeType, String scope) throws FalconException { try { OozieClientFactory.get(cluster).kill(jobId, rangeType, scope); LOG.info("Killed job for instances on cluster {}", jobId, scope, cluster); } catch (OozieClientException e) { throw new FalconException(e); } }
Source:
<code>public void testConcurrentReadStateAndProcessAndClose() throws Exception { final int totalStates = 5; final int[] states = {1, 2, 3, 4}; final ChannelStateReader stateReader = new ResultPartitionTest.FiniteChannelStateReader(totalStates, states); final int totalBuffers = 3; final NettyShuffleEnvironment environment = new NettyShuffleEnvironmentBuilder() .setBufferSize(states.length * Integer.BYTES) .setNumNetworkBuffers(totalBuffers) .build(); final SingleInputGate inputGate = createInputGate(environment); final ExecutorService executor = Executors.newFixedThreadPool(3); try (Closer closer = Closer.create()) { closer.register(environment::close); closer.register(executor::shutdown); inputGate.setup(); Callable<Void> closeTask = () -> { inputGate.close(); return null; }; Callable<Void> readRecoveredStateTask = () -> { inputGate.readRecoveredState(executor, stateReader); return null; }; Callable<Void> processStateTask = () -> { while (true) { try { if (!getNextBufferAndVerify(inputGate, states)) { Thread.sleep(1); } } catch (Throwable t) { return null; } } }; <START> executor.invokeAll(Arrays.asList(closeTask, readRecoveredStateTask, processStateTask)); assertEquals(totalBuffers, environment.getNetworkBufferPool().getNumberOfAvailableMemorySegments()); assertTrue(inputGate.getCloseFuture().isDone()); <END> } }</code><technical_language>remove awaitTermination close calls</technical_language>

Target:
public void testConcurrentReadStateAndProcessAndClose() throws Exception { final int totalStates = 7; final int[] states = {1, 2, 3, 4, 5, 6}; final ChannelStateReader stateReader = new ResultPartitionTest.FiniteChannelStateReader(totalStates, states); final int totalBuffers = 5; final NettyShuffleEnvironment environment = new NettyShuffleEnvironmentBuilder() .setBufferSize(states.length * Integer.BYTES) .setNumNetworkBuffers(totalBuffers) .build(); final SingleInputGate inputGate = createInputGate(environment); final ExecutorService executor = Executors.newFixedThreadPool(3); try (Closer closer = Closer.create()) { closer.register(environment::close); closer.register(executor::shutdown); inputGate.setup(); Callable<Void> closeTask = () -> { inputGate.close(); return null; }; Callable<Void> readRecoveredStateTask = () -> { inputGate.readRecoveredState(executor, stateReader); return null; }; Callable<Void> processStateTask = () -> { while (true) { try { if (!getNextBufferAndVerify(inputGate, states)) { Thread.sleep(1); } } catch (Throwable t) { return null; } } }; executor.invokeAll(Arrays.asList(closeTask, readRecoveredStateTask, processStateTask)); assertEquals(totalBuffers, environment.getNetworkBufferPool().getNumberOfAvailableMemorySegments()); assertTrue(inputGate.getCloseFuture().isDone()); } }
Source:
<code>private void destroyPlayer() { if (playerFragment == null) { return; } showDeletePanel(getView()); playerFragment.lockOrientation(); FragmentManager childManager = getChildFragmentManager(); childManager.findFragmentById(R.id.container_player); childManager.beginTransaction().remove(playerFragment).commitAllowingStateLoss(); View container = getView().findViewById(R.id.container_player); <START> if (container.getVisibility() != View.GONE) { <END> container.setVisibility(View.GONE); } playerFragment = null; }</code><technical_language>nit-pick: good reason check if view is GONE, is harm in setting GONE</technical_language>

Target:
private void destroyPlayer() { if (playerFragment == null) { return; } showDeletePanel(getView()); playerFragment.lockOrientation(); getChildFragmentManager().beginTransaction().remove(playerFragment).commitAllowingStateLoss(); View container = getView().findViewById(R.id.container_player); container.setVisibility(View.GONE); playerFragment = null; }
Source:
<code>public String getTranslatedValue(@Nonnull String codeListName, @Nullable String code, String langCode) { String value = getValue(codeListName, code, langCode); if (value != null && value.startsWith("$")) { <START> return Value.of(value).translate().getString(); <END> } else { return value; } }</code><technical_language>need langcode for Value.of(value).translate() too</technical_language>

Target:
public String getTranslatedValue(@Nonnull String codeListName, @Nullable String code, String langCode) { String value = getValue(codeListName, code, langCode); if (value != null && value.startsWith("$")) { return Value.of(value).translate(langCode).getString(); } else { return value; } }
Source:
<code>public void write(Persistable p) { if (p.getID() != -1) { update(p.getID(), p); return; } <START> int persistableSize = TableBuilder.toBlob(p).length; <END> if (persistableSize > HybridFileBackedSqlStorage.ONE_MB_DB_SIZE_LIMIT) { throw new RecordTooLargeException(persistableSize); } SQLiteDatabase db = helper.getHandle(); try { db.beginTransaction(); long ret = db.insertOrThrow(table, DatabaseHelper.DATA_COL, helper.getContentValues(p)); if (ret > Integer.MAX_VALUE) { throw new RuntimeException("Waaaaaaaaaay too many values"); } p.setID((int)ret); db.setTransactionSuccessful(); } finally { db.endTransaction(); } }</code><technical_language>want check this in update well</technical_language>

Target:
public void write(Persistable p) { if (p.getID() != -1) { update(p.getID(), p); return; } SQLiteDatabase db = helper.getHandle(); try { db.beginTransaction(); long ret = db.insertOrThrow(table, DatabaseHelper.DATA_COL, helper.getContentValues(p)); if (ret > Integer.MAX_VALUE) { throw new RuntimeException("Waaaaaaaaaay too many values"); } p.setID((int)ret); db.setTransactionSuccessful(); } finally { db.endTransaction(); } }
Source:
<code>private void startPlaying() { mPlayer = new MediaPlayer(); try { mPlayer.setDataSource(this, mOutputUri); mPlayer.prepare(); mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { stopPlaying(); } }); mPlayer.start(); mPlayButton.setImageResource(R.drawable.pause); } catch (IOException e) { <START> } <END> }</code><technical_language>Fails silently</technical_language>

Target:
private void startPlaying() { mPlayer = new MediaPlayer(); try { mPlayer.setDataSource(this, mOutputUri); mPlayer.prepare(); mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mediaPlayer) { stopPlaying(); } }); mPlayer.start(); mPlayButton.setImageResource(R.drawable.pause); } catch (IOException e) { Utils.d("Exception in playing media: "+e.toString()); } }
Source:
<code><START> private static final Optional<String> detectedDockerHostIp = IN_A_CONTAINER ? getDefaultGateway() : Optional.empty(); <END> public static String getDockerHostIpAddress(DockerClientConfig config) { switch (config.getDockerHost().getScheme()) { case "http": case "https": case "tcp": return config.getDockerHost().getHost(); case "unix": if (IN_A_CONTAINER) { return getDefaultGateway().orElse("localhost"); } return "localhost"; default: return null; } }</code><technical_language>please put this method upper was, diff smaller</technical_language>

Target:
private static final Optional<String> detectedDockerHostIp = IN_A_CONTAINER ? getDefaultGateway() : Optional.empty(); @Getter(lazy = true) private static final Optional<String> defaultGateway = Optional .ofNullable(DockerClientFactory.instance().runInsideDocker( cmd -> cmd.withCmd("sh", "-c", "ip route|awk '/default/ { print $3 }'"), (client, id) -> { try { LogToStringContainerCallback loggingCallback = new LogToStringContainerCallback(); client.logContainerCmd(id).withStdOut(true) .withFollowStream(true) .exec(loggingCallback) .awaitStarted(); loggingCallback.awaitCompletion(3, SECONDS); return loggingCallback.toString(); } catch (Exception e) { log.warn("Can't parse the default gateway IP", e); return null; } } )) .map(StringUtils::trimToEmpty) .filter(StringUtils::isNotBlank); public static String getDockerHostIpAddress(DockerClientConfig config) { switch (config.getDockerHost().getScheme()) { case "http": case "https": case "tcp": return config.getDockerHost().getHost(); case "unix": if (IN_A_CONTAINER) { return getDefaultGateway().orElse("localhost"); } return "localhost"; default: return null; } }
Source:
<code>public Subscriber<ObservableConnection<T, T>> call(final Subscriber<? super ObservableConnection<T, T>> originalSubscriber) { Subscriber<ObservableConnection<T, T>> liftSubscriber = new Subscriber<ObservableConnection<T, T>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { originalSubscriber.onError(e); } @Override public void onNext(final ObservableConnection<T, T> connection) { final ChannelPipeline p = connection.getChannel().pipeline(); ChannelHandlerContext hctx = p.context(WebSocketClientHandler.class); if (hctx != null) { WebSocketClientHandler handler = p.get(WebSocketClientHandler.class); handler.addHandshakeFinishedListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isCancelled()) { <START> originalSubscriber.unsubscribe(); <END> } else if (future.isSuccess()) { originalSubscriber.onNext(connection); originalSubscriber.onCompleted(); } else { originalSubscriber.onError(future.cause()); } } }); } else { originalSubscriber.onError(new ChannelPipelineException( "invalid pipeline configuration - WebSocket pipeline with no WebSocketClientHandler")); } } }; originalSubscriber.add(liftSubscriber); return liftSubscriber; }</code><technical_language>code is sufficient for handling future completion: java if (future.isSuccess()) { originalSubscriber.onNext(connection); originalSubscriber.onCompleted(); } else { originalSubscriber.onError(future.cause()); } For cancellation, isSuccess() returns false cause() returns CancellationException</technical_language>

Target:
public Subscriber<ObservableConnection<T, T>> call(final Subscriber<? super ObservableConnection<T, T>> originalSubscriber) { Subscriber<ObservableConnection<T, T>> liftSubscriber = new Subscriber<ObservableConnection<T, T>>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { originalSubscriber.onError(e); } @Override public void onNext(final ObservableConnection<T, T> connection) { final ChannelPipeline p = connection.getChannel().pipeline(); ChannelHandlerContext hctx = p.context(WebSocketClientHandler.class); if (hctx != null) { WebSocketClientHandler handler = p.get(WebSocketClientHandler.class); handler.addHandshakeFinishedListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { originalSubscriber.onNext(connection); originalSubscriber.onCompleted(); } else { originalSubscriber.onError(future.cause()); } } }); } else { originalSubscriber.onError(new ChannelPipelineException( "invalid pipeline configuration - WebSocket pipeline with no WebSocketClientHandler")); } } }; originalSubscriber.add(liftSubscriber); return liftSubscriber; }
Source:
<code>public void shouldTestPurgeProgramAttributeType() throws Exception { ProgramAttributeType programAttributeType = pws.getProgramAttributeType(1); pws.purgeProgramAttributeType(programAttributeType); <START> assertEquals(0,pws.getAllProgramAttributeTypes().size()); <END> }</code><technical_language>clearer if started asserting size more purging</technical_language>

Target:
public void shouldTestPurgeProgramAttributeType() throws Exception { ProgramAttributeType programAttributeType = pws.getProgramAttributeType(1); int totalAttributeTypes = pws.getAllProgramAttributeTypes().size(); pws.purgeProgramAttributeType(programAttributeType); assertEquals((totalAttributeTypes - 1), pws.getAllProgramAttributeTypes().size()); }
Source:
<code>private Artifact createArtifact(IProgressMonitor monitor, RoughArtifact roughArtifact, Artifact realParent) throws OseeCoreException { Artifact realArtifact = roughToRealArtifact.get(roughArtifact); if (realArtifact != null) { return realArtifact; } realArtifact = artifactResolver.resolve(roughArtifact, transaction.getBranch(), realParent, destinationArtifact); unmatchedArtifacts.remove(realArtifact); for (RoughArtifact childRoughArtifact : roughArtifact.getDescendants()) { Artifact childArtifact = createArtifact(monitor, childRoughArtifact, realArtifact); if (areValid(realArtifact, childArtifact)) { removeOtherParent(childArtifact, realArtifact); if (!childArtifact.hasParent()) { realArtifact.addChild(importArtifactOrder, childArtifact); } } if (extractor != null) { <START> if (extractor.artifactCreated(childArtifact)) { <END> childArtifact.persist(transaction); } } } if (realArtifact != null) { realArtifact.persist(transaction); } return realArtifact; }</code><technical_language>consider merging if conditions line</technical_language>

Target:
private Artifact createArtifact(IProgressMonitor monitor, RoughArtifact roughArtifact, Artifact realParent) throws OseeCoreException { Artifact realArtifact = roughToRealArtifact.get(roughArtifact); if (realArtifact != null) { return realArtifact; } realArtifact = artifactResolver.resolve(roughArtifact, transaction.getBranch(), realParent, destinationArtifact); unmatchedArtifacts.remove(realArtifact); for (RoughArtifact childRoughArtifact : roughArtifact.getDescendants()) { Artifact childArtifact = createArtifact(monitor, childRoughArtifact, realArtifact); if (areValid(realArtifact, childArtifact)) { removeOtherParent(childArtifact, realArtifact); if (!childArtifact.hasParent()) { realArtifact.addChild(importArtifactOrder, childArtifact); } } if ((extractor != null) && (extractor.artifactCreated(childArtifact))) { childArtifact.persist(transaction); } } if (realArtifact != null) { realArtifact.persist(transaction); } return realArtifact; }
Source:
<code><START> static ReadCountCollection removeColumnsWithTooManyZeros(final ReadCountCollection readCounts, final int maximumColumnZeros, final Logger logger) { <END> final Set<String> columnsToKeep = new HashSet<>(readCounts.columnNames().size()); final RealMatrix counts = readCounts.counts(); for (int i = 0; i < counts.getColumnDimension(); i++) { final double[] columnCounts = counts.getColumn(i); int zeroCounts = 0; for (final double columnCount : columnCounts) { if (columnCount == 0.0) { zeroCounts++; } } if (zeroCounts <= maximumColumnZeros) { columnsToKeep.add(readCounts.columnNames().get(i)); } } final int columnsToDropCount = readCounts.columnNames().size() - columnsToKeep.size(); if (columnsToDropCount == 0) { logger.info( String.format("No count column dropped due to zero counts; there is no column with a large number of targets with zero counts (<= %d of %d) ", maximumColumnZeros, readCounts.targets().size())); return readCounts; } else if (columnsToDropCount == readCounts.columnNames().size()) { throw new UserException.BadInput("The number of zeros per count column is too large resulting in all count columns to be dropped"); } else { logger.info( String.format("Some counts columns dropped, %d of %d, as they have too many targets with zeros (> %d of %d)." , columnsToDropCount, readCounts.columnNames().size(), maximumColumnZeros, readCounts.targets().size())); return readCounts.subsetColumns(columnsToKeep); } }</code><technical_language>targets, Stream-ify this</technical_language>

Target:
static ReadCountCollection removeColumnsWithTooManyZeros(final ReadCountCollection readCounts, final int maximumColumnZeros, final Logger logger) { final RealMatrix counts = readCounts.counts(); final Set<String> columnsToKeep = IntStream.range(0, counts.getColumnDimension()).boxed() .filter(i -> countZeroes(counts.getColumn(i)) <= maximumColumnZeros) .map(i -> readCounts.columnNames().get(i)).collect(Collectors.toSet()); final int columnsToDropCount = readCounts.columnNames().size() - columnsToKeep.size(); if (columnsToDropCount == 0) { logger.info( String.format("No count column dropped due to zero counts; there is no column with a large number of targets with zero counts (<= %d of %d) ", maximumColumnZeros, readCounts.targets().size())); return readCounts; } else if (columnsToDropCount == readCounts.columnNames().size()) { throw new UserException.BadInput("The number of zeros per count column is too large resulting in all count columns to be dropped"); } else { logger.info( String.format("Some counts columns dropped, %d of %d, as they have too many targets with zeros (> %d of %d)." , columnsToDropCount, readCounts.columnNames().size(), maximumColumnZeros, readCounts.targets().size())); return readCounts.subsetColumns(columnsToKeep); } }
Source:
<code>private Collection<String> buildFileList(Collection<IFile> files) throws CoreException { <START> Collection<String> result = new ArrayList<String>(); <END> for (IFile file : files) { RepositoryMapping mapping = RepositoryMapping.getMapping(file); if (mapping == null) throw new CoreException(Activator.error(NLS.bind(CoreText.CommitOperation_couldNotFindRepositoryMapping, file), null)); String repoRelativePath = mapping.getRepoRelativePath(file); result.add(repoRelativePath); } return result; }</code><technical_language>I HashSet faster in addUntracked() call contains() is O(n) for ArrayList O(1) for HashSet</technical_language>

Target:
private Collection<String> buildFileList(Collection<IFile> files) throws CoreException { Collection<String> result = new HashSet<String>(); for (IFile file : files) { RepositoryMapping mapping = RepositoryMapping.getMapping(file); if (mapping == null) throw new CoreException(Activator.error(NLS.bind(CoreText.CommitOperation_couldNotFindRepositoryMapping, file), null)); String repoRelativePath = mapping.getRepoRelativePath(file); result.add(repoRelativePath); } return result; }
Source:
<code>public void send(String destinationUri, DatastreamProducerRecord record, SendCallback onSendComplete) { try { Validate.notNull(record, "null event record."); Validate.notNull(record.getEvents(), "null datastream events."); LOG.debug("Sending Datastream event record: " + record); for (Pair<byte[], byte[]> event : record.getEvents()) { ProducerRecord<byte[], byte[]> outgoing; try { outgoing = convertToProducerRecord(destinationUri, record, event.getKey(), event.getValue()); } catch (Exception e) { String errorMessage = String.format("Failed to convert DatastreamEvent (%s) to ProducerRecord.", event); LOG.error(errorMessage, e); throw new DatastreamRuntimeException(errorMessage, e); } _eventWriteRate.mark(); <START> _eventByteWriteRate.mark(event.getValue().length); <END> _producer.send(outgoing, (metadata, exception) -> onSendComplete.onCompletion( new DatastreamRecordMetadata(String.valueOf(metadata.offset()), metadata.topic(), metadata.partition()), exception)); } } catch (Exception e) { _eventTransportErrorCount.inc(); String errorMessage = String.format("Sending event (%s) to topic %s and Kafka cluster (Metadata brokers) %s " + "failed with exception", record.getEvents(), destinationUri, _brokers); ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e); } LOG.debug("Done sending Datastream event record: " + record); }</code><technical_language>include key</technical_language>

Target:
public void send(String destinationUri, DatastreamProducerRecord record, SendCallback onSendComplete) { try { Validate.notNull(record, "null event record."); Validate.notNull(record.getEvents(), "null datastream events."); LOG.debug("Sending Datastream event record: " + record); for (Pair<byte[], byte[]> event : record.getEvents()) { ProducerRecord<byte[], byte[]> outgoing; try { outgoing = convertToProducerRecord(destinationUri, record, event.getKey(), event.getValue()); } catch (Exception e) { String errorMessage = String.format("Failed to convert DatastreamEvent (%s) to ProducerRecord.", event); LOG.error(errorMessage, e); throw new DatastreamRuntimeException(errorMessage, e); } _eventWriteRate.mark(); _eventByteWriteRate.mark(event.getKey().length + event.getValue().length); _producer.send(outgoing, (metadata, exception) -> onSendComplete.onCompletion( new DatastreamRecordMetadata(String.valueOf(metadata.offset()), metadata.topic(), metadata.partition()), exception)); } } catch (Exception e) { _eventTransportErrorRate.mark(); String errorMessage = String.format("Sending event (%s) to topic %s and Kafka cluster (Metadata brokers) %s " + "failed with exception", record.getEvents(), destinationUri, _brokers); ErrorLogger.logAndThrowDatastreamRuntimeException(LOG, errorMessage, e); } LOG.debug("Done sending Datastream event record: " + record); }
Source:
<code>private SecureStoreInitData discoverSecureStoreClass(File sitePath) { if (Strings.isNullOrEmpty(getSecureStoreLib())) { return null; } <START> String currentSecureStore; <END> try { currentSecureStore = getSecureStoreClassFromGerritConfig(new SitePaths(sitePath)); if (!Strings.isNullOrEmpty(currentSecureStore)) { throw new RuntimeException( String .format( "SecureStore is already set to %s. To change it use switch-secure-store program.", currentSecureStore)); } } catch (FileNotFoundException e) { } try { File secureStoreLib = new File(getSecureStoreLib()); if (!secureStoreLib.exists()) { throw new InvalidSecureStoreException(String.format( "File %s doesn't exist", getSecureStoreLib())); } JarScanner scanner = new JarScanner(secureStoreLib); List<String> secureStores = scanner.findChildrenOf(SecureStore.class); if (secureStores.isEmpty()) { throw new InvalidSecureStoreException(String.format( "Cannot find class implementing %s interface in %s", SecureStore.class.getName(), getSecureStoreLib())); } if (secureStores.size() > 1) { throw new InvalidSecureStoreException(String.format( "%s have more that one implementation of %s interface", getSecureStoreLib(), SecureStore.class.getName())); } IoUtil.loadJARs(secureStoreLib); return new SecureStoreInitData(getSecureStoreLib(), secureStores.get(0)); } catch (IOException e) { throw new InvalidSecureStoreException(String.format("%s is not a valid jar ", getSecureStoreLib())); } }</code><technical_language>Move this line 2650. needed here, in try body</technical_language>

Target:
private SecureStoreInitData discoverSecureStoreClass(File sitePath) { if (Strings.isNullOrEmpty(getSecureStoreLib())) { return null; } String currentSecureStore; try { currentSecureStore = getSecureStoreClassFromGerritConfig(new SitePaths(sitePath)); if (!Strings.isNullOrEmpty(currentSecureStore)) { throw new RuntimeException( String .format( "SecureStore is already set to %s. To change it use switch-secure-store program.", currentSecureStore)); } } catch (FileNotFoundException e) { } try { File secureStoreLib = new File(getSecureStoreLib()); if (!secureStoreLib.exists()) { throw new InvalidSecureStoreException(String.format( "File %s doesn't exist", getSecureStoreLib())); } JarScanner scanner = new JarScanner(secureStoreLib); List<String> secureStores = scanner.findChildrenOf(SecureStore.class); if (secureStores.isEmpty()) { throw new InvalidSecureStoreException(String.format( "Cannot find class implementing %s interface in %s", SecureStore.class.getName(), getSecureStoreLib())); } if (secureStores.size() > 1) { throw new InvalidSecureStoreException(String.format( "%s have more that one implementation of %s interface", getSecureStoreLib(), SecureStore.class.getName())); } IoUtil.loadJARs(secureStoreLib); return new SecureStoreInitData(secureStoreLib, secureStores.get(0)); } catch (IOException e) { throw new InvalidSecureStoreException(String.format("%s is not a valid jar", getSecureStoreLib())); } }
Source:
<code>void cleanup () { for (Entry<String, CacheFileCopy> entry : this.filesTable.entrySet()) { String tempFilePathname = RAImageIngestModule.getRATempPath(currentCase, moduleName) + File.separator + entry.getKey(); try { entry.getValue().getFileCopy().getChannel().close(); entry.getValue().getFileCopy().close(); File tmpFile = new File(tempFilePathname); if (!tmpFile.delete()) { tmpFile.deleteOnExit(); } } catch (IOException ex) { <START> logger.log(Level.SEVERE, String.format("Failed to delete cache file copy %s", tempFilePathname), ex); <END> } } }</code><technical_language>If unable delete a temp file is a SEVERE error? this information a warning</technical_language>

Target:
void cleanup () { for (Entry<String, CacheFileCopy> entry : this.filesTable.entrySet()) { String tempFilePathname = RAImageIngestModule.getRATempPath(currentCase, moduleName) + File.separator + entry.getKey(); try { entry.getValue().getFileCopy().getChannel().close(); entry.getValue().getFileCopy().close(); File tmpFile = new File(tempFilePathname); if (!tmpFile.delete()) { tmpFile.deleteOnExit(); } } catch (IOException ex) { logger.log(Level.WARNING, String.format("Failed to delete cache file copy %s", tempFilePathname), ex); } } }
Source:
<code>public static Optional<InsightCard> processData(final Long accountId, final ImmutableList<AggregateSleepStats> sleepStats, final Boolean isNewUser) { if (sleepStats.isEmpty()) { return Optional.absent(); } float totDuration = 0.0f; float totMotion = 0.0f; int numDays = 0; for (final AggregateSleepStats stat : sleepStats) { if (stat.motionScore.motionPeriodMinutes == 0) { continue; } totMotion += (float) stat.motionScore.numMotions; totDuration += (float) stat.motionScore.motionPeriodMinutes; numDays++; } if (totMotion == 0 || numDays < MIN_DAYS_REQUIRED) { return Optional.absent(); } final float averageMotionPercentage = ((totMotion / totDuration) * 100.0f); final float overallDiff = (( averageMotionPercentage - AVERAGE_SLEEP_PERC) / AVERAGE_SLEEP_PERC ) * 100.0f; Text text; if (Math.abs(overallDiff) >= SIGNIFICANT_DIFF) { if (overallDiff > 0) { text = SleepMotionMsgEN.moreMovement(numDays, (int) Math.abs(overallDiff), (int) averageMotionPercentage); <START> } else { <END> text = SleepMotionMsgEN.lessMovement(numDays, (int) Math.abs(overallDiff), (int) averageMotionPercentage); } } else { if ((int) overallDiff != 0) { text = SleepMotionMsgEN.equalMovement(numDays, (int) Math.abs(overallDiff), (int) averageMotionPercentage); } else { text = SleepMotionMsgEN.reallyEqualMovement(numDays, (int) Math.abs(overallDiff), (int) averageMotionPercentage); } } return Optional.of(new InsightCard(accountId, text.title, text.message, InsightCard.Category.SLEEP_QUALITY, InsightCard.TimePeriod.RECENTLY, DateTime.now(DateTimeZone.UTC))); }</code><technical_language>convert absolute in SleepMotionMsgEN</technical_language>

Target:
public static Optional<InsightCard> processData(final Long accountId, final ImmutableList<AggregateSleepStats> sleepStats, final Boolean isNewUser) { if (sleepStats.isEmpty()) { return Optional.absent(); } float totDuration = 0.0f; float totMotion = 0.0f; int numDays = 0; for (final AggregateSleepStats stat : sleepStats) { if (stat.motionScore.motionPeriodMinutes == 0) { continue; } totMotion += (float) stat.motionScore.numMotions; totDuration += (float) stat.motionScore.motionPeriodMinutes; numDays++; } if (totMotion == 0 || numDays < MIN_DAYS_REQUIRED) { return Optional.absent(); } final float averageMotionPercentage = ((totMotion / totDuration) * 100.0f); final float overallDiff = (( averageMotionPercentage - AVERAGE_SLEEP_PERC) / AVERAGE_SLEEP_PERC ) * 100.0f; Text text; if (Math.abs(overallDiff) >= SIGNIFICANT_DIFF) { if (overallDiff > 0) { text = SleepMotionMsgEN.moreMovement(numDays, (int) overallDiff, (int) averageMotionPercentage); } else { text = SleepMotionMsgEN.lessMovement(numDays, (int) overallDiff, (int) averageMotionPercentage); } } else { if ((int) overallDiff != 0) { text = SleepMotionMsgEN.equalMovement(numDays, (int) overallDiff, (int) averageMotionPercentage); } else { text = SleepMotionMsgEN.reallyEqualMovement(numDays, (int) overallDiff, (int) averageMotionPercentage); } } return Optional.of(new InsightCard(accountId, text.title, text.message, InsightCard.Category.SLEEP_QUALITY, InsightCard.TimePeriod.RECENTLY, DateTime.now(DateTimeZone.UTC))); }
Source:
<code>public List<RadiologyOrder> getRadiologyOrdersByPatients(List<Patient> patients) { final Criteria radiologyOrderCriteria = createRadiologyOrderCriteria(); addRestrictionOnPatients(radiologyOrderCriteria, patients); <START> List<RadiologyOrder> result = (List<RadiologyOrder>) radiologyOrderCriteria.list(); <END> return result == null ? new ArrayList<RadiologyOrder>() : result; }</code><technical_language>final</technical_language>

Target:
public List<RadiologyOrder> getRadiologyOrdersByPatients(List<Patient> patients) { final Criteria radiologyOrderCriteria = createRadiologyOrderCriteria(); addRestrictionOnPatients(radiologyOrderCriteria, patients); final List<RadiologyOrder> result = (List<RadiologyOrder>) radiologyOrderCriteria.list(); return result == null ? new ArrayList<RadiologyOrder>() : result; }
Source:
<code>public List queryAuditRepositoryOnCriteria(String eUserId, String ePatientId, Date startDate, Date endDate) { LOG.debug("AuditRepositoryDAO.getAuditRepositoryOnCriteria() Begin"); if (eUserId == null && ePatientId == null && startDate == null) { LOG.info("-- No - Input Parameters found for Audit Query --"); LOG.debug("AuditRepositoryDAO.getAuditRepositoryOnCriteria() End"); return null; } Session session = null; List<AuditRepositoryRecord> queryList = null; try { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); session = sessionFactory.openSession(); LOG.info("Getting Record"); Criteria aCriteria = session.createCriteria(AuditRepositoryRecord.class); if (eUserId != null && !eUserId.equals("")) { aCriteria.add(Expression.eq("userId", eUserId)); } if (ePatientId != null && !ePatientId.equals("")) { aCriteria.add(Expression.eq("receiverPatientId", ePatientId)); } if (startDate != null && endDate != null) { aCriteria.add(Expression.between("timeStamp", new Date(startDate.getTime()), new Date(endDate.getTime()))); } else if (startDate != null && endDate == null) { aCriteria.add(Expression.ge("timeStamp", new Date(startDate.getTime()))); } queryList = aCriteria.list(); } catch (HibernateException e) { <START> LOG.error("Exception in AuditLog.get() occured due to :" + e.getLocalizedMessage(), e); <END> } finally { if (session != null) { session.flush(); session.close(); } } LOG.debug("AuditRepositoryDAO.getAuditRepositoryOnCriteria() End"); return queryList; }</code><technical_language>If need another commit this PR, fix this typo? "occurred"</technical_language>

Target:
public List queryAuditRepositoryOnCriteria(String eUserId, String ePatientId, Date startDate, Date endDate) { if (eUserId == null && ePatientId == null && startDate == null) { LOG.info("-- No - Input Parameters found for Audit Query --"); return null; } Session session = null; List<AuditRepositoryRecord> queryList = null; try { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); session = sessionFactory.openSession(); LOG.info("Getting Record"); Criteria aCriteria = session.createCriteria(AuditRepositoryRecord.class); if (eUserId != null && !eUserId.equals("")) { aCriteria.add(Expression.eq("userId", eUserId)); } if (ePatientId != null && !ePatientId.equals("")) { aCriteria.add(Expression.eq("receiverPatientId", ePatientId)); } if (startDate != null && endDate != null) { aCriteria.add(Expression.between("timeStamp", new Date(startDate.getTime()), new Date(endDate.getTime()))); } else if (startDate != null && endDate == null) { aCriteria.add(Expression.ge("timeStamp", new Date(startDate.getTime()))); } queryList = aCriteria.list(); } catch (HibernateException e) { LOG.error("Exception in AuditLog.get() occurred due to :" + e.getLocalizedMessage(), e); } finally { if (session != null) { session.flush(); session.close(); } } return queryList; }
Source:
<code>private void removePropertiesWithExpression(ModelNode newAddOp, List<String> warnings, String... properties) { for (String property : properties) { if (newAddOp.hasDefined(property) && newAddOp.get(property).getType() == EXPRESSION) { if (property.equals(JGROUPS_CHANNEL.getName())) { <START> ModelNode resolvedNode = newAddOp.get(property).resolve(); <END> newAddOp.get(property).set(resolvedNode); } else { newAddOp.remove(property); } warnings.add(ROOT_LOGGER.couldNotMigrateResourceAttributeWithExpression(property, pathAddress(newAddOp.get(OP_ADDR)))); } } }</code><technical_language>1 jgroups-channel jgroups-stack allow expressions in new messaging-activemq. copy them. resolve copy is guarantee resolved DC similar resolved domain servers</technical_language>

Target:
private List<String> removePropertiesWithExpression(ModelNode newAddOp, List<String> warnings, String... properties) { List<String> removed = new ArrayList<>(); for (String property : properties) { if (newAddOp.hasDefined(property) && newAddOp.get(property).getType() == EXPRESSION) { newAddOp.remove(property); warnings.add(ROOT_LOGGER.couldNotMigrateResourceAttributeWithExpression(property, pathAddress(newAddOp.get(OP_ADDR)))); removed.add(property); } } return removed; }
Source:
<code>public synchronized void saveTags(Long sessionData_id, List<TagDto> tags) { List<String> tagNames = new ArrayList<String>(); for (TagDto tagDto : tags) { tagNames.add(tagDto.getName()); } try { entityManager.getTransaction().begin(); if (tagNames.isEmpty()) entityManager.createNativeQuery("delete from SessionTagEntity where sessions_id=:sessionData_id") .setParameter("sessionData_id", sessionData_id) .executeUpdate(); else { entityManager.createNativeQuery("delete from SessionTagEntity where sessions_id=:sessionData_id and tags_name not in (:tagNames)") .setParameter("sessionData_id", sessionData_id) .setParameter("tagNames", tagNames) .executeUpdate(); } <START> if (!tagNames.isEmpty()) { <END> for (String tagStr : tagNames) { entityManager.createNativeQuery( "insert into SessionTagEntity(sessions_id,tags_name) " + "values (:sessionData_id,:tagStr)" + "ON DUPLICATE KEY UPDATE tags_name=:tagStr") .setParameter("sessionData_id", sessionData_id) .setParameter("tagStr", tagStr) .executeUpdate(); } } } finally { entityManager.getTransaction().commit(); } }</code><technical_language>if is here</technical_language>

Target:
public synchronized void saveTags(Long sessionData_id, List<TagDto> tags) { Set<TagEntity> tagEntities = new HashSet<TagEntity>(); SessionData sessionData; for (TagDto tagDto : tags) { tagEntities.add(new TagEntity(tagDto.getName(), tagDto.getDescription())); } try { entityManager.getTransaction().begin(); sessionData = (SessionData) entityManager.createQuery("select sd from SessionData as sd where sd.id = (:sessionData_id)") .setParameter("sessionData_id", sessionData_id) .getSingleResult(); if (sessionData != null) { sessionData.setTags(tagEntities); entityManager.merge(sessionData); entityManager.flush(); } } finally { entityManager.getTransaction().commit(); } }