auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public Boolean call() { try { long start = 0; if (logger.isInfoEnabled()) { start = System.currentTimeMillis(); logger.info("Removing job " + jobId); } SchedulerDBManager dbManager = service.getInfrastructure().getDBManager(); List<InternalJob> jobs = dbManager.loadJobWithTasksIfNotRemoved(jobId); TerminationData terminationData; if (jobs.size() != 1) { terminationData = service.getJobs().removeJob(jobId); } else { if (isInFinishedState(jobs.get(0))) { terminationData = service.getJobs().removeJob(jobId); } else { terminationData = service.getJobs().killJob(jobId); } } service.submitTerminationDataHandler(terminationData); if (jobs.size() != 1) { return false; } InternalJob job = jobs.get(0); job.setRemovedTime(System.currentTimeMillis()); boolean removeFromDb = PASchedulerProperties.JOB_REMOVE_FROM_DB.getValueAsBoolean(); dbManager.removeJob(jobId, jobs.get(0).getRemovedTime(), removeFromDb); ServerJobAndTaskLogs.getInstance().remove(jobId, job.getOwner()); if (logger.isInfoEnabled()) { logger.info("Job " + jobId + " removed in " + (System.currentTimeMillis() - start) + "ms"); } service.getListener() .jobStateUpdated(job.getOwner(), new NotificationData<JobInfo>(SchedulerEvent.JOB_REMOVE_FINISHED, new JobInfoImpl((JobInfoImpl) job.getJobInfo()))); service.wakeUpSchedulingThread(); } catch (Exception e) { logger.error("Error while removing job " + jobId, e); throw e; } return true; }

Target:
public Boolean call() { try { long start = 0; if (logger.isInfoEnabled()) { start = System.currentTimeMillis(); logger.info("Removing job " + jobId); } SchedulerDBManager dbManager = service.getInfrastructure().getDBManager(); List<InternalJob> jobs = dbManager.loadJobWithTasksIfNotRemoved(jobId); TerminationData terminationData; if (jobs.size() != 1) { terminationData = service.getJobs().removeJob(jobId); } else { if (isInFinishedState(jobs.get(0))) { terminationData = service.getJobs().removeJob(jobId); } else { terminationData = service.getJobs().killJob(jobId); } } service.submitTerminationDataHandler(terminationData); if (jobs.size() != 1) { return false; } InternalJob job = jobs.get(0); job.setRemovedTime(System.currentTimeMillis()); boolean removeFromDb = PASchedulerProperties.JOB_REMOVE_FROM_DB.getValueAsBoolean(); dbManager.removeJob(jobId, job.getRemovedTime(), removeFromDb); ServerJobAndTaskLogs.getInstance().remove(jobId, job.getOwner()); if (logger.isInfoEnabled()) { logger.info("Job " + jobId + " removed in " + (System.currentTimeMillis() - start) + "ms"); } service.getListener() .jobStateUpdated(job.getOwner(), new NotificationData<JobInfo>(SchedulerEvent.JOB_REMOVE_FINISHED, new JobInfoImpl((JobInfoImpl) job.getJobInfo()))); service.wakeUpSchedulingThread(); } catch (Exception e) { logger.error("Error while removing job " + jobId, e); throw e; } return true; }
Source:
public void run() { try { final String path = ZKPaths.makePath(basePath, segmentHolder.getSegmentIdentifier()); final byte[] payload = jsonMapper.writeValueAsBytes(segmentHolder.getChangeRequest()); curator.create().withMode(CreateMode.EPHEMERAL).forPath(path, payload); log.debug( "ZKNode created for server to [%s] %s [%s]", basePath, segmentHolder.getType() == LOAD ? "load" : "drop", segmentHolder.getSegmentIdentifier() ); final ScheduledFuture<?> future = monitorNodeRemovedExecutor.schedule( () -> { try { if (curator.checkExists().forPath(path) != null) { failAssign(segmentHolder, new ISE("%s was never removed! Failing this operation!", path)); } else { log.debug("%s detected to be removed. ", path); } } catch (Exception e) { failAssign(segmentHolder, e); } }, config.getLoadTimeoutDelay().getMillis(), TimeUnit.MILLISECONDS ); final Stat stat = curator.checkExists().usingWatcher( (CuratorWatcher) watchedEvent -> { switch (watchedEvent.getType()) { case NodeDeleted: future.cancel(true); entryRemoved(segmentHolder, watchedEvent.getPath()); break; default: } } ).forPath(path); if (stat == null) { final byte[] noopPayload = jsonMapper.writeValueAsBytes(new SegmentChangeRequestNoop()); curator.create().withMode(CreateMode.EPHEMERAL).forPath(path, noopPayload); entryRemoved(segmentHolder, path); } } catch (KeeperException.NodeExistsException ne) { log.warn(ne, "ZK node already exists because segment change request hasn't yet been processed"); failAssign(segmentHolder); } catch (Exception e) { failAssign(segmentHolder, e); } }

Target:
public void run() { try { final String path = ZKPaths.makePath(basePath, segmentHolder.getSegmentIdentifier()); final byte[] payload = jsonMapper.writeValueAsBytes(segmentHolder.getChangeRequest()); curator.create().withMode(CreateMode.EPHEMERAL).forPath(path, payload); log.debug( "ZKNode created for server to [%s] %s [%s]", basePath, segmentHolder.getType() == LOAD ? "load" : "drop", segmentHolder.getSegmentIdentifier() ); final ScheduledFuture<?> nodeDeletedCheck = scheduleNodeDeletedCheck(path); final Stat stat = curator.checkExists().usingWatcher( (CuratorWatcher) watchedEvent -> { switch (watchedEvent.getType()) { case NodeDeleted: nodeDeletedCheck.cancel(true); entryRemoved(segmentHolder, watchedEvent.getPath()); break; default: } } ).forPath(path); if (stat == null) { final byte[] noopPayload = jsonMapper.writeValueAsBytes(new SegmentChangeRequestNoop()); curator.create().withMode(CreateMode.EPHEMERAL).forPath(path, noopPayload); entryRemoved(segmentHolder, path); } } catch (KeeperException.NodeExistsException ne) { log.warn(ne, "ZK node already exists because segment change request hasn't yet been processed"); failAssign(segmentHolder); } catch (Exception e) { failAssign(segmentHolder, e); } }
Source:
public void getInstanceAsync_nullConfigShouldThrow() { thrown.expect(IllegalArgumentException.class); Realm.getInstanceAsync(null, new Realm.Callback() { @Override public void onSuccess(Realm realm) { } }); }

