auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static Tocd readObjectClassDefinition(String pid) throws IOException, Exception, XMLStreamException, FactoryConfigurationError { Tocd ocd = null; StringBuilder sbMetatypeXmlName = new StringBuilder(); sbMetatypeXmlName.append("OSGI-INF/metatype/").append(pid).append(".xml"); String metatypeXmlName = sbMetatypeXmlName.toString(); String metatypeXml = IOUtil.readResource(metatypeXmlName); if (metatypeXml != null) { Tmetadata metaData = unmarshalXml(metatypeXml, Tmetadata.class); if (metaData.getOCD() != null && metaData.getOCD().size() > 0) { ocd = (Tocd) metaData.getOCD().get(0); } else { logger.warn("Cannot find OCD for component with pid: {}", pid); } } return ocd; }

Target:
public static Tocd readObjectClassDefinition(String pid) throws IOException, Exception, XMLStreamException, FactoryConfigurationError { Tocd ocd = null; StringBuilder sbMetatypeXmlName = new StringBuilder(); sbMetatypeXmlName.append("OSGI-INF/metatype/").append(pid).append(".xml"); String metatypeXmlName = sbMetatypeXmlName.toString(); String metatypeXml = IOUtil.readResource(metatypeXmlName); if (metatypeXml != null) { Tmetadata metaData = unmarshal(metatypeXml, Tmetadata.class); if (metaData.getOCD() != null && !metaData.getOCD().isEmpty()) { ocd = (Tocd) metaData.getOCD().get(0); } else { logger.warn("Cannot find OCD for component with pid: {}", pid); } } return ocd; }
Source:
private InetAddress getRandomIPv4Address(final IpPrefix prefix) throws UnknownHostException { byte[] bytes = prefix.getAddress().getAddress(); bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF); return InetAddress.getByAddress(bytes); }

Target:
private InetAddress getRandomIPv4Address(final IpPrefix prefix) throws UnknownHostException { if (prefix.getPrefixLength() != DEFAULT_PREFIX_LENGTH) { throw new IllegalArgumentException("Unexpected prefix length: " + prefix); } byte[] bytes = prefix.getAddress().getAddress(); bytes[3] = getRandomSanitizedByte(DOUG_ADAMS, asByte(0), asByte(1), FF); return InetAddress.getByAddress(bytes); }
Source:
public MemberId bestUpstreamDatabase() throws UpstreamDatabaseSelectionException { MemberId result = null; for ( UpstreamDatabaseSelectionStrategy strategy : strategies ) { log.debug( "Trying selection strategy [%s]", strategy.toString() ); try { Optional<MemberId> foundMemberByStrategy = strategy.upstreamDatabase(); if ( foundMemberByStrategy.isPresent() ) { result = foundMemberByStrategy.get(); break; } } catch ( NoSuchElementException ex ) { } } if ( result == null ) { throw new UpstreamDatabaseSelectionException( "Could not find an upstream database with which to connect." ); } log.debug( "Selected upstream database [%s]", result ); return result; }

Target:
public MemberId bestUpstreamDatabase() throws UpstreamDatabaseSelectionException { MemberId result = null; for ( UpstreamDatabaseSelectionStrategy strategy : strategies ) { log.debug( "Trying selection strategy [%s]", strategy.toString() ); try { if ( strategy.upstreamDatabase().isPresent() ) { result = strategy.upstreamDatabase().get(); break; } } catch ( NoSuchElementException ex ) { } } if ( result == null ) { throw new UpstreamDatabaseSelectionException( "Could not find an upstream database with which to connect." ); } log.debug( "Selected upstream database [%s]", result ); return result; }
Source:
public String getEmbedMapWikiCode(){ String mapID = mapFrame.getAttribute("data-mapid"); String r = "<imap map-id='"+mapID+"'/>"; return r; }

Target:
public String getEmbedMapWikiCode() { return "<imap map-id='" + mapFrame.getAttribute("data-mapid") + "'/>"; }
Source:
public void testGetValidTraceTypes() { for (Class<? extends ITmfTrace> traceType : fModule.getValidTraceTypes()) { assertTrue(fModule.appliesToTraceType(traceType)); } }

Target:
public void testGetValidTraceTypes() { TraceTypeHelper traceTypeHelper = TmfTraceType.getInstance().getTraceType(VALID_TRACE_TYPE); int traceTypeCount = 0; for (Class<? extends ITmfTrace> traceType : fModule.getValidTraceTypes()) { assertTrue(fModule.appliesToTraceType(traceType)); assertEquals(traceTypeHelper.getTraceClass(), traceType); traceTypeCount++; } assertEquals(1, traceTypeCount); }
Source:
static public <T> Flux<T> fluxInlineIfPossibleAsObs(Callable<Flux<T>> function, IRetryPolicy retryPolicy) { if (retryPolicy == null) { return Flux.defer(() -> { try { return function.call(); } catch (Exception e) { return Mono.error(e); } }); } else { return BackoffRetryUtility.fluxExecuteRetry(() -> function.call(), retryPolicy); } }

Target:
static public <T> Flux<T> fluxInlineIfPossibleAsObs(Callable<Flux<T>> function, IRetryPolicy retryPolicy) { if (retryPolicy == null) { return Flux.defer(() -> { try { return function.call(); } catch (Exception e) { return Flux.error(e); } }); } else { return BackoffRetryUtility.fluxExecuteRetry(() -> function.call(), retryPolicy); } }
Source:
public ExtensionProxy activate(String extensionName) { ExtensionEntry entry = loadedEntries.get(extensionName); if (entry == null) { throw new RuntimeException(String.format("No extensioned with instance name %1$s could be found", extensionName)); } if (entry.enabled) { entry.extension.getContext().put( TRACE_LOG_CONTEXT_KEY, LogFactory.getLog( String.format( "%1$s.%2$s.%3$s", getTraceLog(), entry.extension.getContext().get(Base.ContextKeys.EXTENSION_NAME), entry.extension.getContext().get(Base.ContextKeys.INSTANCE_NAME) ) ) ); try { ExtMap output = entry.extension.invoke( new ExtMap().mput( Base.InvokeKeys.COMMAND, Base.InvokeCommands.INITIALIZE ) ); } catch (Exception ex) { log.error( String.format( "Error in activating extension %1$s. Exception message is %2$s", entry.name, ex.getMessage() ) ); if (log.isDebugEnabled()) { log.debug(ex.toString(), ex); } throw new RuntimeException(ex); } synchronized (globalContext) { globalContext.<List<ExtMap>> get(Base.GlobalContextKeys.EXTENSIONS).add( new ExtMap().mput( Base.ExtensionRecord.INSTANCE_NAME, entry.extension.getContext().get(Base.ContextKeys.INSTANCE_NAME) ).mput( Base.ExtensionRecord.PROVIDES, entry.extension.getContext().get(Base.ContextKeys.PROVIDES) ).mput( Base.ExtensionRecord.EXTENSION, entry.extension.getExtension() ).mput( Base.ExtensionRecord.CONTEXT, entry.extension.getContext() ) ); } entry.activated = true; dumpConfig(entry.extension); setChanged(); notifyObservers(); } return entry != null ? entry.extension : null; }

