auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void removePortletDefinition(IPortletDefinition portletDefinition, IPerson person) { IPortletDefinition portletDef = portletDefinitionDao.getPortletDefinition(portletDefinition.getPortletDefinitionId()); String portletDefinitionId = portletDefinition.getPortletDefinitionId().getStringId(); IEntity channelDefEntity = GroupService.getEntity(portletDefinitionId, IPortletDefinition.class); Iterator<IEntityGroup> iter = channelDefEntity.getAncestorGroups().iterator(); while (iter.hasNext()) { IEntityGroup group = iter.next(); group.removeChild(channelDefEntity); group.update(); } AuthorizationService authService = AuthorizationService.instance(); String target = PermissionHelper.permissionTargetIdForPortletDefinition(portletDefinition); IUpdatingPermissionManager upm = authService.newUpdatingPermissionManager(IPermission.PORTAL_SUBSCRIBE); IPermission[] oldPermissions = upm.getPermissionsForTarget(target); upm.removePermissions(oldPermissions); marketplaceRatingDao.clearRatingsForPortlet(portletDef); portletDefinitionDao.deletePortletDefinition(portletDef); }

Target:
public void removePortletDefinition(IPortletDefinition portletDefinition, IPerson person) { IPortletDefinition portletDef = portletDefinitionDao.getPortletDefinition(portletDefinition.getPortletDefinitionId()); String portletDefinitionId = portletDefinition.getPortletDefinitionId().getStringId(); IEntity channelDefEntity = GroupService.getEntity(portletDefinitionId, IPortletDefinition.class); for (IEntityGroup group : channelDefEntity.getAncestorGroups()) { group.removeChild(channelDefEntity); group.update(); } AuthorizationService authService = AuthorizationService.instance(); String target = PermissionHelper.permissionTargetIdForPortletDefinition(portletDefinition); IUpdatingPermissionManager upm = authService.newUpdatingPermissionManager(IPermission.PORTAL_SUBSCRIBE); IPermission[] oldPermissions = upm.getPermissionsForTarget(target); upm.removePermissions(oldPermissions); marketplaceRatingDao.clearRatingsForPortlet(portletDef); portletDefinitionDao.deletePortletDefinition(portletDef); }
Source:
public void testAffiliationVocabTerm() throws Exception { SAXBuilder builder = new SAXBuilder(); Document modsDoc = builder.build(new FileInputStream(new File( "src/test/resources/datastream/inventoryMods.xml"))); when(dip.getMods()).thenReturn(modsDoc.detachRootElement()); Map<String, List<List<String>>> authTerms = new HashMap<String, List<List<String>>>(); List<List<String>> terms = new ArrayList<List<String>>(); List<String> depts = new ArrayList<String>(); depts.add("Music"); terms.add(depts); authTerms.put("<LINK_0>", terms); when(vocabManager.getAuthoritativeForms(any(PID.class), any(Element.class))).thenReturn(authTerms); filter.filter(dip); verify(idb).setDepartment(listCaptor.capture()); assertTrue(listCaptor.getValue().contains("Music")); }

Target:
public void testAffiliationVocabTerm() throws Exception { SAXBuilder builder = new SAXBuilder(); Document modsDoc = builder.build(new FileInputStream(new File( "src/test/resources/datastream/inventoryMods.xml"))); when(dip.getMods()).thenReturn(modsDoc.detachRootElement()); Map<String, List<List<String>>> authTerms = new HashMap<>(); List<List<String>> terms = new ArrayList<>(); List<String> depts = new ArrayList<>(); depts.add("Music"); terms.add(depts); authTerms.put("<LINK_0>", terms); when(vocabManager.getAuthoritativeForms(any(PID.class), any(Element.class))).thenReturn(authTerms); filter.filter(dip); verify(idb).setDepartment(listCaptor.capture()); assertTrue(listCaptor.getValue().contains("Music")); }
Source:
public ValuesSourceConfig( ValuesSourceType valuesSourceType, FieldContext fieldContext, boolean unmapped, AggregationScript.LeafFactory script, ValueType scriptValueType, Object missing, ZoneId timeZone, DocValueFormat format, LongSupplier nowSupplier ) { if (unmapped && fieldContext != null) { throw new IllegalStateException("value source config is invalid; marked as unmapped but specified a mapped field"); } this.valuesSourceType = valuesSourceType; this.fieldContext = fieldContext; this.unmapped = unmapped; this.script = script; this.scriptValueType = scriptValueType; this.missing = missing; this.timeZone = timeZone; this.format = format == null ? DocValueFormat.RAW : format; this.nowSupplier = nowSupplier; if (!valid()) { throw new IllegalStateException( "value source config is invalid; must have either a field context or a script or marked as unwrapped"); } final ValuesSource vs; if (this.unmapped) { vs = valueSourceType().getEmpty(); } else { if (fieldContext() == null) { vs = valueSourceType().getScript(script(), scriptValueType()); } else { vs = valueSourceType().getField(fieldContext(), script()); } } if (missing() != null) { valuesSource = valueSourceType().replaceMissing(vs, missing, format, nowSupplier); } else { valuesSource = vs; } }

Target:
public ValuesSourceConfig( ValuesSourceType valuesSourceType, FieldContext fieldContext, boolean unmapped, AggregationScript.LeafFactory script, ValueType scriptValueType, Object missing, ZoneId timeZone, DocValueFormat format, LongSupplier nowSupplier ) { if (unmapped && fieldContext != null) { throw new IllegalStateException("value source config is invalid; marked as unmapped but specified a mapped field"); } this.valuesSourceType = valuesSourceType; this.fieldContext = fieldContext; this.unmapped = unmapped; this.script = script; this.scriptValueType = scriptValueType; this.missing = missing; this.timeZone = timeZone; this.format = format == null ? DocValueFormat.RAW : format; this.nowSupplier = nowSupplier; if (!valid()) { throw new IllegalStateException( "value source config is invalid; must have either a field context or a script or marked as unwrapped"); } valuesSource = ConstructValuesSource(missing, format, nowSupplier); }
Source:
public Map<Guid, GlusterAsyncTask> getTaskListForCluster(Guid id) { VDS upServer = ClusterUtils.getInstance().getUpServer(id); if (upServer == null) { log.debug("No up server in cluster"); return null; } VDSReturnValue returnValue =runVdsCommand(VDSCommandType.GlusterTasksList, new VdsIdVDSCommandParametersBase(upServer.getId())); if (returnValue.getSucceeded()) { List<GlusterAsyncTask> tasks = (List<GlusterAsyncTask>)returnValue.getReturnValue(); Map<Guid, GlusterAsyncTask> tasksMap = new HashMap<>(); for (GlusterAsyncTask task: tasks) { tasksMap.put(task.getTaskId(),task); } return tasksMap; } else { log.error(returnValue.getVdsError()); return null; } }