Target:
public void getInstanceAsync_nullConfigShouldThrow() { thrown.expect(IllegalArgumentException.class); Realm.getInstanceAsync(null, new Realm.Callback() { @Override public void onSuccess(Realm realm) { fail(); } }); }
Source:
public Response updateWorkflowInstance(@ApiParam("Internal id for workflow instance") @PathParam("id") long id, @ApiParam("Submitted workflow instance information") UpdateWorkflowInstanceRequest req) { return handleExceptions(() -> { boolean updated = super.updateWorkflowInstance(id, req, workflowInstanceFactory, workflowInstances, workflowInstanceDao); return (updated ? noContent() : status(CONFLICT)).build(); }); }

Target:
public Response updateWorkflowInstance(@ApiParam("Internal id for workflow instance") @PathParam("id") long id, @ApiParam("Submitted workflow instance information") UpdateWorkflowInstanceRequest req) { return handleExceptions(() -> { boolean updated = super.updateWorkflowInstance(id, req, workflowInstanceFactory, workflowInstances, workflowInstanceDao); return (updated ? noContent() : status(CONFLICT)); }); }
Source:
private void registerReceivers() { this.registrar = new BroadcastRegistrar(); this.registrar.addAction(UserList.ACTION_USER_LIST_UPDATE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { Log.i("MenuFragment", "User list update intent caught"); ((UserListAdapter)userView.getAdapter()) .updateUserList( ( (CustomApp)getActivity().getApplication() ).getUserList()); } }).register(this.getActivity()); }

Target:
private void registerReceivers() { this.registrar = new BroadcastRegistrar(); this.registrar.addAction(UserList.ACTION_USER_LIST_UPDATE, new IBroadcastActionHandler() { @Override public void onReceiveAction(Context context, Intent intent) { ((UserListAdapter)userView.getAdapter()).notifyDataSetChanged(); } }).register(this.getActivity()); }
Source:
private QueueEntry(List<DataSegment> segments) { Preconditions.checkArgument(segments != null && !segments.isEmpty()); final List<DataSegment> segmentsToSort = new ArrayList<>(segments); Collections.sort(segmentsToSort); this.interval = new Interval( segmentsToSort.get(0).getInterval().getStart(), segmentsToSort.get(segmentsToSort.size() - 1).getInterval().getEnd() ); this.segments = segmentsToSort; }

Target:
private QueueEntry(List<DataSegment> segments) { Preconditions.checkArgument(segments != null && !segments.isEmpty()); DateTime minStart = DateTimes.MAX, maxEnd = DateTimes.MIN; for (DataSegment segment : segments) { if (segment.getInterval().getStart().compareTo(minStart) < 0) { minStart = segment.getInterval().getStart(); } if (segment.getInterval().getEnd().compareTo(maxEnd) > 0) { maxEnd = segment.getInterval().getEnd(); } } this.interval = new Interval(minStart, maxEnd); this.segments = segments; }
Source:
public void select(final int delay) { ArgumentVerifier.assertNotNegative(delay, "delay"); checkRunning(); localNoThreadScheduler.tick(null); try { if(delay == 0) { commonSelector.selectNow(); } else { commonSelector.select(delay); } if(isRunning()) { for(final SelectionKey key: commonSelector.selectedKeys()) { try { if(key.isAcceptable()) { doServerAccept(servers.get(key.channel())); } else { final Client tmpClient = clients.get(key.channel()); try{ if(key.isConnectable() && tmpClient != null) { doClientConnect(tmpClient, commonSelector); key.cancel(); setClientOperations(tmpClient); } else { if (key.isReadable()) { if(tmpClient != null){ stats.addRead(doClientRead(tmpClient, commonSelector)); } else { final Server server = servers.get(key.channel()); if(server != null && server.getServerType() == WireProtocol.UDP) { server.acceptChannel((DatagramChannel)server.getSelectableChannel()); } } } if(key.isWritable()) { stats.addWrite(doClientWrite(tmpClient, commonSelector)); } } } catch(Exception e) { if(tmpClient != null) { tmpClient.close(); } } } } catch(CancelledKeyException e) { } } commonSelector.selectNow(); localNoThreadScheduler.tick(null); } } catch (IOException e) { } catch(ClosedSelectorException e) { } catch (NullPointerException e) { } }

Target:
public void select(final int delay) { ArgumentVerifier.assertNotNegative(delay, "delay"); checkRunning(); localNoThreadScheduler.tick(null); try { if(delay == 0) { commonSelector.selectNow(); } else { commonSelector.select(delay); } if(isRunning()) { for(final SelectionKey key: commonSelector.selectedKeys()) { try { if(key.isAcceptable()) { doServerAccept(servers.get(key.channel())); } else { final Client tmpClient = clients.get(key.channel()); if(key.isConnectable() && tmpClient != null) { doClientConnect(tmpClient, commonSelector); key.cancel(); setClientOperations(tmpClient); } else { if (key.isReadable()) { if(tmpClient != null){ stats.addRead(doClientRead(tmpClient, commonSelector)); } else { final Server server = servers.get(key.channel()); if(server != null && server.getServerType() == WireProtocol.UDP) { server.acceptChannel((DatagramChannel)server.getSelectableChannel()); } } } if(key.isWritable()) { stats.addWrite(doClientWrite(tmpClient, commonSelector)); } } } } catch(CancelledKeyException e) { } } commonSelector.selectNow(); localNoThreadScheduler.tick(null); } } catch (IOException e) { } catch(ClosedSelectorException e) { } catch (NullPointerException e) { } }
Source:
private String setParameter(HttpMessage msg, NameValuePair originalPair, String name, String value, boolean escaped) { ParameterParser parser; if (originalPair.getType() == NameValuePair.TYPE_POST_DATA) { parser = Model.getSingleton().getSession().getFormParamParser(msg.getRequestHeader().getURI().toString()); } else { parser = Model.getSingleton().getSession().getUrlParamParser(msg.getRequestHeader().getURI().toString()); } StringBuilder sb = new StringBuilder(); String encodedValue = (escaped) ? value : getEscapedValue(msg, value); NameValuePair pair; boolean isAppended = false; String query = null; for (int i = 0; i < getParamList().size(); i++) { pair = getParamList().get(i); if (i == originalPair.getPosition()) { isAppended = paramAppend(sb, getEscapedName(msg, name), encodedValue, parser); } else { isAppended = paramAppend(sb, getEscapedName(msg, pair.getName()), getEscapedValue(msg, pair.getValue()), parser); } if (isAppended && i < getParamList().size() - 1) { sb.append(parser.getDefaultKeyValuePairSeparator()); } query = sb.toString(); } if (query == null) { query = encodedValue; } buildMessage(msg, query); return query; }