Target:
public ExtensionProxy activate(String extensionName) { return activate(extensionName, false); }
Source:
public void swipeFromPointToPoint(int startX, int startY, int endX, int endY, int duration, int waitAfter) { startX = (int)((startX / 100f) * appNativeWidth); startY = (int)(((startY / 100f) * appNativeHeight) + taskbarNativeHeight); endX = (int)((endX / 100f) * appNativeWidth); endY = (int)(((endY / 100f) * appNativeHeight) + taskbarNativeHeight); if (mobileDriver.getContext() != "NATIVE_APP") { mobileDriver.context("NATIVE_APP"); } try { mobileDriver.swipe(startX, startY, endX, endY, duration); } catch (Exception e) try { Thread.sleep(waitAfter); } catch (Exception e) if (mobileDriver.getContext() != "WEBVIEW_1") { mobileDriver.context("WEBVIEW_1"); } }

Target:
public void swipeFromPointToPoint(int startX, int startY, int endX, int endY, int duration, int waitAfter) { String methodName = "swipeFromPointToPoint"; startX = (int)((startX / 100f) * appNativeWidth); startY = (int)(((startY / 100f) * appNativeHeight) + taskbarNativeHeight); endX = (int)((endX / 100f) * appNativeWidth); endY = (int)(((endY / 100f) * appNativeHeight) + taskbarNativeHeight); switchToContext(CONTEXT_NATIVE_APP, methodName); mobileDriver.swipe(startX, startY, endX, endY, duration); waitForFinish(waitAfter, methodName); switchToContext(CONTEXT_WEBVIEW_1, methodName); }
Source:
public void setNamedParameters(Map<String, Object> params) { if (params != null) params.forEach(this.namedParameters::put); }

Target:
public void setNamedParameters(Map<String, Object> params) { if (params == null) { namedParameters.clear(); } else { namedParameters.putAll(params); } }
Source:
public boolean supports(final JEEContext context) { val token = context.getRequestParameter(OAuth20Constants.TOKEN) .map(String::valueOf).orElse(StringUtils.EMPTY); val clientId = OAuth20Utils.getClientIdAndClientSecret(context).getLeft(); return StringUtils.isNotBlank(token) && StringUtils.isNotBlank(clientId); }

Target:
public boolean supports(final JEEContext context) { val token = context.getRequestParameter(OAuth20Constants.TOKEN) .map(String::valueOf).orElse(StringUtils.EMPTY); if (StringUtils.isBlank(token)) { return false; } val clientId = OAuth20Utils.getClientIdAndClientSecret(context).getLeft(); return StringUtils.isNotBlank(clientId); }
Source:
public Properties getProperties() { List<Element> elements = getElements( "*" ); Properties result = new Properties(); for ( Element e : elements ) { Node value = e.getFirstChild(); result.setProperty( e.getNodeName(), (value == null ? "" : e.getFirstChild().getNodeValue() ) ); } for ( String key : result.stringPropertyNames() ) { if ( result.getProperty( key ).startsWith( "${" ) ) { result.setProperty( key, getValue( result, key ) ); } } return result; }

Target:
public Properties getProperties() { List<Element> elements = getElements( "*" ); Properties result = new Properties(); for ( Element e : elements ) { Node value = e.getFirstChild(); result.setProperty( e.getNodeName(), (value == null ? "" : getPomView().resolveExpressions( e.getFirstChild().getNodeValue() ) ) ); } return result; }
Source:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { wasExternal = savedInstanceState.getBoolean(WAS_EXTERNAL_KEY); loginExtraWasConsumed = savedInstanceState.getBoolean(EXTRA_CONSUMED_KEY); } if (finishIfNotRoot()) { return; } ACRAUtil.registerAppData(); uiController = new HomeActivityUIController(this); sessionNavigator = new SessionNavigator(this); formAndDataSyncer = new FormAndDataSyncer(this); processFromExternalLaunch(savedInstanceState); processFromShortcutLaunch(); processFromLoginLaunch(); }

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (savedInstanceState != null) { loginExtraWasConsumed = savedInstanceState.getBoolean(EXTRA_CONSUMED_KEY); } if (finishIfNotRoot()) { return; } ACRAUtil.registerAppData(); uiController = new HomeActivityUIController(this); sessionNavigator = new SessionNavigator(this); formAndDataSyncer = new FormAndDataSyncer(this); processFromExternalLaunch(savedInstanceState); processFromShortcutLaunch(); processFromLoginLaunch(); }
Source:
public void setSourceContainers(ISourceContainer[] containers) { synchronized (this) { List<ISourceContainer> list = Arrays.asList(containers); ISourceContainer[] old = getSourceContainers(); for (ISourceContainer o : old) { if (!list.contains(o)) { o.dispose(); } } fSourceContainers = containers; for (ISourceContainer container : containers) { container.init(this); } } fResolvedElements = null; ISourceLookupParticipant[] participants = getParticipants(); for (ISourceLookupParticipant participant : participants) { participant.sourceContainersChanged(this); } }

Target:
public void setSourceContainers(ISourceContainer[] containers) { synchronized (this) { List<ISourceContainer> list = Arrays.asList(containers); ISourceContainer[] old = getSourceContainers(); for (ISourceContainer container : old) { if (!list.contains(container)) { container.dispose(); } } fSourceContainers = containers; for (ISourceContainer container : containers) { container.init(this); } } fResolvedElements = null; ISourceLookupParticipant[] participants = getParticipants(); for (ISourceLookupParticipant participant : participants) { participant.sourceContainersChanged(this); } }
Source:
public void undo() { if (fbType instanceof BasicFBType) { ((BasicFBType) fbType).getAlgorithm().add(((BasicFBType) fbType).getAlgorithm().indexOf(newAlgorithm), oldAlgorithm); updateECActions(false); ((BasicFBType) fbType).getAlgorithm().remove(newAlgorithm); } }