Target:
public Map<Guid, GlusterAsyncTask> getTaskListForCluster(Guid id) { VDS upServer = ClusterUtils.getInstance().getUpServer(id); if (upServer == null) { log.info("No up server in cluster"); return null; } VDSReturnValue returnValue =runVdsCommand(VDSCommandType.GlusterTasksList, new VdsIdVDSCommandParametersBase(upServer.getId())); if (returnValue.getSucceeded()) { List<GlusterAsyncTask> tasks = (List<GlusterAsyncTask>)returnValue.getReturnValue(); Map<Guid, GlusterAsyncTask> tasksMap = new HashMap<>(); for (GlusterAsyncTask task: tasks) { tasksMap.put(task.getTaskId(),task); } return tasksMap; } else { log.error(returnValue.getVdsError()); return null; } }
Source:
public static AbstractCheck cloneCheck(AbstractCheck check) { final AbstractCheck clone; if (check instanceof OneCheckInstancePerApplication) { clone = check; } else if (check instanceof OneCheckInstancePerThread) { final ClassLoader classLoader = CheckCloneService.class.getClassLoader(); final ModuleFactory factory = new PackageObjectFactory( Checker.class.getPackage().getName(), classLoader); clone = doCloneCheck(check, factory); clone.init(); } else { if (LOG.isDebugEnabled()) { final String checkClassName = check.getClass().getSimpleName(); final String message = String.format(Locale.ROOT, CHECK_MUST_IMPLEMENT_INTERFACE_MSG, checkClassName); LOG.debug(message); } clone = check; } return clone; }

Target:
public static AbstractCheck cloneCheck(AbstractCheck check) { final AbstractCheck clone; if (check.getClass().isAnnotationPresent(FileStatefulCheck.class)) { clone = doCloneCheck(check); } else if (check.getClass().isAnnotationPresent(StatelessCheck.class) || check.getClass().isAnnotationPresent(GlobalStatefulCheck.class)) { clone = check; } else { final String checkClassName = check.getClass().getSimpleName(); final LocalizedMessage message = new LocalizedMessage(0, Definitions.CHECKSTYLE_BUNDLE, MODULE_MUST_IMPLEMENT_MT_INTERFACE, new String[] {checkClassName}, null, CheckCloneService.class, null); LOG.debug(message.getMessage()); clone = doCloneCheck(check); } return clone; }
Source:
public void testVerificationResourceFields() throws HTTPError { BankAccount bankAccount = createdAssociatedBankAccount(); BankAccountVerification verification = bankAccount.verify(); assertNotNull(verification.attempts); assertNotNull(verification.attempts_remaining); assertNotNull(verification.created_at); assertNotNull(verification.deposit_status); assertNotNull(verification.href); assertNotNull(verification.id); assertNotNull(verification.bank_account); assertNotNull(verification.meta); assertNotNull(verification.updated_at); assertNotNull(verification.verification_status); }

Target:
public void testVerificationResourceFields() throws HTTPError { BankAccount bankAccount = createdAssociatedBankAccount(); BankAccountVerification verification = bankAccount.verify(); assertEquals(verification.attempts.intValue(), 0); assertEquals(verification.attempts_remaining.intValue(), 3); assertNotNull(verification.created_at); assertEquals(verification.deposit_status, "succeeded"); assertTrue(verification.href.contains("/verifications/BZ")); assertTrue(verification.id.contains("BZ")); assertEquals(verification.bank_account.href, bankAccount.href); assertNotNull(verification.updated_at); assertEquals(verification.verification_status, "pending"); }
Source:
public TabletState getState(Set<TServerInstance> liveServers) { if (suspend != null) { return TabletState.SUSPENDED; } TServerInstance server = getServer(); if (server == null) return TabletState.UNASSIGNED; if (server.equals(current) || server.equals(future)) { if (liveServers.contains(server)) if (server.equals(future)) { return TabletState.ASSIGNED; } else { return TabletState.HOSTED; } else { return TabletState.ASSIGNED_TO_DEAD_SERVER; } } return TabletState.UNASSIGNED; }

Target:
public TabletState getState(Set<TServerInstance> liveServers) { switch ((current == null ? 0 : _HAS_CURRENT) | (future == null ? 0 : _HAS_FUTURE) | (suspend == null ? 0 : _HAS_SUSPEND)) { case 0: return TabletState.UNASSIGNED; case _HAS_SUSPEND: return TabletState.SUSPENDED; case _HAS_FUTURE: case (_HAS_FUTURE | _HAS_SUSPEND): return liveServers.contains(future) ? TabletState.ASSIGNED : TabletState.ASSIGNED_TO_DEAD_SERVER; case _HAS_CURRENT: case (_HAS_CURRENT | _HAS_SUSPEND): return liveServers.contains(current) ? TabletState.HOSTED : TabletState.ASSIGNED_TO_DEAD_SERVER; default: throw new IllegalStateException(); } }
Source:
private void prepareRetransmission(final Exchange exchange, final RetransmissionTask task) { if (executor.isShutdown()) { LOGGER.info("Endpoint is being destroyed: skipping retransmission"); return; } exchange.setRetransmissionHandle(null); updateRetransmissionTimeout(exchange); task.message.addMessageObserver(new MessageObserverAdapter() { @Override public void onSent() { task.message.removeMessageObserver(this); if (!exchange.isComplete()) { exchange.execute(new StripedExchangeJob(exchange) { @Override public void runStriped() { task.startTimer(); } }); } } @Override public void onSendError(Throwable error) { exchange.executeComplete(); } }); }

Target:
private void prepareRetransmission(final Exchange exchange, final RetransmissionTask task) { if (executor.isShutdown()) { LOGGER.info("Endpoint is being destroyed: skipping retransmission"); return; } exchange.setRetransmissionHandle(null); updateRetransmissionTimeout(exchange); task.message.addMessageObserver(new MessageObserverAdapter() { @Override public void onSent() { task.message.removeMessageObserver(this); if (!exchange.isComplete()) { exchange.execute(new StripedExchangeJob(exchange) { @Override public void runStriped() { task.startTimer(); } }); } } }); }
Source:
public void testByteBufferRead() throws Exception { prepareData(); doByteBufferRead(jceCipherClass, false); doByteBufferRead(opensslCipherClass, false); doByteBufferRead(jceCipherClass, true); doByteBufferRead(opensslCipherClass, true); }