Target:
private String setParameter(HttpMessage msg, NameValuePair originalPair, String name, String value, boolean escaped) { ParameterParser parser; if (originalPair.getType() == NameValuePair.TYPE_POST_DATA) { parser = Model.getSingleton().getSession().getFormParamParser(msg.getRequestHeader().getURI().toString()); } else { parser = Model.getSingleton().getSession().getUrlParamParser(msg.getRequestHeader().getURI().toString()); } StringBuilder sb = new StringBuilder(); String encodedValue = (escaped) ? value : getEscapedValue(msg, value); NameValuePair pair; boolean isAppended; for (int i = 0; i < getParamList().size(); i++) { pair = getParamList().get(i); if (i == originalPair.getPosition()) { isAppended = paramAppend(sb, getEscapedName(msg, name), encodedValue, parser); } else { isAppended = paramAppend(sb, getEscapedName(msg, pair.getName()), getEscapedValue(msg, pair.getValue()), parser); } if (isAppended && i < getParamList().size() - 1) { sb.append(parser.getDefaultKeyValuePairSeparator()); } } if (sb.length() == 0) { sb.append(encodedValue); } String query = sb.toString(); buildMessage(msg, query); return query; }
Source:
public boolean intersects(GeoShape geoShape) { throw new VertexiumException("Not implemented for argument type " + geoShape.getClass().getName()); }

Target:
public boolean intersects(GeoShape geoShape) { return geoShapes.stream().anyMatch(shape -> shape.intersects(geoShape)); }
Source:
public void process(TestDeployment testDeployment, Archive<?> protocolArchive) { TestClass testClass = this.testClass.get(); if (testClass.isAnnotationPresent(WarpTest.class)) { Archive<?> applicationArchive = testDeployment.getApplicationArchive(); List<ArchivePath> classPathsToRemove = new LinkedList<ArchivePath>(); for (ArchivePath archivePath : applicationArchive.getContent().keySet()) { String path = archivePath.get(); String classPath = testClass.getName().replace(".", "/"); if (path.matches("/WEB-INF/classes/" + classPath + "(\\$[0-9]*)?\\.class")) { classPathsToRemove.add(archivePath); } } for (ArchivePath archivePath : classPathsToRemove) { applicationArchive.delete(archivePath); } WebArchive protocolWar = (WebArchive)protocolArchive; protocolWar.addAsLibrary( ShrinkWrap.create(JavaArchive.class, "arquillian-warp-filter.jar") .addClass(WarpFilter.class)); } }

Target:
public void process(TestDeployment testDeployment, Archive<?> protocolArchive) { TestClass testClass = this.testClass.get(); if (testClass.isAnnotationPresent(WarpTest.class)) { Archive<?> applicationArchive = testDeployment.getApplicationArchive(); List<ArchivePath> classPathsToRemove = new LinkedList<ArchivePath>(); for (ArchivePath archivePath : applicationArchive.getContent().keySet()) { String path = archivePath.get(); String classPath = testClass.getName().replace(".", "/"); if (path.matches("/WEB-INF/classes/" + classPath + "(\\$[0-9]*)?\\.class")) { classPathsToRemove.add(archivePath); } } for (ArchivePath archivePath : classPathsToRemove) { applicationArchive.delete(archivePath); } if (Validate.isArchiveOfType(WebArchive.class, protocolArchive)) { protocolArchive.as(WebArchive.class).addAsLibrary( ShrinkWrap.create(JavaArchive.class, "arquillian-warp-filter.jar") .addClass(WarpFilter.class)); } else { throw new IllegalArgumentException("Protocol archives of type "+protocolArchive.getClass()+" not supported. Please use the Servlet 3.0 protocol."); } } }
Source:
public int compareTo(Comment that){ return (int) (this.getId() - that.getId()); }

Target:
public int compareTo(Comment that){ return Long.valueOf(this.getId()).compareTo(that.getId()); }
Source:
protected void invokeTestMethod(JupiterEngineExecutionContext context, DynamicTestExecutor dynamicTestExecutor) { ExtensionContext extensionContext = context.getExtensionContext(); context.getThrowableCollector().execute(() -> { Object instance = extensionContext.getRequiredTestInstance(); Object testFactoryMethodResult = executableInvoker.invoke(getTestMethod(), instance, extensionContext, context.getExtensionRegistry()); TestSource defaultTestSource = getSource().orElseThrow( () -> new JUnitException("Illegal state: TestSource must be present")); if (testFactoryMethodResult instanceof DynamicNode) { execute((DynamicNode) testFactoryMethodResult, defaultTestSource, 1, dynamicTestExecutor); return; } try (Stream<DynamicNode> dynamicNodeStream = toDynamicNodeStream(testFactoryMethodResult)) { int index = 1; Iterator<DynamicNode> iterator = dynamicNodeStream.iterator(); while (iterator.hasNext()) { execute(iterator.next(), defaultTestSource, index++, dynamicTestExecutor); } } catch (ClassCastException ex) { throw invalidReturnTypeException(ex); } }); }

Target:
protected void invokeTestMethod(JupiterEngineExecutionContext context, DynamicTestExecutor dynamicTestExecutor) { ExtensionContext extensionContext = context.getExtensionContext(); context.getThrowableCollector().execute(() -> { Object instance = extensionContext.getRequiredTestInstance(); Object testFactoryMethodResult = executableInvoker.invoke(getTestMethod(), instance, extensionContext, context.getExtensionRegistry()); TestSource defaultTestSource = getSource().orElseThrow( () -> new JUnitException("Illegal state: TestSource must be present")); try (Stream<DynamicNode> dynamicNodeStream = toDynamicNodeStream(testFactoryMethodResult)) { int index = 1; Iterator<DynamicNode> iterator = dynamicNodeStream.iterator(); while (iterator.hasNext()) { DynamicNode dynamicNode = iterator.next(); Optional<JupiterTestDescriptor> descriptor = createDynamicDescriptor(this, dynamicNode, index++, defaultTestSource, getDynamicDescendantFilter()); descriptor.ifPresent(dynamicTestExecutor::execute); } } catch (ClassCastException ex) { throw invalidReturnTypeException(ex); } }); }
Source:
GdkColor getContextColor () { if (OS.GTK_VERSION >= OS.VERSION(3, 16, 0)) { if (foreground != null) { return display.toGdkColor (foreground); } else { return display.COLOR_LIST_FOREGROUND; } } else { return super.getContextBackground (); } }