Target:
public void undo() { ((BasicFBType) fbType).getAlgorithm().add(((BasicFBType) fbType).getAlgorithm().indexOf(newAlgorithm), oldAlgorithm); updateECActions(false); ((BasicFBType) fbType).getAlgorithm().remove(newAlgorithm); }
Source:
public TopologyInfo getTopologyInfoWithOpts(String id, GetInfoOptions options) throws NotAliveException, AuthorizationException, TException { return nimbus.getTopologyInfoWithOpts(id, options); }

Target:
public TopologyInfo getTopologyInfoWithOpts(String id, GetInfoOptions options) throws TException { return nimbus.getTopologyInfoWithOpts(id, options); }
Source:
public void testUnassignServer() { FirewallPolicy result = firewallPolicyApi().unassignServerIp(currentFirewallPolicy.id(), currentServer.ips().get(0).id()); assertNotNull(result); assertEquals(result.id(), currentFirewallPolicy.id()); }

Target:
public void testUnassignServer() { FirewallPolicy result = firewallPolicyApi().unassignServerIp(currentFirewallPolicy.id(), currentServer.ips().get(0).id()); assertNotNull(result); assertEquals(result.serverIps().size(), 0); }
Source:
public void addGeneratedProfiles(String expId, String folderPath, String inputFileName, String metaData, String grVersion, String uploader, boolean isPrivate) throws SQLException, IOException { Experiment e = expMethods.getExperiment(expId); if (e == null) { throw new IOException(expId + " does not exist."); } Genome g = genMethods.getGenomeRelease(grVersion); if (g == null) { throw new IOException("Invalid Genome Release! " + grVersion + " does not exist"); } File profileFolder = new File(folderPath); if (!profileFolder.exists()) { throw new IOException("There are no profiles in this folder!"); } for (File f : profileFolder.listFiles()) { if (!f.getName().equals(inputFileName)) { String checkSumMD5; long fileSize; try (FileInputStream is = new FileInputStream(f)) { checkSumMD5 = DigestUtils.md5Hex(is); } fileSize = f.length(); fileMethods.addGeneratedFile(e.getID(), FileTuple.PROFILE, f.getPath(), inputFileName, metaData, uploader, isPrivate, grVersion, checkSumMD5, fileSize); } } }

Target:
public void addGeneratedProfiles(String expId, String folderPath, String inputFileName, String metaData, String grVersion, String uploader, boolean isPrivate) throws SQLException, IOException { Experiment e = expMethods.getExperiment(expId); if (e == null) { throw new IOException(expId + " does not exist."); } Genome g = genMethods.getGenomeRelease(grVersion); if (g == null) { throw new IOException("Invalid Genome Release! " + grVersion + " does not exist"); } File profileFolder = new File(folderPath); if (!profileFolder.exists()) { throw new IOException("There are no profiles in this folder!"); } for (File f : profileFolder.listFiles()) { if (!f.getName().equals(inputFileName)) { String checkSumMD5; try (FileInputStream is = new FileInputStream(f)) { checkSumMD5 = DigestUtils.md5Hex(is); } fileMethods.addGeneratedFile(e.getID(), FileTuple.PROFILE, f.getPath(), inputFileName, metaData, uploader, isPrivate, grVersion, checkSumMD5, f.length()); } } }
Source:
public static <P extends VdcActionParametersBase> CommandBase<P> createCommand(VdcActionType action, P parameters, CommandContext commandContext) { try { Constructor<CommandBase<? extends VdcActionParametersBase>> constructor = commandContext != null ? findCommandConstructor(getCommandClass(action.name(), CommandSuffix), parameters.getClass(), commandContext.getClass()) : findCommandConstructor(getCommandClass(action.name(), CommandSuffix), parameters.getClass()); CommandBase<P> cmd = (CommandBase<P>) constructor.newInstance(new Object[] { parameters }); Injector.injectMembers(cmd); return cmd; } catch (InvocationTargetException ex) { log.error("Error in invocating CTOR of command " + action.name() + ". Exception is ", ex); return null; } catch (Exception ex) { log.error("An exception has occured while trying to create a command object for command " + action.name(), ex); return null; } }

Target:
public static <P extends VdcActionParametersBase> CommandBase<P> createCommand(VdcActionType action, P parameters, CommandContext commandContext) { try { CommandBase<P> result = null; if (commandContext == null) { result = (CommandBase<P>)findCommandConstructor(getCommandClass(action.name(), CommandSuffix), parameters.getClass()).newInstance(parameters); } else { result = (CommandBase<P>) findCommandConstructor(getCommandClass(action.name(), CommandSuffix), parameters.getClass(), commandContext.getClass()).newInstance(parameters, commandContext); } Injector.injectMembers(result); return result; } catch (InvocationTargetException ex) { log.error("Error in invocating CTOR of command " + action.name() + ". Exception is ", ex); return null; } catch (Exception ex) { log.error("An exception has occured while trying to create a command object for command " + action.name(), ex); return null; } }
Source:
protected void onCancelled() { super.onCancelled(); if(wasKeyLoggedIn) { CommCareApplication._().getSession().startLogout(); } }

Target:
protected void onCancelled() { super.onCancelled(); if(wasKeyLoggedIn) { try { CommCareApplication._().getSession().startLogout(); } catch (SessionUnavailableException e) { } } }
Source:
public View getView(Context context) { view = LayoutInflater.from(context).inflate(getViewResource(), null); BrickViewProvider.setAlphaOnView(view, alphaValue); final Brick instance = this; int checkboxVisibility = View.GONE; boolean enabled = true; boolean isChecked = false; if (checkbox != null) { checkboxVisibility = checkbox.getVisibility(); enabled = checkbox.isEnabled(); isChecked = checkbox.isChecked(); } checkbox = view.findViewById(R.id.brick_checkbox); checkbox.setChecked(isChecked); checkbox.setVisibility(checkboxVisibility); checkbox.setEnabled(enabled); checkbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { adapter.handleCheck(instance, ((CheckBox) view).isChecked()); } }); return view; }