Target:
public void testByteBufferRead() throws Exception { doByteBufferRead(jceCipherClass, false); doByteBufferRead(opensslCipherClass, false); doByteBufferRead(jceCipherClass, true); doByteBufferRead(opensslCipherClass, true); }
Source:
public void invalidWhenDestinationEndsWithSlash() { assertNotNull(new RefSpec("refs/heads/*:refs/heads/")); }

Target:
public void invalidWhenDestinationEndsWithSlash() { assertNotNull(new RefSpec("refs/heads/master:refs/heads/")); }
Source:
public void onSupportActionModeFinished(ActionMode mode) { mActionMode = null; if (selectedTextView != null) selectedTextView.setWindowFocusWait(false); if (mSelectionModeActive == false) { selectedTextView = null; } super.onSupportActionModeFinished(mode); }

Target:
public void onSupportActionModeFinished(ActionMode mode) { mActionMode = null; if (selectedTextView != null) selectedTextView.setWindowFocusWait(false); if (!selectionModeActive) { selectedTextView = null; } super.onSupportActionModeFinished(mode); }
Source:
public void shouldRecordProcessRatio() { task = createStatelessTask(createConfig(false, "0"), StreamsConfig.METRICS_LATEST); final KafkaMetric metric = getMetric("active-process", "%s-ratio", task.id().toString(), StreamsConfig.METRICS_LATEST); assertEquals(0.0d, (double) metric.metricValue(), 0.0001d); task.recordProcessBatchTime(10L); task.recordProcessBatchTime(15L); task.recordProcessTimeRatioAndBufferSize(100L); assertEquals(0.25d, (double) metric.metricValue(), 0.0001d); task.recordProcessBatchTime(10L); assertEquals(0.25d, (double) metric.metricValue(), 0.0001d); task.recordProcessBatchTime(10L); task.recordProcessTimeRatioAndBufferSize(20L); assertEquals(1.0d, (double) metric.metricValue(), 0.0001d); }

Target:
public void shouldRecordProcessRatio() { task = createStatelessTask(createConfig(false, "0"), StreamsConfig.METRICS_LATEST); final KafkaMetric metric = getMetric("active-process", "%s-ratio", task.id().toString(), StreamsConfig.METRICS_LATEST); assertThat(metric.metricValue(), equalTo(0.0d)); task.recordProcessBatchTime(10L); task.recordProcessBatchTime(15L); task.recordProcessTimeRatioAndBufferSize(100L); assertThat(metric.metricValue(), equalTo(0.25d)); task.recordProcessBatchTime(10L); assertThat(metric.metricValue(), equalTo(0.25d)); task.recordProcessBatchTime(10L); task.recordProcessTimeRatioAndBufferSize(20L); assertThat(metric.metricValue(), equalTo(1.0d)); }
Source:
private void identifyDuplicateFieldDefinitionsForMessages(final List<Message> messages) { final StringBuilder errorMessage = new StringBuilder(); for (final Message message : messages) { final Set<Integer> allFieldsForMessage = new HashSet<>(); identifyDuplicateFieldDefinitionsForMessage( message.name(), message, allFieldsForMessage, new ArrayDeque<>(), errorMessage); } if (errorMessage.length() > 0) { if (!Boolean.getBoolean(CodecGenerationTool.VALIDATION_ALLOW_DUPLICATES)) { throw new IllegalStateException(errorMessage.toString()); } } }

Target:
private void identifyDuplicateFieldDefinitionsForMessages(final List<Message> messages) { final StringBuilder errorMessage = new StringBuilder(); for (final Message message : messages) { final Set<Integer> allFieldsForMessage = new HashSet<>(); identifyDuplicateFieldDefinitionsForMessage( message.name(), message, allFieldsForMessage, new ArrayDeque<>(), errorMessage); } if (errorMessage.length() > 0) { if (!allowDuplicates) { throw new IllegalStateException(String.format( "%sUse -D%s=true to allow duplicated fields (Dangerous. May broke parser).", errorMessage, CodecGenerationTool.FIX_CODECS_ALLOW_DUPLICATE_FIELDS)); } } }
Source:
private void skipBytes(Stack stack, long byteCount) throws IOException, FormatException { boolean hasChunks = stack.chunkLogicalPositions != null; if (!stack.compression && !hasChunks) { in.seek(in.getFilePointer() + byteCount); state.nextReadPosition += byteCount; } else if (stack.compression) { if (skipBuffer == null) { skipBuffer = new byte[8192]; } while (byteCount > 0) { int readSize = (int)Math.min(skipBuffer.length, byteCount); readFromStack(stack, skipBuffer, 0, readSize); byteCount -= readSize; } } else { long remainingBytesInChunk = remainingBytesInChunk(stack); while (byteCount > 0) { while (remainingBytesInChunk == 0) { switchChunk(stack, state.currentChunk + 1); in.seek(state.chunkFileStart); remainingBytesInChunk = remainingBytesInChunk(stack); } long skipSize = Math.min(remainingBytesInChunk, byteCount); in.seek(in.getFilePointer() + skipSize); byteCount -= skipSize; remainingBytesInChunk -= skipSize; } } }

Target:
private void skipBytes(Stack stack, long byteCount) throws IOException, FormatException { boolean hasChunks = stack.chunkLogicalPositions != null; if (!stack.compression && !hasChunks) { in.skipBytes(byteCount); state.nextReadPosition += byteCount; } else if (stack.compression) { if (skipBuffer == null) { skipBuffer = new byte[8192]; } while (byteCount > 0) { int readSize = (int)Math.min(skipBuffer.length, byteCount); readFromStack(stack, skipBuffer, 0, readSize); byteCount -= readSize; } } else { while(byteCount > 0) { int skipSize = (int)Math.min(byteCount, Integer.MAX_VALUE); readFromStackRaw(stack, null, 0, skipSize); byteCount -= skipSize; } } }
Source:
public void run(IResources resources, IAnathemaModel anathemaModel, IAnathemaView view) { File legacyDatabaseFile = new File( anathemaModel.getRepository().getRepositoryPath() + "equipment/Equipment.yap" ); database = GsonEquipmentDatabase.CreateFrom(anathemaModel); EquipmentGson gson = new EquipmentGson(); if( !legacyDatabaseFile.exists() && isDatabaseEmpty() ) { ProxySplashscreen.getInstance().displayStatusMessage( resources.getString("Equipment.Bootjob.DefaultDatabaseSplashmessage")); try { ZipInputStream jarFile = new ZipInputStream( new BufferedInputStream( getJarFileLocation().openStream() ) ); ZipEntry file; while( (file = jarFile.getNextEntry()) != null ) { if( file.getName().matches( EQUIPMENT_REGEX ) ){ String itemJSON = getStringFromStream( jarFile ); database.saveTemplate( gson.fromJson( itemJSON ) ); } } } catch ( IOException e ) { throw new RuntimeException("Could not create default database."); } catch ( NoSuchElementException e ) { throw new RuntimeException("Could not create default database."); } } }