Target:
GdkColor getContextColor () { if (OS.GTK_VERSION >= OS.VERSION(3, 16, 0)) { if (foreground != null) { return display.toGdkColor (foreground); } else { return display.COLOR_LIST_FOREGROUND; } } else { return super.getContextColor (); } }
Source:
public List<Pool> lookupOversubscribedBySubscriptionIds(Owner owner, Map<String, Entitlement> subIdMap) { List<Criterion> subIdMapCriteria = new ArrayList<Criterion>(); Criterion[] exampleCriteria = new Criterion[0]; Owner currentOwner = null; for (Entry<String, Entitlement> entry : subIdMap.entrySet()) { SimpleExpression subscriptionExpr = Restrictions.eq("sourceSub.subscriptionId", entry.getKey()); Junction subscriptionJunction = Restrictions.and(subscriptionExpr).add( Restrictions.or(Restrictions.isNull("sourceEntitlement"), Restrictions.eqOrIsNull("sourceEntitlement", entry.getValue()))); subIdMapCriteria.add(subscriptionJunction); } return currentSession() .createCriteria(Pool.class) .createAlias("sourceSubscription", "sourceSub") .add(Restrictions.eq("owner", owner)) .add(Restrictions.ge("quantity", 0L)) .add(Restrictions.gtProperty("consumed", "quantity")) .add(Restrictions.or(subIdMapCriteria.toArray(exampleCriteria))).list(); }

Target:
public List<Pool> lookupOversubscribedBySubscriptionIds(Owner owner, Map<String, Entitlement> subIdMap) { List<Criterion> subIdMapCriteria = new ArrayList<Criterion>(); Criterion[] exampleCriteria = new Criterion[0]; for (Entry<String, Entitlement> entry : subIdMap.entrySet()) { SimpleExpression subscriptionExpr = Restrictions.eq("sourceSub.subscriptionId", entry.getKey()); Junction subscriptionJunction = Restrictions.and(subscriptionExpr).add( Restrictions.or(Restrictions.isNull("sourceEntitlement"), Restrictions.eqOrIsNull("sourceEntitlement", entry.getValue()))); subIdMapCriteria.add(subscriptionJunction); } return currentSession() .createCriteria(Pool.class) .createAlias("sourceSubscription", "sourceSub") .add(Restrictions.eq("owner", owner)) .add(Restrictions.ge("quantity", 0L)) .add(Restrictions.gtProperty("consumed", "quantity")) .add(Restrictions.or(subIdMapCriteria.toArray(exampleCriteria))).list(); }
Source:
public void onDisable() { getBackup().setPendingShutdown(true); for (User user : getOnlineUsers()) { if (user.isVanished()) { user.setVanished(false); user.sendMessage(tl("unvanishedReload")); } user.stopTransaction(); } cleanupOpenInventories(); if (i18n != null) { i18n.onDisable(); } if (backup != null) { backup.stopTask(); } Economy.setEss(null); Trade.closeLog(); getUserMap().getUUIDMap().shutdown(); HandlerList.unregisterAll(this); while (getBackup().isActive()) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } }

Target:
public void onDisable() { boolean stopping = ServerState.isStopping(); if (!stopping) { LOGGER.log(Level.SEVERE, tl("serverReloading")); } getBackup().setPendingShutdown(true); for (User user : getOnlineUsers()) { if (user.isVanished()) { user.setVanished(false); user.sendMessage(tl("unvanishedReload")); } if (stopping) { user.setLastLocation(); if (!user.isHidden()) { user.setLastLogout(System.currentTimeMillis()); } user.cleanup(); } else { user.stopTransaction(); } } cleanupOpenInventories(); if (getBackup().getTaskLock() != null && !getBackup().getTaskLock().isDone()) { LOGGER.log(Level.SEVERE, tl("backupInProgress")); getBackup().getTaskLock().join(); } if (i18n != null) { i18n.onDisable(); } if (backup != null) { backup.stopTask(); } Economy.setEss(null); Trade.closeLog(); getUserMap().getUUIDMap().shutdown(); HandlerList.unregisterAll(this); }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((m_name == null) ? 0 : m_name.hashCode()); return result; }

Target:
public int hashCode() { return Objects.hash(m_name); }
Source:
GenericRecord getBobRecord1(org.apache.avro.Schema avroOutputSchema) { return new GenericRecordBuilder(avroOutputSchema) .set("film_id", "1") .set("film_name", "matrix") .set("renamed_category", "thriller") .set("renamed_actor", "bob") .build(); }

Target:
private GenericRecord getBobRecord1(org.apache.avro.Schema avroOutputSchema) { return new GenericRecordBuilder(avroOutputSchema) .set("film_id", "1") .set("film_name", "matrix") .set("renamed_category", "thriller") .set("renamed_actor", "bob") .build(); }
Source:
public List<AdverseEventType> getAllAdverseEventTypes() { TypedQuery<AdverseEventType> query; query = entityManager.createQuery("SELECT a from AdverseEventType a", AdverseEventType.class); return query.getResultList(); }

Target:
public List<AdverseEventType> getAllAdverseEventTypes() { return entityManager.createQuery("SELECT a from AdverseEventType a", AdverseEventType.class).getResultList(); }
Source:
static LogicalPlan.Builder create(LogicalPlan.Builder source, List<WindowFunction> windowFunctions) { if (windowFunctions.isEmpty()) { return source; } return (tableStats, hints, usedBeforeNextFetch) -> { HashSet<Symbol> allUsedColumns = new HashSet<>(extractColumns(usedBeforeNextFetch)); Set<Symbol> columnsUsedInFunctions = extractColumns(windowFunctions); LinkedHashMap<WindowDefinition, ArrayList<WindowFunction>> groupedFunctions = new LinkedHashMap<>(); for (WindowFunction windowFunction : windowFunctions) { WindowDefinition windowDefinition = windowFunction.windowDefinition(); if (windowFunction.filter() != null) { columnsUsedInFunctions.add(windowFunction.filter()); } OrderBy orderBy = windowDefinition.orderBy(); if (orderBy != null) { columnsUsedInFunctions.addAll(extractColumns(orderBy.orderBySymbols())); } columnsUsedInFunctions.addAll(extractColumns(windowDefinition.partitions())); ArrayList<WindowFunction> functions = groupedFunctions.computeIfAbsent(windowDefinition, w -> new ArrayList<>()); functions.add(windowFunction); } allUsedColumns.addAll(columnsUsedInFunctions); LogicalPlan sourcePlan = source.build(tableStats, hints, allUsedColumns); LogicalPlan lastWindowAgg = sourcePlan; for (Map.Entry<WindowDefinition, ArrayList<WindowFunction>> entry : groupedFunctions.entrySet()) { lastWindowAgg = new WindowAgg(lastWindowAgg, entry.getKey(), entry.getValue(), lastWindowAgg.outputs()); } return lastWindowAgg; }; }