Target:
public View getView(Context context) { view = LayoutInflater.from(context).inflate(getViewResource(), null); BrickViewProvider.setAlphaOnView(view, alphaValue); int checkboxVisibility = View.GONE; boolean enabled = true; boolean isChecked = false; if (checkbox != null) { checkboxVisibility = checkbox.getVisibility(); enabled = checkbox.isEnabled(); isChecked = checkbox.isChecked(); } checkbox = view.findViewById(R.id.brick_checkbox); checkbox.setChecked(isChecked); checkbox.setVisibility(checkboxVisibility); checkbox.setEnabled(enabled); checkbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { adapter.handleCheck(BrickBaseType.this, ((CheckBox) view).isChecked()); } }); return view; }
Source:
public void mercury_navigation_navigationElementsAnonymousUser() { init(); topBar.openNavigation(); Assertion.assertTrue(navigation.isUserAvatarVisible()); Assertion.assertFalse(navigation.isUserProfileLinkVisible()); Assertion.assertFalse(navigation.isLogoutLinkVisible()); }

Target:
public void mercury_navigation_navigationElementsAnonymousUser() { init(); topBar.openNavigation(); Assertion.assertTrue(navigation.isUserAvatarVisible()); Assertion.assertFalse(navigation.isUserProfileLinkVisible()); Assertion.assertFalse(navigation.isLogoutLinkVisible()); Assertion.assertEquals(navigation.getNavigationHeaderText(), "Sign In | Register"); }
Source:
private boolean isDelete(Conflict conflict) { return StringUtils.equalsIgnoreCase(conflict.getOperationKind().toString(), "delete"); }

Target:
private boolean isDelete(Conflict conflict) { return OperationKind.DELETE == conflict.getOperationKind(); }
Source:
public Number nextValue(EmbeddedCacheManager cacheManager, NextValueRequest request) { CounterManager counterManager = EmbeddedCounterManagerFactory.asCounterManager( cacheManager ); String counterName = ( IdSourceKeyMetadata.IdSourceType.SEQUENCE.equals( request.getKey().getMetadata().getType() ) ) ? request.getKey().getTable() : request.getKey().getColumnValue(); if ( !counterManager.isDefined( counterName ) ) { boolean definedByCurrentThread = counterManager.defineCounter( counterName, CounterConfiguration.builder( CounterType.UNBOUNDED_STRONG ) .initialValue( request.getInitialValue() ) .storage( Storage.VOLATILE ) .build() ); if ( definedByCurrentThread ) { return new Long( request.getInitialValue() ); } } StrongCounter strongCounter = counterManager.getStrongCounter( counterName ); try { return strongCounter.addAndGet( request.getIncrement() ).get(); } catch (ExecutionException | InterruptedException e) { throw new HibernateException( "Interrupting Operation " + e.getMessage(), e ); } }

Target:
public Number nextValue(EmbeddedCacheManager cacheManager, NextValueRequest request) { CounterManager counterManager = EmbeddedCounterManagerFactory.asCounterManager( cacheManager ); String counterName = ( IdSourceKeyMetadata.IdSourceType.SEQUENCE.equals( request.getKey().getMetadata().getType() ) ) ? request.getKey().getTable() : request.getKey().getColumnValue(); if ( !counterManager.isDefined( counterName ) ) { boolean definedByCurrentThread = counterManager.defineCounter( counterName, CounterConfiguration.builder( CounterType.UNBOUNDED_STRONG ) .initialValue( request.getInitialValue() ) .storage( Storage.VOLATILE ) .build() ); if ( definedByCurrentThread ) { return Long.valueOf( request.getInitialValue() ); } } StrongCounter strongCounter = counterManager.getStrongCounter( counterName ); try { return strongCounter.addAndGet( request.getIncrement() ).get(); } catch (ExecutionException | InterruptedException e) { String message = "Exception while incrementing the sequence " + counterName ; log.error( message ); throw new HibernateException( message + " : " + e.getMessage(), e ); } }
Source:
public <S extends Message, T extends Message> void dispatch(SinkModule<S, T> module, String topic, T message) { try (MDCCloseable mdc = Logging.withPrefixCloseable(MessageConsumerManager.LOG_PREFIX)) { LOG.trace("dispatch({}): sending message {}", topic, message); final ProducerRecord<String,byte[]> record = new ProducerRecord<>(topic, module.marshal(message)); while(true) { try { final Future<RecordMetadata> future = producer.send(record); future.get(); break; } catch (InterruptedException e) { LOG.warn("Interrupted while sending message to topic {}.", topic, e); break; } catch (ExecutionException e) { LOG.warn("Timeout occured while sending message to topic {}, it will be attempted again.", topic, e); } } } }

Target:
public <S extends Message, T extends Message> void dispatch(SinkModule<S, T> module, String topic, T message) { try (MDCCloseable mdc = Logging.withPrefixCloseable(MessageConsumerManager.LOG_PREFIX)) { LOG.trace("dispatch({}): sending message {}", topic, message); final ProducerRecord<String, String> record = new ProducerRecord<>(topic, module.marshal(message)); while(true) { try { final Future<RecordMetadata> future = producer.send(record); future.get(); break; } catch (InterruptedException e) { LOG.warn("Interrupted while sending message to topic {}.", topic, e); Thread.currentThread().interrupt(); break; } catch (ExecutionException e) { LOG.warn("Timeout occured while sending message to topic {}, it will be attempted again.", topic); } } } }
Source:
public void testTryLockWithTimeoutAfterLockWithSmallTimeout() throws Throwable { assertTrue(await(lock.tryLock())); CompletableFuture<Boolean> tryLock = lock.tryLock(1, TimeUnit.NANOSECONDS); TimeUnit.NANOSECONDS.sleep(1); await(lock.unlock()); assertFalse(await(tryLock)); }