Target:
public void run(IResources resources, IAnathemaModel anathemaModel, IAnathemaView view) { File legacyDatabaseFile = new File( anathemaModel.getRepository().getRepositoryPath(), "equipment" + File.separatorChar + "Equipment.yap" ); database = GsonEquipmentDatabase.CreateFrom(anathemaModel); EquipmentGson gson = new EquipmentGson(); if( !legacyDatabaseFile.exists() && isDatabaseEmpty() ) { ProxySplashscreen.getInstance().displayStatusMessage( resources.getString("Equipment.Bootjob.DefaultDatabaseSplashmessage")); try { for( IAnathemaResourceFile file : anathemaModel.getReflections().getResourcesMatching( EQUIPMENT_REGEX ) ) { String itemJSON = getStringFromStream( file.getURL().openStream() ); database.saveTemplateNoOverwrite( gson.fromJson( itemJSON ) ); } } catch ( IOException e ) { throw new RuntimeException("Could not create default database."); } } }
Source:
private static boolean copyFile(String sourceFileName, String destinationFileName) { File sourceFile = new File(sourceFileName); File destinationFile = new File(destinationFileName); LOG.debug("copy file from-to: {}, {}", sourceFileName, destinationFileName); if (sourceFile.exists()) { try { org.apache.commons.io.FileUtils.copyFile(sourceFile, destinationFile, false); LOG.info("copy successful: {}", destinationFileName); gatewayNew = null; return true; } catch (IOException e) { LOG.error("error while copy: {}", destinationFileName, e); } } else { LOG.error("error while copy source not found: {}", sourceFileName); } return false; }

Target:
private static boolean copyFile(String sourceFileName, String destinationFileName) { File sourceFile = new File(sourceFileName); File destinationFile = new File(destinationFileName); LOG.debug("copy file from-to: {}, {}", sourceFileName, destinationFileName); if (sourceFile.exists()) { try { FileUtils.copyFile(sourceFile, destinationFile, false); LOG.info("copy successful: {}", destinationFileName); return true; } catch (IOException e) { LOG.error("error while copy: {}", destinationFileName, e); } } else { LOG.error("error while copy source not found: {}", sourceFileName); } return false; }
Source:
public synchronized void close(Handler<AsyncResult<Void>> completionHandler) { if (closed || eventBus == null) { if (completionHandler != null) { completionHandler.handle(Future.succeededFuture()); } return; } closed = true; closeHooks.run(ar -> { deploymentManager.undeployAll(ar1 -> { this.executeBlocking(fut -> { if (haManager() != null) { haManager().stop(); } fut.complete(); }, false, ar2 -> { addressResolver.close(ar3 -> { eventBus.close(ar4 -> { closeClusterManager(ar5 -> { Set<HttpServer> httpServers = new HashSet<>(sharedHttpServers.values()); Set<NetServerImpl> netServers = new HashSet<>(sharedNetServers.values()); sharedHttpServers.clear(); sharedNetServers.clear(); int serverCount = httpServers.size() + netServers.size(); AtomicInteger serverCloseCount = new AtomicInteger(); Handler<AsyncResult<Void>> serverCloseHandler = res -> { if (res.failed()) { log.error("Failure in shutting down server", res.cause()); } if (serverCloseCount.incrementAndGet() == serverCount) { deleteCacheDirAndShutdown(completionHandler); } }; for (HttpServer server : httpServers) { server.close(serverCloseHandler); } for (NetServerImpl server : netServers) { server.close(serverCloseHandler); } if (serverCount == 0) { deleteCacheDirAndShutdown(completionHandler); } }); }); }); }); }); }); }

Target:
public synchronized void close(Handler<AsyncResult<Void>> completionHandler) { if (closed || eventBus == null) { if (completionHandler != null) { completionHandler.handle(Future.succeededFuture()); } return; } closed = true; closeHooks.run(ar -> { deploymentManager.undeployAll(ar1 -> { HAManager haManager = haManager(); Future<Void> haFuture = Future.future(); if (haManager != null) { this.executeBlocking(fut -> { haManager.stop(); fut.complete(); }, false, haFuture); } else { haFuture.complete(); } haFuture.setHandler(ar2 -> { addressResolver.close(ar3 -> { eventBus.close(ar4 -> { closeClusterManager(ar5 -> { Set<HttpServer> httpServers = new HashSet<>(sharedHttpServers.values()); Set<NetServerImpl> netServers = new HashSet<>(sharedNetServers.values()); sharedHttpServers.clear(); sharedNetServers.clear(); int serverCount = httpServers.size() + netServers.size(); AtomicInteger serverCloseCount = new AtomicInteger(); Handler<AsyncResult<Void>> serverCloseHandler = res -> { if (res.failed()) { log.error("Failure in shutting down server", res.cause()); } if (serverCloseCount.incrementAndGet() == serverCount) { deleteCacheDirAndShutdown(completionHandler); } }; for (HttpServer server : httpServers) { server.close(serverCloseHandler); } for (NetServerImpl server : netServers) { server.close(serverCloseHandler); } if (serverCount == 0) { deleteCacheDirAndShutdown(completionHandler); } }); }); }); }); }); }); }
Source:
private void writeFileParameter(@NonNull final Parameter param) throws IOException { mOut.writeBytes(PREFIX); mOut.writeBytes(mBoundary); mOut.writeBytes(NEWLINE); final String fileName = param.mFileName != null ? param.mFileName : param.mFile != null ? param.mFile.getName() : ""; mOut.writeBytes("Content-Disposition: form-data; name=\"" + param.mName + "\"; filename=\"" + fileName + "\""); mOut.writeBytes(NEWLINE); final MediaType type = param.mType != null ? param.mType : MediaType.APPLICATION_OCTET_STREAM; mOut.writeBytes("Content-Type: " + type.mType); mOut.writeBytes(NEWLINE); mOut.writeBytes(NEWLINE); if (param.mFile != null) { final Closer closer = Closer.create(); try { final InputStream in = closer.register(new FileInputStream(param.mFile)); IOUtils.copy(in, mOut); } catch (final Throwable t) { throw closer.rethrow(t); } finally { closer.close(); } } mOut.writeBytes(NEWLINE); }