Target:
static LogicalPlan.Builder create(LogicalPlan.Builder source, List<WindowFunction> windowFunctions) { if (windowFunctions.isEmpty()) { return source; } return (tableStats, hints, usedBeforeNextFetch) -> { HashSet<Symbol> allUsedColumns = new HashSet<>(extractColumns(usedBeforeNextFetch)); Set<Symbol> columnsUsedInFunctions = extractColumns(windowFunctions); LinkedHashMap<WindowDefinition, ArrayList<WindowFunction>> groupedFunctions = new LinkedHashMap<>(); for (WindowFunction windowFunction : windowFunctions) { WindowDefinition windowDefinition = windowFunction.windowDefinition(); if (windowFunction.filter() != null) { columnsUsedInFunctions.addAll(extractColumns(windowFunction.filter())); } OrderBy orderBy = windowDefinition.orderBy(); if (orderBy != null) { columnsUsedInFunctions.addAll(extractColumns(orderBy.orderBySymbols())); } columnsUsedInFunctions.addAll(extractColumns(windowDefinition.partitions())); ArrayList<WindowFunction> functions = groupedFunctions.computeIfAbsent(windowDefinition, w -> new ArrayList<>()); functions.add(windowFunction); } allUsedColumns.addAll(columnsUsedInFunctions); LogicalPlan sourcePlan = source.build(tableStats, hints, allUsedColumns); LogicalPlan lastWindowAgg = sourcePlan; for (Map.Entry<WindowDefinition, ArrayList<WindowFunction>> entry : groupedFunctions.entrySet()) { lastWindowAgg = new WindowAgg(lastWindowAgg, entry.getKey(), entry.getValue(), lastWindowAgg.outputs()); } return lastWindowAgg; }; }
Source:
@Override public void setup(Context.OperatorContext context) { super.setup(context); fields = new ArrayList<Field>(); String[] field_info = fieldInfo.split(","); for ( int i=0 ; i < field_info.length ; i++ ) { String[] field_tuple = field_info[i].split(":"); Field field = new Field(); field.setName(field_tuple[0]); String[] type_format = field_tuple[1].split("\\|"); field.setType(type_format[0].toUpperCase()); if ( type_format.length > 1 ) { field.setFormat(type_format[1]); } getFields().add(field); } preference = new CsvPreference.Builder('"', fieldDelimiter, lineDelimiter).build(); int countKeyValue = getFields().size(); nameMapping = new String[countKeyValue]; processors = new CellProcessor[countKeyValue]; initialise(nameMapping, processors); }

Target:
public void setup(Context.OperatorContext context) { super.setup(context); fields = new ArrayList<Field>(); String[] fieldInfoTuple = fieldInfo.split(","); for (int i = 0; i < fieldInfoTuple.length; i++) { String[] fieldTuple = fieldInfoTuple[i].split(":"); Field field = new Field(); field.setName(fieldTuple[0]); String[] typeFormat = fieldTuple[1].split("\\|"); field.setType(typeFormat[0].toUpperCase()); if (typeFormat.length > 1) { field.setFormat(typeFormat[1]); } getFields().add(field); } preference = new CsvPreference.Builder('"', fieldDelimiter, lineDelimiter).build(); int countKeyValue = getFields().size(); nameMapping = new String[countKeyValue]; processors = new CellProcessor[countKeyValue]; initialise(nameMapping, processors); }
Source:
public Optional<Type> elementType(Type containerType) { return findGenericParameter(containerType, getErasedType(containerType)); }

Target:
public Optional<Type> elementType(Type containerType) { return findGenericParameter(containerType, EnumSet.class); }
Source:
public static int getInt(String str, int defaultVal) { try { return Integer.parseInt(str); } catch (NumberFormatException e) { return defaultVal; } }

Target:
public static int getInt(String str, int defaultVal) { if (PatternUtils.NUMERIC.matcher(str).matches()) return Integer.parseInt(str); return defaultVal; }
Source:
public double getMeanTaskRunningTime(String jobId) { final long id = Long.parseLong(jobId); Double result = executeReadOnlyTransaction(session -> { Query jobQuery = session.getNamedQuery("checkJobExistence").setParameter("id", id); if (jobQuery.uniqueResult() == null) { return null; } Query query = session.getNamedQuery("getMeanTaskRunningTime").setParameter("id", id); Double result1 = (Double) query.uniqueResult(); return result1 == null ? 0 : result1; }); return checkResult(id, result); }

Target:
public double getMeanTaskRunningTime(String jobId) { final long id = Long.parseLong(jobId); Double result = executeReadOnlyTransaction(session -> { Query jobQuery = session.getNamedQuery("checkJobExistence").setParameter("id", id); if (jobQuery.uniqueResult() == null) { return null; } Query query = session.getNamedQuery("getMeanTaskRunningTime").setParameter("id", id); Double uniqueResult = (Double) query.uniqueResult(); return uniqueResult == null ? 0.0d : uniqueResult; }); return checkResult(id, result); }
Source:
public static void main(String[] args) { if (args.length == 0) { printUsage(System.err, "You must provide a properties file"); System.exit(1); } MultiLangDaemonConfig config = null; try { config = new MultiLangDaemonConfig(args[0]); } catch (IOException e) { printUsage(System.err, "You must provide a properties file"); System.exit(1); } catch (IllegalArgumentException e) { printUsage(System.err, e.getMessage()); System.exit(1); } ExecutorService executorService = config.getExecutorService(); final MultiLangDaemon daemon = new MultiLangDaemon( config.getKinesisClientLibConfiguration(), config.getRecordProcessorFactory(), executorService); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { LOG.info("Process terminanted, will initiate shutdown."); try { Future<Void> fut = daemon.worker.requestShutdown(); fut.get(); LOG.info("Process shutdown is complete."); } catch (InterruptedException | ExecutionException e) { LOG.error("Encountered an error during shutdown.", e); } } }); Future<Integer> future = executorService.submit(daemon); try { System.exit(future.get()); } catch (InterruptedException | ExecutionException e) { LOG.error("Encountered an error while running daemon", e); } System.exit(1); }