Target:
public void testTryLockWithTimeoutAfterLockWithSmallTimeout() throws Throwable { assertTrue(await(lock.tryLock())); assertFalse(await(lock.tryLock(1, TimeUnit.NANOSECONDS))); }
Source:
public BlockOutStream getOutStream(long blockId, long blockSize, WorkerNetAddress address, OutStreamOptions options) throws IOException { if (blockSize == -1) { try (CloseableResource<BlockMasterClient> blockMasterClientResource = mContext.acquireBlockMasterClientResource()) { blockSize = blockMasterClientResource.get().getBlockInfo(blockId).getLength(); } } if (address == null) { throw new ResourceExhaustedException(ExceptionMessage.NO_SPACE_FOR_BLOCK_ON_WORKER .getMessage(FormatUtils.getSizeFromBytes(blockSize))); } LOG.debug("Create block outstream for of block size at address {}, using options: {}", blockId, blockSize, address, options); if (!address.getContainerHost().equals("")) { String containerName = address.getContainerHost(); LOG.debug("Worker is in a container. Replace host with container host {}", address.getHost(), containerName); address.setHost(containerName); } return BlockOutStream.create(mContext, blockId, blockSize, address, options); }

Target:
public BlockOutStream getOutStream(long blockId, long blockSize, WorkerNetAddress address, OutStreamOptions options) throws IOException { if (blockSize == -1) { try (CloseableResource<BlockMasterClient> blockMasterClientResource = mContext.acquireBlockMasterClientResource()) { blockSize = blockMasterClientResource.get().getBlockInfo(blockId).getLength(); } } if (address == null) { throw new ResourceExhaustedException(ExceptionMessage.NO_SPACE_FOR_BLOCK_ON_WORKER .getMessage(FormatUtils.getSizeFromBytes(blockSize))); } LOG.debug("Create block outstream for of block size at address {}, using options: {}", blockId, blockSize, address, options); return BlockOutStream.create(mContext, blockId, blockSize, address, options); }
Source:
public static void beforeAll() throws Exception { com.cloudant.client.api.Replication r = account.replication(); r.source(CloudantClientHelper.getReplicationSourceUrl("animaldb")); r.createTarget(true); r.target(dbResource.getDbURIWithUserInfo()); r.trigger(); }

Target:
public static void beforeAll() throws Exception { com.cloudant.client.api.Replication r = account.replication(); r.source(getReplicationSourceUrl("animaldb")); r.createTarget(true); r.target(dbResource.getDbURIWithUserInfo()); r.trigger(); }
Source:
public static URL[] getURLs(String value, Bundle definingBundle) { if (value == null) { return null; } StringTokenizer tokens = new StringTokenizer(value, ","); List<URL> array = new ArrayList<>(10); while (tokens.hasMoreTokens()) { array.add(getUrl(tokens.nextToken().trim(), definingBundle)); } return (URL[]) array.toArray(new URL[array.size()]); }

Target:
private static List<URL> getURLs(String value, Bundle definingBundle) { if (value == null) { return Collections.emptyList(); } StringTokenizer tokens = new StringTokenizer(value, ","); List<URL> array = new ArrayList<>(10); while (tokens.hasMoreTokens()) { Optional<URL> urlToken = getUrl(tokens.nextToken().trim(), definingBundle); if (urlToken.isPresent()) { array.add(urlToken.get()); } } return array; }
Source:
private boolean updateEnvironment(ConsumerDTO updated, Consumer toUpdate) { boolean changesMade = false; boolean environmentFound = false; Environment e = null; String environmentId = updated.getEnvironment() == null ? null : updated.getEnvironment().getId(); String environmentName = updated.getEnvironment() == null ? null : updated.getEnvironment().getName(); if (environmentName != null && environmentId == null) { List<Environment> environment = environmentCurator.listForOwnerByName(toUpdate.getOwner(), environmentName).list(); if (!environment.isEmpty() && environment.size() == 1) { e = environment.get(0); environmentId = environment.get(0).getId(); environmentFound = true; } else { throw new NotFoundException(i18n.tr( "Environment with name \"{0}\" could not be found.", environmentName)); } } if (environmentId != null && (toUpdate.getEnvironmentId() == null || !toUpdate.getEnvironmentId().equals(environmentId))) { if (!environmentFound) { e = environmentCurator.get(environmentId); if (e == null) { throw new NotFoundException(i18n.tr( "Environment with ID \"{0}\" could not be found.", environmentId)); } } changesMade = true; log.info("Updating environment to: {}", environmentId); } if (e != null && changesMade) { toUpdate.setEnvironment(e); Owner owner = ownerCurator.findOwnerById(toUpdate.getOwnerId()); if (owner.isContentAccessEnabled()) { toUpdate.setContentAccessCert(null); contentAccessCertService.removeContentAccessCert(toUpdate); } poolManager.regenerateCertificatesOf(toUpdate, true); } return changesMade; }

Target:
private boolean updateEnvironment(ConsumerDTO updated, Consumer toUpdate) { if (updated.getEnvironment() == null) { return false; } boolean changesMade = false; String environmentId = updated.getEnvironment() == null ? null : updated.getEnvironment().getId(); String environmentName = updated.getEnvironment() == null ? null : updated.getEnvironment().getName(); String validatedEnvId = null; if (environmentId != null) { if (toUpdate.getEnvironmentId() == null || !toUpdate.getEnvironmentId().equals(environmentId)) { if (!environmentCurator.exists(environmentId)) { throw new NotFoundException(i18n.tr( "Environment with ID \"{0}\" could not be found.", environmentId)); } validatedEnvId = environmentId; } } else if (environmentName != null) { String envId = this.environmentCurator. getEnvironmentIdByName(toUpdate.getOwnerId(), environmentName); if (envId == null) { throw new NotFoundException(i18n.tr( "Environment with name \"{0}\" could not be found.", environmentName)); } if (toUpdate.getEnvironmentId() == null || !envId.equals(toUpdate.getEnvironmentId())) { validatedEnvId = envId; } } if (validatedEnvId != null) { toUpdate.setEnvironmentId(validatedEnvId); Owner owner = ownerCurator.findOwnerById(toUpdate.getOwnerId()); if (owner.isContentAccessEnabled()) { toUpdate.setContentAccessCert(null); contentAccessCertService.removeContentAccessCert(toUpdate); } poolManager.regenerateCertificatesOf(toUpdate, true); changesMade = true; } return changesMade; }
Source:
public void delVirtualPortMapping(UUID hostIdentifier, UUID portId) throws StateAccessException, SerializationException { String virtualMappingPath = paths.getHostVrnPortMappingPath(hostIdentifier, portId); List<Op> ops = new ArrayList<>(); if (zk.exists(virtualMappingPath)) { ops.add(zk.getDeleteOp(virtualMappingPath)); PortConfig port = portZkManager.get(portId); if (port.getHostId().equals(hostIdentifier)) { ops.add(getMapUpdatePortOp(port, portId, null, null)); } zk.multi(ops); } }