Target:
private void writeFileParameter(@NonNull final Parameter param) throws IOException { mOut.writeBytes(PREFIX); mOut.writeBytes(mBoundary); mOut.writeBytes(NEWLINE); String fileName = param.mFileName; if (fileName == null && param.mFile != null) { fileName = param.mFile.getName(); } if (fileName == null) { fileName = ""; } mOut.writeBytes("Content-Disposition: form-data; name=\"" + param.mName + "\"; filename=\"" + fileName + "\""); mOut.writeBytes(NEWLINE); final MediaType type = param.mType != null ? param.mType : MediaType.APPLICATION_OCTET_STREAM; mOut.writeBytes("Content-Type: " + type.mType); mOut.writeBytes(NEWLINE); mOut.writeBytes(NEWLINE); if (param.mFile != null) { final Closer closer = Closer.create(); try { final InputStream in = closer.register(new FileInputStream(param.mFile)); IOUtils.copy(in, mOut); } catch (final Throwable t) { throw closer.rethrow(t); } finally { closer.close(); } } mOut.writeBytes(NEWLINE); }
Source:
public void exec(final Shell shell) throws IOException { final String dir = FilenameUtils.getFullPathNoEndSeparator(this.path); final String mask = FilenameUtils.getName(this.path); final String url = String.format( "<LINK_0>", this.bucket, this.prefix ); final int files = new Terminal(shell).exec( new StringBuilder() .append("CONFIG=$(mktemp /tmp/s3cmdput-XXXX)") .append(" && cat > $CONFIG") .append(" && HEAD=") .append( Terminal.quotate( Terminal.escape( String.format( "s3://%s/%s", this.bucket, this.prefix ) ) ) ) .append(" && cd ") .append(Terminal.quotate(Terminal.escape(dir))) .append(" && if [ -e ").append(mask).append(" ];then") .append(" FILES=$(find ").append(mask).append(" -type f)") .append(" && for f in $FILES; do s3cmd --config=$CONFIG put $f \"$HEAD$f\" > /dev/null && echo $f; done; fi") .toString(), new StringBuilder() .append("[default]\n") .append("access_key=").append(this.key).append('\n') .append("secret_key=").append(this.secret).append('\n') .toString() ).split("\n").length; if (mask.contains("*")) { final String href = String.format("%sindex.html", url); this.tag(String.format("see [%d files](%s)", files, href), href); } else { final String href = String.format("%s%s", url, mask); this.tag(String.format("see [%s](%s) file", mask, href), href); } }

Target:
public void exec(final Shell shell) throws IOException { final String dir = FilenameUtils.getFullPathNoEndSeparator(this.path); final String mask = FilenameUtils.getName(this.path); final String url = String.format( "<LINK_0>", this.bucket, this.prefix ); final int files = new Terminal(shell).exec( new StringBuilder() .append("CONFIG=$(mktemp /tmp/s3cmdput-XXXX)") .append(" && cat > $CONFIG") .append(" && HEAD=") .append( Terminal.quotate( Terminal.escape( String.format( "s3://%s/%s", this.bucket, this.prefix ) ) ) ) .append(" && cd ") .append(Terminal.quotate(Terminal.escape(dir))) .append(" && if [ -e ").append(mask).append(" ];then") .append(" FILES=$(find ").append(mask).append(" -type f)") .append(" && for f in $FILES; do s3cmd --config=$CONFIG put $f \"$HEAD$f\" > /dev/null && echo $f; done;") .append(" else echo No files found by mask ").append(mask) .append("; fi;") .toString(), new StringBuilder() .append("[default]\n") .append("access_key=").append(this.key).append('\n') .append("secret_key=").append(this.secret).append('\n') .toString() ).split("\n").length; if (mask.contains("*")) { final String href = String.format("%sindex.html", url); this.tag(String.format("see [%d files](%s)", files, href), href); } else { final String href = String.format("%s%s", url, mask); this.tag(String.format("see [%s](%s) file", mask, href), href); } }
Source:
public void createFullTextResource() throws IOException, JsonParseException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { ResponseEntity<String> response = storeTestAnnotation(FULL_TEXT_RESOURCE); validateResponse(response); Annotation storedAnno = getApiClient().parseResponseBody(response); assertEquals(storedAnno.getBody().getInternalType(), ResourceTypes.FULL_TEXT_RESOURCE.name()); }

Target:
public void createFullTextResource() throws IOException, JsonParseException, IllegalAccessException, IllegalArgumentException, InvocationTargetException { ResponseEntity<String> response = storeTestAnnotation(FULL_TEXT_RESOURCE); validateResponse(response); Annotation storedAnno = getApiClient().parseResponseBody(response); assertEquals(storedAnno.getBody().getInternalType(), ResourceTypes.FULL_TEXT_RESOURCE.name()); assertTrue(storedAnno.getBody().getValue().equals(FULL_TEXT_RESOURCE_VALUE)); }
Source:
public void testCustomCleaner() throws Exception { deployContrib("org.nuxeo.ecm.platform.query.api.test", "configuration-test-contrib.xml"); applyInlineDeployments(); ConfigurationService cs = Framework.getService(ConfigurationService.class); String s = cs.getProperty(NXQLQueryBuilder.IGNORED_CHARS_KEY); assertEquals("&/{}()", s); assertNotNull(s); assertEquals("= 'a $ b'", NXQLQueryBuilder.serializeFullText("a $ b")); assertEquals("= '10.3'", NXQLQueryBuilder.serializeFullText("10.3")); }

Target:
public void testCustomCleaner() throws Exception { pushInlineDeployments("org.nuxeo.ecm.platform.query.api.test:configuration-test-contrib.xml"); ConfigurationService cs = Framework.getService(ConfigurationService.class); String s = cs.getProperty(NXQLQueryBuilder.IGNORED_CHARS_KEY); assertEquals("&/{}()", s); assertNotNull(s); assertEquals("= 'a $ b'", NXQLQueryBuilder.serializeFullText("a $ b")); assertEquals("= '10.3'", NXQLQueryBuilder.serializeFullText("10.3")); }
Source:
private void addTaskAndResolveOrphans(ITmfStateSystemBuilder ssb, TaskContainerEvent t) { processTaskEvent(ssb, t); setTaskCPUStatus(ssb, t); boolean retryUnresolvedTasks = false; do { retryUnresolvedTasks = false; for (Iterator<TaskContainerEvent> iterator = unresolvedTasks.iterator(); iterator.hasNext();) { final TaskContainerEvent orphan = iterator.next(); if (orphan == null) { iterator.remove(); continue; } if (isParentContainerAdded(ssb, orphan)) { processTaskEvent(ssb, orphan); setTaskCPUStatus(ssb, t); iterator.remove(); retryUnresolvedTasks = true; } } } while (retryUnresolvedTasks); }