Target:
public static void main(String[] args) { if (args.length == 0) { printUsage(System.err, "You must provide a properties file"); System.exit(1); } MultiLangDaemonConfig config = null; try { config = new MultiLangDaemonConfig(args[0]); } catch (IOException e) { printUsage(System.err, "You must provide a properties file"); System.exit(1); } catch (IllegalArgumentException e) { printUsage(System.err, e.getMessage()); System.exit(1); } ExecutorService executorService = config.getExecutorService(); final MultiLangDaemon daemon = new MultiLangDaemon( config.getKinesisClientLibConfiguration(), config.getRecordProcessorFactory(), executorService); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { LOG.info("Process terminanted, will initiate shutdown."); try { Future<Void> fut = daemon.worker.requestShutdown(); fut.get(5000, TimeUnit.MILLISECONDS); LOG.info("Process shutdown is complete."); } catch (InterruptedException | ExecutionException | TimeoutException e) { LOG.error("Encountered an error during shutdown.", e); } } }); Future<Integer> future = executorService.submit(daemon); try { System.exit(future.get()); } catch (InterruptedException | ExecutionException e) { LOG.error("Encountered an error while running daemon", e); } System.exit(1); }
Source:
public final Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable { boolean releaseRemote = false; try { if (command.hasFlag(Flag.FORCE_WRITE_LOCK) && ctx.isInTxScope()) { boolean skipLocking = hasSkipLocking(command); if (!skipLocking) { releaseRemote = true; acquireRemoteIfNeeded(ctx, command, cdl.localNodeIsPrimaryOwner(command.getKey())); } long lockTimeout = getLockAcquisitionTimeout(command, skipLocking); lockKeyAndCheckOwnership(ctx, command.getKey(), lockTimeout, skipLocking); } return invokeNextInterceptor(ctx, command); } catch (Throwable t) { releaseRemote = false; releaseLocksOnFailureBeforePrepare(ctx); throw t; } finally { if (!ctx.isInTxScope()) lockManager.unlockAll(ctx); if(releaseRemote) releaseRemoteIfNeeded(ctx, command, cdl.localNodeIsPrimaryOwner(command.getKey())); } }

Target:
public final Object visitGetKeyValueCommand(InvocationContext ctx, GetKeyValueCommand command) throws Throwable { try { if (command.hasFlag(Flag.FORCE_WRITE_LOCK) && ctx.isInTxScope()) { boolean skipLocking = hasSkipLocking(command); if (!skipLocking) { acquireRemoteIfNeeded(ctx, command, cdl.localNodeIsPrimaryOwner(command.getKey())); } long lockTimeout = getLockAcquisitionTimeout(command, skipLocking); lockKeyAndCheckOwnership(ctx, command.getKey(), lockTimeout, skipLocking); } return invokeNextInterceptor(ctx, command); } catch (Throwable t) { releaseLocksOnFailureBeforePrepare(ctx); throw t; } finally { if (!ctx.isInTxScope()) lockManager.unlockAll(ctx); } }
Source:
public boolean isCameraFlashAvailable() { return (frontCameraInformation.flashAvailable || backCameraInformation.flashAvailable); }

Target:
public boolean isCameraFlashAvailable() { return (hasBackCameraFlash() || hasFrontCameraFlash()); }
Source:
public void signs() throws IOException { MatcherAssert.assertThat( new String( new SiHmac( "key", SiHmac.HMAC256 ).sign( "The quick brown fox jumps over the lazy dog".getBytes() ) ), Matchers.equalTo( "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8" ) ); }

Target:
public void signs() throws IOException { new Assertion<>( "Must have proper signature", new String( new SiHmac("key", SiHmac.HMAC256).sign( "The quick brown fox jumps over the lazy dog".getBytes() ) ), new IsEqual<>( "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8" ) ).affirm(); }
Source:
protected final <C extends SolrUpdateCommand> void scheduleCommand(C command) { if (!isRunning(getCommandGroup())) { throw new IllegalStateException("Attempted to queue a SolrUpdateCommand but " + getClass().getName() + " is not initialized or has been shut down."); } if (command != null) { try { for (int i = 0; i < 5; i++) { if (!commandQueue.contains(FullReindexCommand.DEFAULT_INSTANCE) && !commandQueue.contains(command)) { if (commandQueue.offer(command, getQueueOfferTime(), TimeUnit.MILLISECONDS)) { return; } else if (!isRunning(getCommandGroup())) { throw new IllegalStateException("Attempted to queue a SolrUpdateCommand but " + getClass().getName() + " is not initialized or has been shut down."); } } } throw new IllegalStateException("Unable to add a Solr index update command to the queue within 5 seconds."); } catch (InterruptedException e) { throw new RuntimeException("Unexpected error occurred attempting to add a command to the queue.", e); } } }

Target:
protected final <C extends SolrUpdateCommand> void scheduleCommand(C command) { if (!isRunning(getCommandGroup())) { throw new IllegalStateException("Attempted to queue a SolrUpdateCommand but " + getClass().getName() + " is not initialized or has been shut down."); } if (command != null) { try { for (int i = 0; i < 5; i++) { if (!commandQueue.contains(command)) { if (commandQueue.offer(command, getQueueOfferTime(), TimeUnit.MILLISECONDS)) { return; } else if (!isRunning(getCommandGroup())) { throw new IllegalStateException("Attempted to queue a SolrUpdateCommand but " + getClass().getName() + " is not initialized or has been shut down."); } } } throw new IllegalStateException("Unable to add a Solr index update command to the queue within 5 seconds."); } catch (InterruptedException e) { throw new RuntimeException("Unexpected error occurred attempting to add a command to the queue.", e); } } }
Source:
public Mono<Boolean> acquireInitializationLock(Duration lockExpirationTime) { String lockId = this.getStoreLockName(); CosmosItemProperties containerDocument = new CosmosItemProperties(); containerDocument.id(lockId); BridgeInternal.setProperty(containerDocument, com.azure.data.cosmos.internal.Constants.Properties.TTL, Long.valueOf(lockExpirationTime.getSeconds()).intValue()); return this.client.createItem(this.leaseCollectionLink, containerDocument, new CosmosItemRequestOptions(lockId), false) .map(documentResourceResponse -> { if (documentResourceResponse.item() != null) { this.lockETag = documentResourceResponse.properties().etag(); return true; } else { return false; } }) .onErrorResume(throwable -> { if (throwable instanceof CosmosClientException) { CosmosClientException e = (CosmosClientException) throwable; if (e.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT) { logger.info("Lease synchronization document was acquired by a different instance"); return Mono.just(false); } } logger.warn("Unexpected exception thrown", throwable); return Mono.error(throwable); }); }