Target:
public void delVirtualPortMapping(UUID hostIdentifier, UUID portId) throws StateAccessException, SerializationException { String virtualMappingPath = paths.getHostVrnPortMappingPath(hostIdentifier, portId); List<Op> ops = new ArrayList<>(); if (zk.exists(virtualMappingPath)) { ops.add(zk.getDeleteOp(virtualMappingPath)); PortConfig port = portZkManager.get(portId); if (port.getHostId() != null && port.getHostId().equals(hostIdentifier)) { ops.add(getMapUpdatePortOp(port, portId, null, null)); } zk.multi(ops); } }
Source:
public void createCartInStore(){ StoreFixtures.withStore(client(), store -> { final CartDraft cartDraft = CartDraft.of(EUR).withCountry(DE); final Cart cart = client().executeBlocking(CartInStoreCreateCommand.of(store.getKey(), cartDraft)); assertThat(cart).isNotNull(); assertThat(cart.getStore()).isNotNull(); assertThat(cart.getStore().getKey()).isEqualTo(store.getKey()); client().executeBlocking(CartDeleteCommand.of(cart)); }); }

Target:
public void createCartInStore(){ withStore(client(), store -> { final CartDraft cartDraft = CartDraft.of(EUR).withCountry(DE); final Cart cart = client().executeBlocking(CartInStoreCreateCommand.of(store.getKey(), cartDraft)); assertThat(cart).isNotNull(); assertThat(cart.getStore()).isNotNull(); assertThat(cart.getStore().getKey()).isEqualTo(store.getKey()); client().executeBlocking(CartDeleteCommand.of(cart)); }); }
Source:
public float getBlockLocalityIndex(String host) { return (float) getBlocksLocalityWeightInternal(host, e -> e.weight) / (float) uniqueBlocksTotalWeight; }

Target:
public float getBlockLocalityIndex(String host) { if (uniqueBlocksTotalWeight == 0) { return 0.0f; } else { return (float) getBlocksLocalityWeightInternal(host, HostAndWeight::getWeight) / (float) uniqueBlocksTotalWeight; } }
Source:
public void testNonExistentAuthority() { File file = buildPath(mContext.getFilesDir(), "file.test"); try { FileProvider.getUriForFile(mContext, "com.example.nonexistent", file); fail("Expected exception for non-existent authority"); } catch (IllegalArgumentException e) { } }

Target:
public void testNonExistentAuthority() { File file = buildPath(mContext.getFilesDir(), "file.test"); try { FileProvider.getUriForFile(mContext, "example.nonexistent", file); fail("Expected exception for non-existent authority"); } catch (IllegalArgumentException e) { assertEquals("Couldn't find meta-data for provider with authority example.nonexistent", e.getMessage()); } }
Source:
public void testErrorForwarding() throws Exception { new Context() {{ runTest(() -> { final Exception testException = new Exception("test Exeption"); testingLeaderRetrievalDriver.getFatalErrorHandler().onFatalError(testException); assertThat(testingListener.getError().getMessage(), containsString(testException.getMessage())); }); }}; }

Target:
public void testErrorForwarding() throws Exception { new Context() {{ runTest(() -> { final Exception testException = new Exception("test exception"); testingLeaderRetrievalDriver.onFatalError(testException); testingListener.waitForError(timeout); assertThat(testingListener.getError(), FlinkMatchers.containsCause(testException)); }); }}; }
Source:
public void revisionActionsTwoChangeChangesInTopic() throws Exception { String changeId = createChangeWithTopic("foo2").getChangeId(); approve(changeId); createChangeWithTopic("foo2").getChangeId(); Map<String, ActionInfo> actions = getActions(changeId); assertThat(actions).containsKey("cherrypick"); assertThat(actions).containsKey("submit"); assertThat(actions).hasSize(2); if (isSubmitWholeTopicEnabled()) { ActionInfo info = actions.get("submit"); assertThat(info.enabled).isEqualTo(null); assertThat(info.label).isEqualTo("Submit whole topic"); assertThat(info.method).isEqualTo("POST"); assertThat(info.title).isEqualTo("Other changes in this topic are not ready"); } else { noSubmitWholeTopicAssertions(actions); } }

Target:
public void revisionActionsTwoChangeChangesInTopic() throws Exception { String changeId = createChangeWithTopic("foo2").getChangeId(); approve(changeId); createChangeWithTopic("foo2").getChangeId(); Map<String, ActionInfo> actions = getActions(changeId); assertThat(actions).containsKey("cherrypick"); assertThat(actions).containsKey("submit"); assertThat(actions).hasSize(2); if (isSubmitWholeTopicEnabled()) { ActionInfo info = actions.get("submit"); assertThat(info.enabled).isNull(); assertThat(info.label).isEqualTo("Submit whole topic"); assertThat(info.method).isEqualTo("POST"); assertThat(info.title).isEqualTo("Other changes in this topic are not ready"); } else { noSubmitWholeTopicAssertions(actions); } }
Source:
public void setup() throws Exception { contexts.startRequestScope(); contexts.startSessionScope(); contexts.startApplicationScope(); initEvent.fire(new VRaptorInitialized(null)); super.setup(); }

Target:
public void setup() throws Exception { contexts.startApplicationScope(); contexts.startSessionScope(); initEvent.fire(new VRaptorInitialized(null)); super.setup(); }
Source:
private RebaseResult abort() throws IOException { try { String commitId = readFile(repo.getDirectory(), "ORIG_HEAD"); monitor.beginTask("Aborting rebase: resetting to " + commitId, ProgressMonitor.UNKNOWN); RevCommit commit = walk.parseCommit(repo.resolve(commitId)); DirCacheCheckout dco = new DirCacheCheckout(repo, repo .lockDirCache(), commit.getTree()); dco.setFailOnConflict(false); dco.checkout(); walk.release(); } finally { monitor.endTask(); } try { String headName = readFile(rebaseDir, "head-name"); if (headName.startsWith(Constants.R_REFS)) { monitor.beginTask("Resetting head to " + headName, ProgressMonitor.UNKNOWN); RefUpdate refUpdate = repo.updateRef(Constants.HEAD, false); Result res = refUpdate.link(headName); switch (res) { case FAST_FORWARD: case FORCED: case NO_CHANGE: break; default: throw new IOException("Could not abort rebase"); } } deleteRecursive(rebaseDir); return new RebaseResult(Status.ABORTED); } finally { monitor.endTask(); } }