Target:
private void addTaskAndResolveOrphans(ITmfStateSystemBuilder ssb, TaskContainerEvent t) { processTaskEvent(ssb, t); setTaskCPUStatus(ssb, t); boolean retryUnresolvedTasks = false; do { retryUnresolvedTasks = false; List<TaskContainerEvent> stillUnresolvedTasks = new LinkedList<>(); for (TaskContainerEvent orphan : unresolvedTasks) { if (isParentContainerAdded(ssb, orphan)) { processTaskEvent(ssb, orphan); setTaskCPUStatus(ssb, t); retryUnresolvedTasks = true; } else { stillUnresolvedTasks.add(orphan); } } unresolvedTasks = stillUnresolvedTasks; } while (retryUnresolvedTasks); }
Source:
public CcmV2Parameters getCcmV2Parameters(@Nonnull String accountId, @Nonnull String clusterGatewayDomain, @Nonnull String agentKeyId) { String requestId = Optional.ofNullable(MDCBuilder.getMdcContextMap().get(LoggerContextKey.REQUEST_ID.toString())).orElse(UUID.randomUUID().toString()); MDCBuilder.addRequestId(requestId); InvertingProxy invertingProxy = ccmV2Client.awaitReadyInvertingProxyForAccount(requestId, accountId); InvertingProxyAgent invertingProxyAgent = ccmV2Client.registerInvertingProxyAgent(requestId, accountId, clusterGatewayDomain, agentKeyId); checkArgument(StringUtils.isNotEmpty(invertingProxy.getHostname()), "InvertingProxy Hostname is not initialized."); checkArgument(StringUtils.isNotEmpty(invertingProxy.getCertificate()), "InvertingProxy Certificate is not initialized."); checkArgument(StringUtils.isNotEmpty(invertingProxyAgent.getAgentCrn()), "InvertingProxyAgent Crn is not initialized."); checkArgument(StringUtils.isNotEmpty(invertingProxyAgent.getEncipheredPrivateKey()), "InvertingProxyAgent Enciphered Key is not initialized."); checkArgument(StringUtils.isNotEmpty(invertingProxyAgent.getCertificate()), "InvertingProxyAgent Certificate is not initialized."); LOGGER.debug("CcmV2Config successfully retrieved InvertingProxyHost : '{}', InvertingProxyStatus : '{}' InvertingProxyAgentCrn '{}'", invertingProxy.getHostname(), invertingProxy.getStatus(), invertingProxyAgent.getAgentCrn()); return new DefaultCcmV2Parameters(invertingProxy.getHostname(), invertingProxy.getCertificate(), invertingProxyAgent.getAgentCrn(), agentKeyId, invertingProxyAgent.getEncipheredPrivateKey(), invertingProxyAgent.getCertificate()); }

Target:
public CcmV2Parameters getCcmV2Parameters(@Nonnull String accountId, @Nonnull String clusterGatewayDomain, @Nonnull String agentKeyId) { String requestId = MDCBuilder.getOrGenerateRequestId(); InvertingProxy invertingProxy = ccmV2Client.awaitReadyInvertingProxyForAccount(requestId, accountId); InvertingProxyAgent invertingProxyAgent = ccmV2Client.registerInvertingProxyAgent(requestId, accountId, clusterGatewayDomain, agentKeyId); validateCcmV2ConfigResponse(invertingProxy, invertingProxyAgent); LOGGER.debug("CcmV2Config successfully retrieved InvertingProxyHost : '{}', InvertingProxyStatus : '{}' InvertingProxyAgentCrn '{}'", invertingProxy.getHostname(), invertingProxy.getStatus(), invertingProxyAgent.getAgentCrn()); return new DefaultCcmV2Parameters(invertingProxy.getHostname(), invertingProxy.getCertificate(), invertingProxyAgent.getAgentCrn(), agentKeyId, invertingProxyAgent.getEncipheredPrivateKey(), invertingProxyAgent.getCertificate()); }
Source:
@Test public void getUrlAndUrlParamThrows() { class Example { @GET("foo/bar") Call<Object> method(@Url Object url) { return null; } } try { buildRequest(Example.class, "foo/bar"); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("@Url must be String type. (parameter #1)\n" + " for method Example.method"); } }

Target:
@Test public void getUrlAndUrlParamThrows() { class Example { @GET("foo/bar") Call<Object> method(@Url Object url) { return null; } } try { buildRequest(Example.class, "foo/bar"); fail(); } catch (IllegalArgumentException e) { assertThat(e).hasMessage("@Url must be String type. (parameter #1)\n" + " for method Example.method"); } }
Source:
public final void cleanExpiredUsersSessions() { Date now = new Date(); Iterator<SessionInfo> iterator = sessionInfoList.iterator(); while (iterator.hasNext()) { ConcurrentMap<String, Object> sessionMap = iterator.next().sessionMap; Date hardLimit = (Date) sessionMap.get(HARD_LIMIT_PARAMETER_NAME); Date softLimit = (Date) sessionMap.get(SOFT_LIMIT_PARAMETER_NAME); if (hardLimit != null) { if (hardLimit.before(now)) { iterator.remove(); } } else if (softLimit != null) { if (softLimit.before(now)) { iterator.remove(); } } } }

Target:
public final void cleanExpiredUsersSessions() { Date now = new Date(); Iterator<SessionInfo> iterator = sessionInfoList.iterator(); while (iterator.hasNext()) { ConcurrentMap<String, Object> sessionMap = iterator.next().sessionMap; Date hardLimit = (Date) sessionMap.get(HARD_LIMIT_PARAMETER_NAME); Date softLimit = (Date) sessionMap.get(SOFT_LIMIT_PARAMETER_NAME); if (hardLimit != null) { if (hardLimit.before(now)) { iterator.remove(); } } if (softLimit != null) { if (softLimit.before(now)) { iterator.remove(); } } } }
Source:
private void initializeLookupsConfigWatcher() { lookupMapConfigRef = configManager.watch( LOOKUP_CONFIG_KEY, new TypeReference<Map<String, Map<String, LookupExtractorFactoryMapContainer>>>() { }, null ); if (lookupMapConfigRef.get() == null) { Map<String, Map<String, Map<String, Object>>> oldLookups = configManager.watch( OLD_LOOKUP_CONFIG_KEY, new TypeReference<Map<String, Map<String, Map<String, Object>>>>() { }, null ).get(); if (oldLookups != null) { Map<String, Map<String, LookupExtractorFactoryMapContainer>> converted = new HashMap<>(); for (Map.Entry<String, Map<String, Map<String, Object>>> tierEntry : oldLookups.entrySet()) { Map<String, Map<String, Object>> oldTierLookups = tierEntry.getValue(); if (oldTierLookups != null && !oldTierLookups.isEmpty()) { Map<String, LookupExtractorFactoryMapContainer> convertedTierLookups = new HashMap<>(); for (Map.Entry<String, Map<String, Object>> e : oldTierLookups.entrySet()) { convertedTierLookups.put(e.getKey(), new LookupExtractorFactoryMapContainer(null, e.getValue())); } converted.put(tierEntry.getKey(), convertedTierLookups); } } configManager.set( LOOKUP_CONFIG_KEY, converted, new AuditInfo("autoConversion", "autoConversion", "127.0.0.1") ); } } }