Target:
public Mono<Boolean> acquireInitializationLock(Duration lockExpirationTime) { String lockId = this.getStoreLockName(); CosmosItemProperties containerDocument = new CosmosItemProperties(); containerDocument.id(lockId); BridgeInternal.setProperty(containerDocument, com.azure.data.cosmos.internal.Constants.Properties.TTL, Long.valueOf(lockExpirationTime.getSeconds()).intValue()); return this.client.createItem(this.leaseCollectionLink, containerDocument, new CosmosItemRequestOptions(lockId), false) .map(documentResourceResponse -> { if (documentResourceResponse.item() != null) { this.lockETag = documentResourceResponse.properties().etag(); return true; } else { return false; } }) .onErrorResume(throwable -> { if (throwable instanceof CosmosClientException) { CosmosClientException e = (CosmosClientException) throwable; if (e.statusCode() == ChangeFeedHelper.HTTP_STATUS_CODE_CONFLICT) { logger.info("Lease synchronization document was acquired by a different instance"); return Mono.just(false); } } logger.error("Unexpected exception thrown", throwable); return Mono.error(throwable); }); }
Source:
public static DatabaseAdaptor buildDatabaseAdaptor() { DatabaseAdaptor da = new DatabaseAdaptor(); if (USE_MARIADB) { da.setUsername(MARIAD_DB.getUsername()); da.setPassword(MARIAD_DB.getPassword()); } da.setDriverInfo(DRIVER_CLASS, DEFAULT_CONNECTION_URL); return da; }

Target:
public static DatabaseAdaptor buildDatabaseAdaptor() { DatabaseAdaptor da = new DatabaseAdaptor(); da.setDriverInfo(DRIVER_CLASS, DEFAULT_CONNECTION_URL); return da; }
Source:
CompletableFuture<Void> asyncCompleteLocalTransaction(AdvancedCache<?, ?> cache, long timeout) { return blockingHandler.runBlockingOperation(() -> { try { commitLocalTransaction(cache, xid, timeout); } catch (HeuristicMixedException e) { hasCommits = true; hasRollbacks = true; } catch (RollbackException | HeuristicRollbackException e) { hasRollbacks = true; } catch (Throwable t) { hasErrors = true; } }, this).toCompletableFuture(); }

Target:
CompletionStage<Void> asyncCompleteLocalTransaction(AdvancedCache<?, ?> cache, long timeout) { return blockingManager.runBlocking(() -> { try { commitLocalTransaction(cache, xid, timeout); } catch (HeuristicMixedException e) { hasCommits = true; hasRollbacks = true; } catch (RollbackException | HeuristicRollbackException e) { hasRollbacks = true; } catch (Throwable t) { hasErrors = true; } }, this); }
Source:
public void init() throws IOException, JAXBException { registerEntities(); transactionTemplate.execute(new TransactionCallback<Object>() { @Override public Object doInTransaction(TransactionStatus status) { try { doInit(); } catch (Exception e) { throw new RuntimeException(e); } return null; } }); }

Target:
public void init() throws IOException, JAXBException { registerEntities(); transactionTemplate.execute((s) -> { try { doInit(); } catch (Exception e) { throw new BeanInitializationException(String.format("Failed to initialize: msg-[%s]", e.getMessage()), e); } return null; }); }
Source:
public void setUp() throws Exception { Log.d(TAG, "setup key at settings"); System.setProperty("dexmaker.dexcache", InstrumentationRegistry.getContext().getCacheDir().getPath()); Log.d(TAG, "setup key at settings"); InstrumentationRegistry.getContext().getCacheDir(); System.setProperty("dexmaker.dexcache", InstrumentationRegistry.getContext().getCacheDir().getPath()); if (AuthenticationSettings.INSTANCE.getSecretKeyData() == null) { SecretKeyFactory keyFactory = SecretKeyFactory .getInstance("PBEWithSHA256And256BitAES-CBC-BC"); final int iterationCount = 100; final int keyLength = 256; SecretKey tempkey = keyFactory.generateSecret(new PBEKeySpec("test".toCharArray(), "abcdedfdfd".getBytes("UTF-8"), iterationCount, keyLength)); SecretKey secretKey = new SecretKeySpec(tempkey.getEncoded(), "AES"); AuthenticationSettings.INSTANCE.setSecretKey(secretKey.getEncoded()); } }

Target:
public void setUp() throws Exception { Log.d(TAG, "setup key at settings"); System.setProperty("dexmaker.dexcache", InstrumentationRegistry.getContext().getCacheDir().getPath()); if (AuthenticationSettings.INSTANCE.getSecretKeyData() == null) { SecretKeyFactory keyFactory = SecretKeyFactory .getInstance("PBEWithSHA256And256BitAES-CBC-BC"); final int iterationCount = 100; final int keyLength = 256; SecretKey tempkey = keyFactory.generateSecret(new PBEKeySpec("test".toCharArray(), "abcdedfdfd".getBytes("UTF-8"), iterationCount, keyLength)); SecretKey secretKey = new SecretKeySpec(tempkey.getEncoded(), "AES"); AuthenticationSettings.INSTANCE.setSecretKey(secretKey.getEncoded()); } }
Source:
private static boolean neitherIsThis(ExpressionTree leftExpression, ExpressionTree rightExpression) { return (!(leftExpression.is(Tree.Kind.IDENTIFIER) && "this".equals(((IdentifierTree) leftExpression).name())) && !(rightExpression.is(Tree.Kind.IDENTIFIER) && "this".equals(((IdentifierTree) rightExpression).name()))); }