Target:
private RebaseResult abort() throws IOException { try { String commitId = readFile(repo.getDirectory(), "ORIG_HEAD"); monitor.beginTask(MessageFormat.format( JGitText.get().abortingRebase, commitId), ProgressMonitor.UNKNOWN); RevCommit commit = walk.parseCommit(repo.resolve(commitId)); DirCacheCheckout dco = new DirCacheCheckout(repo, repo .lockDirCache(), commit.getTree()); dco.setFailOnConflict(false); dco.checkout(); walk.release(); } finally { monitor.endTask(); } try { String headName = readFile(rebaseDir, "head-name"); if (headName.startsWith(Constants.R_REFS)) { monitor.beginTask(MessageFormat.format( JGitText.get().resettingHead, headName), ProgressMonitor.UNKNOWN); RefUpdate refUpdate = repo.updateRef(Constants.HEAD, false); Result res = refUpdate.link(headName); switch (res) { case FAST_FORWARD: case FORCED: case NO_CHANGE: break; default: throw new IOException("Could not abort rebase"); } } deleteRecursive(rebaseDir); return new RebaseResult(Status.ABORTED); } finally { monitor.endTask(); } }
Source:
private void loadSchema(final String schemaFile) throws IOException { final XmlSchemaCollection schemaCollection = new XmlSchemaCollection(); try (final InputStream schemaStream = new FileInputStream("src/test/resources/" + schemaFile)) { schema = schemaCollection.read(new StreamSource(schemaStream)); } }

Target:
private void loadSchema(final String schemaFile) throws IOException { final XmlSchemaCollection schemaCollection = new XmlSchemaCollection(); try (final InputStream schemaStream = getClass().getClassLoader().getResourceAsStream(schemaFile)) { schema = schemaCollection.read(new StreamSource(schemaStream)); } }
Source:
NettyServerCnxnFactory() { x509Util = new ClientX509Util(); EventLoopGroup bossGroup = new NioEventLoopGroup(0, Executors.newCachedThreadPool()); EventLoopGroup workerGroup = new NioEventLoopGroup(0, Executors.newCachedThreadPool()); bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .option(ChannelOption.SO_REUSEADDR, true) .childOption(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_LINGER, -1) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (secure) { initSSL(pipeline); } pipeline.addLast("servercnxnfactory", channelHandler); } }); ByteBufAllocator testAllocator = TEST_ALLOCATOR.get(); if (testAllocator != null) { bootstrap.option(ChannelOption.ALLOCATOR, testAllocator) .childOption(ChannelOption.ALLOCATOR, testAllocator); } bootstrap.validate(); }

Target:
NettyServerCnxnFactory() { x509Util = new ClientX509Util(); EventLoopGroup bossGroup = NettyUtils.newNioOrEpollEventLoopGroup(); EventLoopGroup workerGroup = NettyUtils.newNioOrEpollEventLoopGroup(); ServerBootstrap bootstrap = new ServerBootstrap() .group(bossGroup, workerGroup) .channel(NettyUtils.nioOrEpollServerSocketChannel()) .option(ChannelOption.SO_REUSEADDR, true) .childOption(ChannelOption.TCP_NODELAY, true) .childOption(ChannelOption.SO_LINGER, -1) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); if (secure) { initSSL(pipeline); } pipeline.addLast("servercnxnfactory", channelHandler); } }); this.bootstrap = configureBootstrapAllocator(bootstrap); this.bootstrap.validate(); }
Source:
private void readHeaders() throws IOException { String line; while ((line = in.readString()) != PacketLineIn.END) { if (line.startsWith("restart ")) restartToken = line.substring("restart ".length()); else if (line.startsWith("last-pack-number ")) lastPackId = line.substring("last-pack-number ".length()); } }

Target:
private Header readHeaders() throws IOException { Header h = new Header(); String line; while ((line = in.readString()) != PacketLineIn.END) { if (line.startsWith("restart ")) h.restartToken = line.substring("restart ".length()); else if (line.startsWith("last-pack-number ")) h.lastPackId = line.substring("last-pack-number ".length()); } return h; }
Source:
public void testRibbonLoadBalancingHttpClient() { RibbonCommandContext context = new RibbonCommandContext("foo"," GET", "http://localhost", false, new LinkedMultiValueMap<String, String>(), new LinkedMultiValueMap<String, String>(), null, new ArrayList<RibbonRequestCustomizer>(), 0l, null); HttpClientRibbonCommand command = httpClientRibbonCommandFactory.create(context); RibbonLoadBalancingHttpClient ribbonClient = command.getClient(); CloseableHttpClient httpClient = getField(ribbonClient, "delegate"); MockingDetails httpClientDetails = mockingDetails(httpClient); assertTrue(httpClientDetails.isMock()); }

Target:
public void testRibbonLoadBalancingHttpClient() { RibbonCommandContext context = new RibbonCommandContext("foo"," GET", "http://localhost", false, new LinkedMultiValueMap<String, String>(), new LinkedMultiValueMap<String, String>(), null, new ArrayList<RibbonRequestCustomizer>(), 0l); HttpClientRibbonCommand command = httpClientRibbonCommandFactory.create(context); RibbonLoadBalancingHttpClient ribbonClient = command.getClient(); CloseableHttpClient httpClient = getField(ribbonClient, "delegate"); MockingDetails httpClientDetails = mockingDetails(httpClient); assertTrue(httpClientDetails.isMock()); }
Source:
public void fetchRegions () { LOGGER.info("Fetching ANSS Authoritative Regions from Geoserve"); File regionsJson = new File(REGIONS_JSON); try { JsonObject json = this.geoserveLayersService.getLayer("anss"); this.regions = new RegionsJSON().parseRegions(json); LOGGER.info("Loaded ANSS Authoritative Regions from Geoserve"); FileUtils.writeFileThenMove( new File(REGIONS_JSON + ".temp"), regionsJson, json.toString().getBytes()); LOGGER.finer("Storing ANSS Authoritative Regions to " + REGIONS_JSON); return; } catch (Exception e) { LOGGER.log(Level.WARNING, "Error updating ANSS Authoritative Regions", e); } if (regionsJson.exists()) { LOGGER.finer("Loading ANSS Authoritative Regions from " + REGIONS_JSON); try (InputStream in = StreamUtils.getInputStream(regionsJson)) { JsonObject json = Json.createReader(in).readObject(); this.regions = new RegionsJSON().parseRegions(json); LOGGER.fine("Loaded ANSS Authoritative Regions from " + REGIONS_JSON + ", last modified=" + XmlUtils.formatDate( new Date(regionsJson.lastModified()))); return; } catch (Exception e) { LOGGER.log(Level.WARNING, "Error loading ANSS Authoritative Regions from " + REGIONS_JSON, e); } } LOGGER.warning("Unable to load ANSS Authoritative Regions"); }