Target:
private void initializeLookupsConfigWatcher() { lookupMapConfigRef = configManager.watch( LOOKUP_CONFIG_KEY, new TypeReference<Map<String, Map<String, LookupExtractorFactoryMapContainer>>>() { }, null ); if (lookupMapConfigRef.get() == null) { Map<String, Map<String, Map<String, Object>>> oldLookups = configManager.watch( OLD_LOOKUP_CONFIG_KEY, new TypeReference<Map<String, Map<String, Map<String, Object>>>>() { }, null ).get(); if (oldLookups != null) { Map<String, Map<String, LookupExtractorFactoryMapContainer>> converted = new HashMap<>(); oldLookups.forEach( (tier, oldTierLookups) -> { if (oldTierLookups != null && !oldTierLookups.isEmpty()) { converted.put(tier, convertTierLookups(oldTierLookups)); } } ); configManager.set( LOOKUP_CONFIG_KEY, converted, new AuditInfo("autoConversion", "autoConversion", "127.0.0.1") ); } } }
Source:
public int compareTypeSafe(Value v, CompareMode mode) { return 0; }

Target:
public int compareTypeSafe(Value v, CompareMode mode) { JsonNode other = ((ValueJson) v).json; if (this.json.equals(other)) { return 0; } if ((this.json.isNumber()) && other.isNumber()) { double d1 = this.json.asDouble(); double d2 = other.asDouble(); return Double.compare(d1, d2); } int comp = this.json.asText().compareTo(other.asText()); if (comp == 0) { return Integer.compare(this.json.hashCode(), other.hashCode()); } return comp; }
Source:
public String asCql() { StringBuilder builder = new StringBuilder("INSERT INTO "); CqlHelper.qualify(keyspace, table, builder); if (json == null) { CqlHelper.appendIds(assignments.keySet(), builder, " (", ",", ")"); CqlHelper.append(assignments.values(), builder, " VALUES (", ",", ")"); } else { builder.append(" JSON "); json.appendTo(builder); if (missingJsonBehavior == MissingJsonBehavior.NULL) { builder.append(" DEFAULT NULL"); } else if (missingJsonBehavior == MissingJsonBehavior.UNSET) { builder.append(" DEFAULT UNSET"); } } if (ifNotExists) { builder.append(" IF NOT EXISTS"); } if (timestamp != null) { builder.append(" USING TIMESTAMP "); if (timestamp instanceof BindMarker) { ((BindMarker) timestamp).appendTo(builder); } else { builder.append(timestamp); } } if (ttl != null) { builder.append(" USING TTL "); if (ttl instanceof BindMarker) { ((BindMarker) ttl).appendTo(builder); } else { builder.append(ttl); } } return builder.toString(); }

Target:
public String asCql() { StringBuilder builder = new StringBuilder("INSERT INTO "); CqlHelper.qualify(keyspace, table, builder); if (json == null) { CqlHelper.appendIds(assignments.keySet(), builder, " (", ",", ")"); CqlHelper.append(assignments.values(), builder, " VALUES (", ",", ")"); } else { builder.append(" JSON "); json.appendTo(builder); if (missingJsonBehavior == MissingJsonBehavior.NULL) { builder.append(" DEFAULT NULL"); } else if (missingJsonBehavior == MissingJsonBehavior.UNSET) { builder.append(" DEFAULT UNSET"); } } if (ifNotExists) { builder.append(" IF NOT EXISTS"); } if (timestamp != null) { builder.append(" USING TIMESTAMP "); if (timestamp instanceof BindMarker) { ((BindMarker) timestamp).appendTo(builder); } else { builder.append(timestamp); } } if (ttlInSeconds != null) { builder.append((timestamp != null) ? " AND " : " USING ").append("TTL "); if (ttlInSeconds instanceof BindMarker) { ((BindMarker) ttlInSeconds).appendTo(builder); } else { builder.append(ttlInSeconds); } } return builder.toString(); }
Source:
public void update() throws BankException, LoginException, BankChoiceException, IOException { super.update(); if (username == null || password == null || username.length() == 0 || password.length() == 0) { throw new LoginException(res.getText(R.string.invalid_username_password).toString()); } urlopen = login(); String response = null; Matcher matcher; try { response = urlopen.open("<LINK_0>"); matcher = reAccounts.matcher(response); int accId = 0; while (matcher.find()) { mIdMappings.put(Integer.toString(accId), matcher.group(2).trim()); accounts.add(new Account(Html.fromHtml(matcher.group(1)).toString().trim() + " (Tillgängligt belopp)", Helpers.parseBalance(matcher.group(5).trim()), Integer.toString(accId))); Account account = new Account(Html.fromHtml(matcher.group(1)).toString().trim() + " (Saldo)", Helpers.parseBalance(matcher.group(6).trim()), "a:" + accId); account.setAliasfor(matcher.group(1).trim()); accounts.add(account); balance = balance.add(Helpers.parseBalance(matcher.group(5))); accId++; } if (accounts.isEmpty()) { throw new BankException(res.getText(R.string.no_accounts_found).toString()); } } finally { super.updateComplete(); } }