Target:
private static boolean neitherIsThis(ExpressionTree leftExpression, ExpressionTree rightExpression) { return !ExpressionUtils.isThis(leftExpression) && !ExpressionUtils.isThis(rightExpression); }
Source:
public int execute(AtlasDbServices fromServices, AtlasDbServices toServices) { if (Stream.of(setup, migrate, validate).filter(Boolean::booleanValue).count() != 1) { printer.error("Exactly one of --setup, --migrate, or --validate should be specified."); return 1; } KeyValueServiceMigrator migrator; migrator = getMigrator(fromServices, toServices); if (setup) { migrator.setup(); } if (migrate) { migrator.migrate(); migrator.cleanup(); } if (validate) { KeyValueServiceValidator validator = new KeyValueServiceValidator(fromServices.getTransactionManager(), toServices.getTransactionManager(), fromServices.getKeyValueService(), threads, batchSize, ImmutableMap.of(), (String message, KeyValueServiceMigrator.KvsMigrationMessageLevel level) -> printer.info(level.toString() + ": " + message), ImmutableSet.of()); validator.validate(true); } return 0; }

Target:
public int execute(AtlasDbServices fromServices, AtlasDbServices toServices) { if (!setup && !migrate && !validate) { printer.error("At least one of --setup, --migrate, or --validate should be specified."); return 1; } KeyValueServiceMigrator migrator; migrator = getMigrator(fromServices, toServices); if (setup) { migrator.setup(); } if (migrate) { migrator.migrate(); migrator.cleanup(); } if (validate) { KeyValueServiceValidator validator = new KeyValueServiceValidator(fromServices.getTransactionManager(), toServices.getTransactionManager(), fromServices.getKeyValueService(), threads, batchSize, ImmutableMap.of(), (String message, KeyValueServiceMigrator.KvsMigrationMessageLevel level) -> printer.info(level.toString() + ": " + message), ImmutableSet.of()); validator.validate(true); } return 0; }
Source:
private AlluxioURI createTempUfsDir(String ufsPath) throws IOException { String path = mTestFolder.newFolder(ufsPath.split("/")).getPath(); return new AlluxioURI("file:??", null, path); }

Target:
private AlluxioURI createTempUfsDir(String ufsPath) throws IOException { String path = mTestFolder.newFolder(ufsPath.split("/")).getPath(); return new AlluxioURI("file", null, path); }
Source:
public Subprocedure buildSubprocedure(String table, String family) { if (rss.isStopping() || rss.isStopped()) { throw new IllegalStateException("Can't start flush region subprocedure on RS: " + rss.getServerName() + ", because stopping/stopped!"); } List<HRegion> involvedRegions; try { involvedRegions = getRegionsToFlush(table); } catch (IOException e1) { throw new IllegalStateException("Failed to figure out if there is region to flush.", e1); } if (involvedRegions == null && involvedRegions.isEmpty()) { LOG.info("no region of is online on the {}.", table, this.rss.getServerName()); return null; } LOG.debug("Launching subprocedure to flush regions for " + table); ForeignExceptionDispatcher exnDispatcher = new ForeignExceptionDispatcher(table); Configuration conf = rss.getConfiguration(); long timeoutMillis = conf.getLong(FLUSH_TIMEOUT_MILLIS_KEY, FLUSH_TIMEOUT_MILLIS_DEFAULT); long wakeMillis = conf.getLong(FLUSH_REQUEST_WAKE_MILLIS_KEY, FLUSH_REQUEST_WAKE_MILLIS_DEFAULT); FlushTableSubprocedurePool taskManager = new FlushTableSubprocedurePool(rss.getServerName().toString(), conf, rss); return new FlushTableSubprocedure(member, exnDispatcher, wakeMillis, timeoutMillis, involvedRegions, table, family, taskManager); }

Target:
public Subprocedure buildSubprocedure(String table, String family) { if (rss.isStopping() || rss.isStopped()) { throw new IllegalStateException("Can't start flush region subprocedure on RS: " + rss.getServerName() + ", because stopping/stopped!"); } List<HRegion> involvedRegions; try { involvedRegions = getRegionsToFlush(table); } catch (IOException e1) { throw new IllegalStateException("Failed to figure out if there is region to flush.", e1); } if (CollectionUtils.isEmpty(involvedRegions)) { LOG.info("no region of is online on the {}.", table, this.rss.getServerName()); return null; } LOG.debug("Launching subprocedure to flush regions for " + table); ForeignExceptionDispatcher exnDispatcher = new ForeignExceptionDispatcher(table); Configuration conf = rss.getConfiguration(); long timeoutMillis = conf.getLong(FLUSH_TIMEOUT_MILLIS_KEY, FLUSH_TIMEOUT_MILLIS_DEFAULT); long wakeMillis = conf.getLong(FLUSH_REQUEST_WAKE_MILLIS_KEY, FLUSH_REQUEST_WAKE_MILLIS_DEFAULT); FlushTableSubprocedurePool taskManager = new FlushTableSubprocedurePool(rss.getServerName().toString(), conf, rss); return new FlushTableSubprocedure(member, exnDispatcher, wakeMillis, timeoutMillis, involvedRegions, table, family, taskManager); }
Source:
public static boolean isFileOpen(File file) { String osName = System.getProperty("os.name", "<None>"); if (osName.startsWith("Windows")) { String fileName = file.getName(); File sameFileName = new File(fileName); return !file.renameTo(sameFileName); } else { String filePath = file.getAbsolutePath(); File nullFile = new File("/dev/null"); ProcessBuilder builder = new ProcessBuilder("lsof", "-c", "java", "-a", "-T", "--", filePath).redirectError(nullFile).redirectOutput(nullFile); try { Process process = builder.start(); int exitValue = process.waitFor(); return exitValue == 0; } catch (InterruptedException | IOException e) { } return false; } }

Target:
public static boolean isFileOpen(File file) { if (IS_OS_WINDOWS) { String fileName = file.getName(); File sameFileName = new File(fileName); return !file.renameTo(sameFileName); } else { String filePath = file.getAbsolutePath(); File nullFile = new File("/dev/null"); ProcessBuilder builder = new ProcessBuilder("lsof", "-c", "java", "-a", "-T", "--", filePath).redirectError(nullFile).redirectOutput(nullFile); try { Process process = builder.start(); int exitValue = process.waitFor(); return exitValue == 0; } catch (InterruptedException | IOException e) { } return false; } }