Target:
public void fetchRegions () { try { this.regions = loadFromGeoserve(); } catch (Exception e) { LOGGER.log(Level.WARNING, "Error fetching ANSS Regions from geoserve", e); try { if (this.regions == null) { this.regions = loadFromFile(); } } catch (Exception e2) { LOGGER.log(Level.WARNING, "Error fetching ANSS Regions from local file", e); } } }
Source:
public byte[] readRound(long seq) throws IOException { lock.readLock().lock(); try { byte[] result = currentLog.readRound(seq); byte[] experimentalResult = experimentalLog.readRound(seq); if (!Arrays.equals(result, experimentalResult)) { log.error("Mismatch in reading round for sequence number between legacy and current " + "implementations. Legacy result {}, current result {}.", SafeArg.of("sequence", seq), UnsafeArg.of("legacy", hydrator.hydrateFromBytes(result)), UnsafeArg.of("current", hydrator.hydrateFromBytes(experimentalResult))); } return result; } finally { lock.readLock().unlock(); } }

Target:
public byte[] readRound(long seq) throws IOException { lock.readLock().lock(); try { byte[] result = currentLog.readRound(seq); byte[] experimentalResult = safeReadFromExperimental(psl -> psl.readRound(seq)); if (!Arrays.equals(result, experimentalResult)) { log.error("Mismatch in reading round for sequence number between legacy and current " + "implementations. Legacy result {}, current result {}.", SafeArg.of("sequence", seq), UnsafeArg.of("legacy", hydrateIfNotNull(result)), UnsafeArg.of("current", hydrateIfNotNull(experimentalResult))); } return result; } finally { lock.readLock().unlock(); } }
Source:
public synchronized void shutdown() { shutdown.set(true); for (ManagedConnectionPool mcp : pools.values()) mcp.shutdown(); pools.clear(); }

Target:
public synchronized void shutdown() { for (ManagedConnectionPool mcp : pools.values()) mcp.shutdown(); pools.clear(); }
Source:
public void testSensitivity(final double expected, final File metricsFile, final double alleleFraction, final int sampleSize) throws Exception { final double tolerance = 0.02; final MetricsFile Metrics = new MetricsFile(); Metrics.read(new FileReader(metricsFile)); final List<Histogram<Integer>> histograms = Metrics.getAllHistograms(); final Histogram<Integer> depthHistogram = histograms.get(0); final Histogram<Integer> qualityHistogram = histograms.get(1); final double result = TheoreticalSensitivity.theoreticalSensitivity(depthHistogram, qualityHistogram, sampleSize, 3, alleleFraction); Assert.assertEquals(result, expected, tolerance); }

Target:
public void testSensitivity(final double expected, final File metricsFile, final double alleleFraction, final int sampleSize) throws Exception { final double tolerance = 0.02; final MetricsFile metrics = new MetricsFile(); try (final FileReader metricsFileReader = new FileReader(metricsFile)) { metrics.read(metricsFileReader); } final List<Histogram<Integer>> histograms = metrics.getAllHistograms(); final Histogram<Integer> depthHistogram = histograms.get(0); final Histogram<Integer> qualityHistogram = histograms.get(1); final double result = TheoreticalSensitivity.theoreticalSensitivity(depthHistogram, qualityHistogram, sampleSize, 3, alleleFraction); Assert.assertEquals(result, expected, tolerance); }
Source:
public static int randomInt(int max) { return SolRandom.randomInt(0f, max); }

Target:
public static int randomInt(int max) { return SolRandom.randomInt(0, max); }
Source:
private boolean shouldEnablePlatformSpecificConfig( OptionValueDescription enablePlatformSpecificConfigDescription, ListMultimap<String, RcChunkOfArgs> commandToRcArgs) { if (enablePlatformSpecificConfigDescription == null || !(boolean) enablePlatformSpecificConfigDescription.getValue()) { return false; } Multiset<String> keys = commandToRcArgs.keys(); for (String commandName : getCommandNamesToParse(commandAnnotation)) { String defaultConfigDef = commandName + ":" + OS.getCurrent().getCanonicalName(); if (keys.contains(defaultConfigDef)) { return true; } } return false; }

Target:
private boolean shouldEnablePlatformSpecificConfig( OptionValueDescription enablePlatformSpecificConfigDescription, ListMultimap<String, RcChunkOfArgs> commandToRcArgs) { if (enablePlatformSpecificConfigDescription == null || !(boolean) enablePlatformSpecificConfigDescription.getValue()) { return false; } for (String commandName : getCommandNamesToParse(commandAnnotation)) { String defaultConfigDef = commandName + ":" + OS.getCurrent().getCanonicalName(); if (commandToRcArgs.containsKey(defaultConfigDef)) { return true; } } return false; }
Source:
public UserResetTokenDTO create(String resetToken, Long userId) { UserResetTokenEntity entity = new UserResetTokenEntity(); entity.setUserResetToken(resetToken); entity.setUserId(userId); entity.setCreationDate(new Date()); entity.setLastModifiedDate(new Date()); if(Util.getCurrentUser() != null) { entity.setLastModifiedUser(Util.getCurrentUser().getId()); } else { entity.setLastModifiedUser(userId); } entity.setDeleted(false); create(entity); return new UserResetTokenDTO(entity); }

Target:
public UserResetTokenDTO create(String resetToken, Long userId) { UserResetTokenEntity entity = new UserResetTokenEntity(); entity.setUserResetToken(resetToken); entity.setUserId(userId); if (Util.getCurrentUser() != null) { entity.setLastModifiedUser(Util.getCurrentUser().getId()); } else { entity.setLastModifiedUser(userId); } entity.setDeleted(false); create(entity); return new UserResetTokenDTO(entity); }