Target:
public void update() throws BankException, LoginException, BankChoiceException, IOException { super.update(); if (username == null || password == null || username.length() == 0 || password.length() == 0) { throw new LoginException(res.getText(R.string.invalid_username_password).toString()); } urlopen = login(); String response = urlopen.open("<LINK_0>"); Matcher matcher = reAccounts.matcher(response); int accId = 0; while (matcher.find()) { mIdMappings.put(Integer.toString(accId), matcher.group(2).trim()); accounts.add(new Account(Html.fromHtml(matcher.group(1)).toString().trim() + " (Tillgängligt belopp)", Helpers.parseBalance(matcher.group(5).trim()), Integer.toString(accId))); Account account = new Account(Html.fromHtml(matcher.group(1)).toString().trim() + " (Saldo)", Helpers.parseBalance(matcher.group(6).trim()), "a:" + accId); account.setAliasfor(matcher.group(1).trim()); accounts.add(account); balance = balance.add(Helpers.parseBalance(matcher.group(5))); accId++; } if (accounts.isEmpty()) { throw new BankException(res.getText(R.string.no_accounts_found).toString()); } super.updateComplete(); }
Source:
public void getAttributesByNames() throws Exception { System.out.println(CLASS_NAME + "getAttributesByNames"); cacheManager.newNestedTransaction(); Attribute groupAttr = setUpGroupAttribute(); AttributeDefinition groupAttrDef = setUpGroupAttributeDefinition(); cacheManager.setAttribute(groupAttr, groupHolder, null); List<String> attributeNames = new ArrayList<>(); attributeNames.add(groupAttr.getName()); attributeNames.add(groupAttrDef.getName()); List<Attribute> attrs = cacheManager.getAttributesByNames(attributeNames, groupHolder, null); assertTrue("result should contain group attribute", attrs.contains(groupAttr)); assertTrue("result should contain group attribute definition", attrs.contains(new Attribute(groupAttrDef))); assertTrue("it should return 2 attributes", attrs.size() == 2); cacheManager.removeAttribute(groupAttr, groupHolder, null); attrs = cacheManager.getAttributesByNames(attributeNames, groupHolder, null); assertTrue("result should not contain group attribute", !attrs.contains(groupAttr)); assertTrue("result should contain group attribute definition", attrs.contains(new Attribute(groupAttrDef))); assertTrue("it should return 2 attribute definitions", attrs.size() == 2); cacheManager.flushNestedTransaction(); attrs = cacheManager.getAttributesByNames(attributeNames, groupHolder, null); assertTrue("result should not contain group attribute", !attrs.contains(groupAttr)); assertTrue("result should contain group attribute definition", attrs.contains(new Attribute(groupAttrDef))); assertTrue("it should return 2 attribute definitions", attrs.size() == 2); }

Target:
public void getAttributesByNames() throws Exception { System.out.println(CLASS_NAME + "getAttributesByNames"); cacheManager.newNestedTransaction(); Attribute groupAttr = setUpGroupAttribute(); AttributeDefinition groupAttrDef = setUpGroupAttributeDefinition(); cacheManager.setAttribute(groupAttr, groupHolder, null); List<String> attributeNames = new ArrayList<>(); attributeNames.add(groupAttr.getName()); attributeNames.add(groupAttrDef.getName()); List<Attribute> attrs = cacheManager.getAttributesByNames(attributeNames, groupHolder, null); assertTrue("result should contain group attribute", attrs.contains(groupAttr)); assertTrue("result should contain group attribute definition", attrs.contains(groupAttrDef)); assertTrue("it should return 2 attributes", attrs.size() == 2); cacheManager.removeAttribute(groupAttr, groupHolder, null); attrs = cacheManager.getAttributesByNames(attributeNames, groupHolder, null); assertTrue("result should not contain group attribute", !attrs.contains(groupAttr)); assertTrue("result should contain group attribute definition", attrs.contains(groupAttrDef)); assertTrue("it should return 2 attribute definitions", attrs.size() == 2); cacheManager.flushNestedTransaction(); attrs = cacheManager.getAttributesByNames(attributeNames, groupHolder, null); assertTrue("result should not contain group attribute", !attrs.contains(groupAttr)); assertTrue("result should contain group attribute definition", attrs.contains(groupAttrDef)); assertTrue("it should return 2 attribute definitions", attrs.size() == 2); }
Source:
public void update(PhysicalPlanHelper physicalPlanHelper) { if (bolt instanceof IUpdatable) { ((IUpdatable) bolt).update(physicalPlanHelper.getTopologyContext()); } }

Target:
public void update(PhysicalPlanHelper physicalPlanHelper) { if (bolt instanceof IUpdatable) { ((IUpdatable) bolt).update(physicalPlanHelper.getTopologyContext()); } collector.updatePhysicalPlanHelper(physicalPlanHelper); }
Source:
private static WebElement findElement(Hook hook, WebDriver driver) throws CandybeanException { try { return driver.findElement(getBy(hook)); } catch (NoSuchElementException e) { throw e; } catch (WebDriverException e) { throw e; } }

Target:
private static WebElement findElement(Hook hook, WebDriver driver) throws CandybeanException { try { return driver.findElement(getBy(hook)); } catch (WebDriverException e) { throw e; } }
Source:
public void delete(Long id) { Form form = formsRepository.get(id); List<Instance> instances = instancesRepository.getAllByJrFormId(form.getJrFormId()); long instancesForVersion = instances.stream().filter(instance -> Objects.equals(instance.getJrVersion(), form.getJrVersion())).count(); if (instancesForVersion > 0) { formsRepository.softDelete(form.getId()); } else { formsRepository.delete(id); } }

Target:
public void delete(Long id) { Form form = formsRepository.get(id); List<Instance> instancesForVersion = instancesRepository.getAllByJrFormIdAndJrVersion(form.getJrFormId(), form.getJrVersion()); if (instancesForVersion.isEmpty()) { formsRepository.delete(id); } else { formsRepository.softDelete(form.getId()); } }
Source:
private static void show(JComponent... components) { for (JComponent component : components) { component.setVisible(true); component.getParent().invalidate(); component.getParent().getParent().invalidate(); } }

Target:
private static void show(JComponent... components) { for (JComponent component : components) { component.setVisible(true); component.getParent().invalidate(); } }
Source:
public JdbcTaskExecutionDao(DataSource dataSource) { Assert.notNull(dataSource, "The dataSource must not be null."); this.jdbcTemplate = new JdbcTemplate(dataSource); this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(this.jdbcTemplate); this.dataSource = dataSource; orderMap = new LinkedHashMap<>(); orderMap.put("START_TIME", Order.DESCENDING); orderMap.put("TASK_EXECUTION_ID", Order.DESCENDING); }

Target:
public JdbcTaskExecutionDao(DataSource dataSource) { Assert.notNull(dataSource, "The dataSource must not be null."); this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource); this.dataSource = dataSource; orderMap = new LinkedHashMap<>(); orderMap.put("START_TIME", Order.DESCENDING); orderMap.put("TASK_EXECUTION_ID", Order.DESCENDING); }