auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public InputSource resolveEntity(String systemId, String publicId) throws IOException, SAXException { InputSource result; if (Parser.HTTPS_TESTNG_DTD_URL.equals(publicId)) { m_validate = true; InputStream is = getClass().getClassLoader().getResourceAsStream(Parser.TESTNG_DTD); if (null == is) { is = Thread.currentThread().getContextClassLoader().getResourceAsStream(Parser.TESTNG_DTD); if (null == is) { System.out.println( "WARNING: couldn't find in classpath " + publicId + "\n" + "Fetching it from the Web site."); result = super.resolveEntity(systemId, publicId); } else { result = new InputSource(is); } } else { result = new InputSource(is); } } else { result = super.resolveEntity(systemId, publicId); } return result; }

Target:
public InputSource resolveEntity(String systemId, String publicId) throws IOException, SAXException { if (Parser.isUnRecognizedPublicId(publicId)) { boolean isHttps = publicId != null && publicId.trim().toLowerCase().startsWith("https"); if (isHttps || RuntimeBehavior.useHttpUrlForDtd()) { return super.resolveEntity(systemId, publicId); } else { String msg = "TestNG by default disables loading DTD from unsecure Urls. " + "If you need to explicitly load the DTD from a http url, please do so " + "by using the JVM argument [-D" + RuntimeBehavior.TESTNG_USE_UNSECURE_URL + "=true]"; throw new TestNGException(msg); } } m_validate = true; InputStream is = loadDtdUsingClassLoader(); if (is != null) { return new InputSource(is); } System.out.println( "WARNING: couldn't find in classpath " + publicId + "\n" + "Fetching it from " + Parser.HTTPS_TESTNG_DTD_URL); return super.resolveEntity(systemId, Parser.HTTPS_TESTNG_DTD_URL); }
Source:
private static void validateConfig(Map<String, Task> config) { if (config.isEmpty()) { return; } if (config.size() > 1 || !(config.containsKey("rollback") || config.containsKey("cleanup"))) { throw new GradleException("Step configuration can only have one setting either 'rollback' or 'cleanup'. " + "Please refer to the documentation."); } String key = config.keySet().iterator().next(); if (!(config.get(key) instanceof Task)) { throw new GradleException("Step configuration '" + key + "' must refer to a Gradle task but it is: '" + config.get(key) + "'. Please refer to the documentation."); } }

Target:
private static void validateConfig(Map<String, Task> config) { if (config.isEmpty()) { return; } if (config.size() > 1 || !(config.containsKey("rollback") || config.containsKey("cleanup"))) { throw new GradleException("Step configuration can only have one setting either 'rollback' or 'cleanup'. " + "Please refer to the documentation."); } Map.Entry<String, Task> entry = config.entrySet().iterator().next(); if (!(entry.getValue() instanceof Task)) { throw new GradleException("Step configuration '" + entry.getKey() + "' must refer to a Gradle task but it is: '" + entry.getValue() + "'. Please refer to the documentation."); } }
Source:
@Test public void connectWithKey() { configureDefaultSSHSlaveLauncher().keyCredentials("test", sshd.getPrivateKeyString()); elasticSleep(1000); slave.save(); verify(); }

Target:
@Test public void connectWithKey() { configureDefaultSSHSlaveLauncher() .keyCredentials("test", sshd.getPrivateKeyString()); slave.save(); verify(); }
Source:
AzureBlobDataAccessor(BlobServiceClient blobServiceClient, BlobBatchClient blobBatchClient, String clusterName, AzureMetrics azureMetrics) { this.blobLayoutStrategy = new AzureBlobLayoutStrategy(clusterName); try { this.storageClient = Utils.getObj(AzureCloudConfig.DEFAULT_AZURE_STORAGE_CLIENT_CLASS, blobServiceClient, blobBatchClient, blobLayoutStrategy); } catch (ReflectiveOperationException roEx) { throw new IllegalArgumentException("Unable to instantiate storage client: " + roEx.getMessage(), roEx); } this.azureMetrics = azureMetrics; this.purgeBatchSize = AzureCloudConfig.DEFAULT_PURGE_BATCH_SIZE; requestTimeout = null; uploadTimeout = null; batchTimeout = null; }

Target:
AzureBlobDataAccessor(BlobServiceClient blobServiceClient, BlobBatchClient blobBatchClient, String clusterName, AzureMetrics azureMetrics) { this.blobLayoutStrategy = new AzureBlobLayoutStrategy(clusterName); try { this.storageClient = Utils.getObj(AzureCloudConfig.DEFAULT_AZURE_STORAGE_CLIENT_CLASS, blobServiceClient, blobBatchClient, azureMetrics, blobLayoutStrategy); } catch (ReflectiveOperationException roEx) { throw new IllegalArgumentException("Unable to instantiate storage client: " + roEx.getMessage(), roEx); } this.azureMetrics = azureMetrics; this.purgeBatchSize = AzureCloudConfig.DEFAULT_PURGE_BATCH_SIZE; requestTimeout = null; uploadTimeout = null; batchTimeout = null; }
Source:
public URI adminUrl() { ServerConnector adminConnector = null; for (Connector connector : jettyServer.getConnectors()) { if (ADMIN_SERVER_CONNECTOR_NAME.equals(connector.getName())) adminConnector = (ServerConnector) connector; } if (adminConnector == null) { List<String> adminListeners = config.getList(WorkerConfig.ADMIN_LISTENERS_CONFIG); if (adminListeners == null) { return advertisedUrl(); } else if (adminListeners.isEmpty()) { return null; } else { log.error("No admin connector found for listeners {}", adminListeners); return null; } } UriBuilder builder = UriBuilder.fromUri(jettyServer.getURI()); builder.port(adminConnector.getLocalPort()); log.info("Admin URI: {}", builder.build()); return builder.build(); }

Target:
public URI adminUrl() { ServerConnector adminConnector = null; for (Connector connector : jettyServer.getConnectors()) { if (ADMIN_SERVER_CONNECTOR_NAME.equals(connector.getName())) adminConnector = (ServerConnector) connector; } if (adminConnector == null) { List<String> adminListeners = config.getList(WorkerConfig.ADMIN_LISTENERS_CONFIG); if (adminListeners == null) { return advertisedUrl(); } else if (adminListeners.isEmpty()) { return null; } else { log.error("No admin connector found for listeners {}", adminListeners); return null; } } UriBuilder builder = UriBuilder.fromUri(jettyServer.getURI()); builder.port(adminConnector.getLocalPort()); return builder.build(); }
Source:
public Void visitSpecialForm(SpecialFormExpression specialForm, AtomicBoolean result) { switch (specialForm.getForm()) { case IN: case IF: case SWITCH: case WHEN: case NULL_IF: case DEREFERENCE: result.set(true); } return super.visitSpecialForm(specialForm, result); }

Target:
public Void visitSpecialForm(SpecialFormExpression specialForm, AtomicBoolean result) { switch (specialForm.getForm()) { case IN: case IF: case SWITCH: case WHEN: case NULL_IF: case DEREFERENCE: result.set(true); } specialForm.getArguments().forEach(argument -> argument.accept(this, result)); return null; }
Source:
public void parseAssociatedNames(Job<?, ?> job, Collection<GitHubRepositoryName> result) { SCMTriggerItem item = SCMTriggerItems.asSCMTriggerItem(job); if (item != null) { for (SCM scm : item.getSCMs()) { addRepositories(scm, buildEnv(job), result); } } }

Target:
public void parseAssociatedNames(Job<?, ?> job, Collection<GitHubRepositoryName> result) { SCMTriggerItem item = SCMTriggerItems.asSCMTriggerItem(job); EnvVars envVars = buildEnv(job); if (item != null) { for (SCM scm : item.getSCMs()) { addRepositories(scm, envVars, result); } } }
Source:
public Object getPropertyValue(Object id) { if (sfName.equals(id)) { return getName(); } if (sfPath.equals(id)) { return getPath().toString(); } if (sfLocation.equals(id)) { return getLocation().toString(); } if (sfExperimentType.equals(id)) { if (getTraceType() != null) { IConfigurationElement ce = sfTraceTypeAttributes.get(getTraceType()); return (ce != null) ? (getCategory(ce) + " : " + ce.getAttribute(TmfTraceType.NAME_ATTR)) : ""; } } return null; }

Target:
public Object getPropertyValue(Object id) { if (sfName.equals(id)) { return getName(); } if (sfPath.equals(id)) { return getPath().toString(); } if (sfLocation.equals(id)) { return getLocation().toString(); } if (sfExperimentType.equals(id)) { if (getTraceType() != null) { IConfigurationElement ce = sfTraceTypeAttributes.get(getTraceType()); return (ce != null) ? (getCategory(ce) + ':' + ce.getAttribute(TmfTraceType.NAME_ATTR)) : new String(); } } return null; }
Source:
public boolean isFieldPresent(String fieldName) { for (int i = 0; i < inputs.length; i++) { DCInput field = inputs[i]; String fullName = field.getElement() + "." + field.getQualifier(); if (fullName.equals(fieldName)) { return true; } } return false; }

Target:
public boolean isFieldPresent(String fieldName) { for (int i = 0; i < inputs.length; i++) { DCInput field = inputs[i]; String fullName = field.getFieldName(); if (fullName.equals(fieldName)) { return true; } } return false; }
Source:
public void handleMessage(Message msg) { AsyncResult ar; if (mDestroyed.get()) { Rlog.e(LOG_TAG, "Received message " + msg + "[" + msg.what + "] while being destroyed. Ignoring."); return; } loge("IsimUiccRecords: handleMessage " + msg + "[" + msg.what + "] "); try { switch (msg.what) { case EVENT_APP_READY: onReady(); break; case IccRecords.EVENT_REFRESH: broadcastRefresh(); super.handleMessage(msg); break; case EVENT_ISIM_AUTHENTICATE_DONE: ar = (AsyncResult)msg.obj; log("EVENT_ISIM_AUTHENTICATE_DONE"); if (ar.exception != null) { log("Exception ISIM AKA: " + ar.exception); } else { try { auth_rsp = (String)ar.result; log("ISIM AKA: auth_rsp = " + auth_rsp); } catch (Exception e) { log("Failed to parse ISIM AKA contents: " + e); } } synchronized (mLock) { mLock.notifyAll(); } break; default: super.handleMessage(msg); } } catch (RuntimeException exc) { Rlog.w(LOG_TAG, "Exception parsing SIM record", exc); } }

Target:
public void handleMessage(Message msg) { AsyncResult ar; if (mDestroyed.get()) { Rlog.e(LOG_TAG, "Received message " + msg + "[" + msg.what + "] while being destroyed. Ignoring."); return; } loge("IsimUiccRecords: handleMessage " + msg + "[" + msg.what + "] "); try { switch (msg.what) { case EVENT_APP_READY: onReady(); break; case EVENT_REFRESH: broadcastRefresh(); super.handleMessage(msg); break; case EVENT_ISIM_AUTHENTICATE_DONE: ar = (AsyncResult)msg.obj; log("EVENT_ISIM_AUTHENTICATE_DONE"); if (ar.exception != null) { log("Exception ISIM AKA: " + ar.exception); } else { try { auth_rsp = (String)ar.result; log("ISIM AKA: auth_rsp = " + auth_rsp); } catch (Exception e) { log("Failed to parse ISIM AKA contents: " + e); } } synchronized (mLock) { mLock.notifyAll(); } break; default: super.handleMessage(msg); } } catch (RuntimeException exc) { Rlog.w(LOG_TAG, "Exception parsing SIM record", exc); } }
Source:
public static String customizedView(String clusterName, String customizedStateName) { return String.format("/%s/EXTERNALVIEW/%s", clusterName, customizedStateName); }

Target:
public static String customizedView(String clusterName, String customizedStateName) { return String.format("/%s/CUSTOMIZEDVIEW/%s", clusterName, customizedStateName); }
Source:
public void anRtuIec61850Device(final Map<String, String> settings) throws Throwable { ScenarioContext.Current().put(Keys.KEY_DEVICE_IDENTIFICATION, Defaults.DEFAULT_DEVICE_IDENTIFICATION); final Map<String, String> rtuSettings = SettingsHelper.addAsDefaults(settings, RTU_DEFAULT_SETTINGS); rtuSettings.put(Keys.KEY_NETWORKADDRESS, this.iec61850MockServerConfig.iec61850MockNetworkAddress()); rtuSettings.put(Keys.KEY_NETWORKADDRESS, this.iec61850MockServerConfig.iec61850MockNetworkAddress()); this.rtuDeviceSteps.anRtuDevice(rtuSettings); createIec61850Device(rtuSettings); }

Target:
public void anRtuIec61850Device(final Map<String, String> settings) throws Throwable { ScenarioContext.Current().put(Keys.KEY_DEVICE_IDENTIFICATION, Defaults.DEFAULT_DEVICE_IDENTIFICATION); final Map<String, String> rtuSettings = SettingsHelper.addAsDefaults(settings, RTU_DEFAULT_SETTINGS); rtuSettings.put(Keys.KEY_NETWORKADDRESS, this.iec61850MockServerConfig.iec61850MockNetworkAddress()); this.rtuDeviceSteps.anRtuDevice(rtuSettings); this.createIec61850Device(rtuSettings); }
Source:
@Override @Nullable public <T extends Serializable> T read(@NotNull String key) throws IgniteCheckedException { if (keysToSkip.contains(key)) return null; lock.readLock().lock(); try { return (T)bridge.read(key); } finally { lock.readLock().unlock(); } }

Target:
@Override @Nullable public <T extends Serializable> T read(@NotNull String key) throws IgniteCheckedException { lock.readLock().lock(); try { return (T)bridge.read(key); } finally { lock.readLock().unlock(); } }
Source:
public void testCreateNewLog() throws Exception { ServerConfiguration conf = TestBKConfiguration.newServerConfiguration(); conf.setLedgerDirNames(ledgerDirs); LedgerDirsManager ledgerDirsManager = new LedgerDirsManager(conf, conf.getLedgerDirs(), new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold())); String logFileName = Long.toHexString(1) + ".log"; File dir = ledgerDirsManager.pickRandomWritableDir(); LOG.info("Picked this directory: " + dir); File newLogFile = new File(dir, logFileName); newLogFile.createNewFile(); EntryLogger el = new EntryLogger(conf, ledgerDirsManager); el.createNewLog(0L); LOG.info("This is the current log id: " + el.getPreviousAllocatedEntryLogId()); assertTrue("Wrong log id", el.getPreviousAllocatedEntryLogId() > 1); }

Target:
public void testCreateNewLog() throws Exception { ServerConfiguration conf = TestBKConfiguration.newServerConfiguration(); conf.setLedgerDirNames(ledgerDirs); LedgerDirsManager ledgerDirsManager = new LedgerDirsManager(conf, conf.getLedgerDirs(), new DiskChecker(conf.getDiskUsageThreshold(), conf.getDiskUsageWarnThreshold())); String logFileName = Long.toHexString(1) + ".log"; File dir = ledgerDirsManager.pickRandomWritableDir(); LOG.info("Picked this directory: {}", dir); File newLogFile = new File(dir, logFileName); newLogFile.createNewFile(); EntryLogger el = new EntryLogger(conf, ledgerDirsManager); EntryLogManagerForSingleEntryLog entryLogManager = (EntryLogManagerForSingleEntryLog) el.getEntryLogManager(); entryLogManager.createNewLog(0L); LOG.info("This is the current log id: {}", entryLogManager.getCurrentLogId()); assertTrue("Wrong log id", entryLogManager.getCurrentLogId() > 1); }
Source:
public GarageDoorData getGarageData() throws InvalidLoginException, IOException { logger.debug("Retreiveing door data"); String url = String.format( "%s/api/v4/userdevicedetails/get?appId=%s&SecurityToken=%s", WEBSITE, appId, getSecurityToken()); JsonNode data = request("GET", url, null, null, true); return new GarageDoorData(data); }

Target:
public GarageDoorData getGarageData() throws InvalidLoginException, IOException { logger.debug("Retreiveing door data"); String url = String.format( "%s/api/v4/userdevicedetails/get?appId=%s&SecurityToken=%s", WEBSITE, enc(appId), enc(getSecurityToken())); JsonNode data = request("GET", url, null, null, true); return new GarageDoorData(data); }
Source:
public synchronized ByteBuf getSavedEncodeBuffer() { if (temporaryBuffer == null) { temporaryBuffer = PooledByteBufAllocator.DEFAULT.buffer(getEstimateSavedEncode()); saveEncoding(temporaryBuffer); } return temporaryBuffer.retain(); }

Target:
public synchronized ByteBuf getSavedEncodeBuffer() { if (temporaryBuffer == null) { temporaryBuffer = PooledByteBufAllocator.DEFAULT.buffer(getEstimateSavedEncode()); saveEncoding(temporaryBuffer); } return temporaryBuffer.retain(1); }
Source:
public int read(ByteBuffer dst) throws IOException { if (this.writeMode.get()) { throw new IOException("Buffer is still in write mode!"); } if (!this.hasRemaining()) { return -1; } if (!dst.hasRemaining()) { return 0; } final int oldIndex = index; for(; index < limit; index++) { if(!dst.hasRemaining()) { break; } dst.put(this.internalMemorySegment.get(index)); } return index-oldIndex; }

Target:
public int read(ByteBuffer dst) throws IOException { if (!this.hasRemaining()) { return -1; } int numBytes = dst.remaining(); final int remaining = this.remaining(); if (numBytes == 0) { return 0; } if(numBytes > remaining) { numBytes = remaining; } internalMemorySegment.get(position(), dst, numBytes); index += numBytes; return numBytes; }
Source:
private RuntimeException prettifyFailure(MockFeatures<?> mockFeatures, Exception generationFailed) { if (Modifier.isPrivate(mockFeatures.mockedType.getModifiers())) { throw new MockitoException(join( "Mockito cannot mock this class: " + mockFeatures.mockedType + ".", "Most likely it is a private class that is not visible by Mockito", "" ), generationFailed); } throw new MockitoException(join( "Mockito cannot mock this class: " + mockFeatures.mockedType, "", "Mockito can only mock visible & non-final classes.", "If you're not sure why you're getting this error, please report to the mailing list.", "", Platform.isJava8BelowUpdate45() ? "Java 8 early builds have bugs that were addressed in Java 1.8.0_45, please update your JDK!\n" : "", Platform.describe(), "", "Underlying exception : " + generationFailed), generationFailed ); }

Target:
private RuntimeException prettifyFailure(MockFeatures<?> mockFeatures, Exception generationFailed) { if (Modifier.isPrivate(mockFeatures.mockedType.getModifiers())) { throw new MockitoException(join( "Mockito cannot mock this class: " + mockFeatures.mockedType + ".", "Most likely it is a private class that is not visible by Mockito", "" ), generationFailed); } throw new MockitoException(join( "Mockito cannot mock this class: " + mockFeatures.mockedType, "", "Mockito can only non-private & non-final classes.", "If you're not sure why you're getting this error, please report to the mailing list.", "", Platform.isJava8BelowUpdate45() ? "Java 8 early builds have bugs that were addressed in Java 1.8.0_45, please update your JDK!\n" : "", Platform.describe(), "", "Underlying exception : " + generationFailed ), generationFailed); }
Source:
public String timeStamp() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); XMLGregorianCalendar now = calendarUtil.buildXMLGregorianCalendarDateTime(new GregorianCalendar()); return dateFormat.format(now.toGregorianCalendar().getTime()); }

Target:
public String timeStamp() { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); return dateFormat.format(new GregorianCalendar().getTime()); }
Source:
private void updateVms() { for (VmStatic vm : vmsLockedForUpdate) { vm.setVmInit(vmInitDao.get(vm.getId())); VmManagementParametersBase updateParams = new VmManagementParametersBase(vm); updateParams.setLockProperties(LockProperties.create(LockProperties.Scope.None)); updateParams.setClusterLevelChangeFromVersion(oldCluster.getCompatibilityVersion()); updateParams.setCompensationEnabled(true); ActionReturnValue result = runInternalAction( ActionType.UpdateVm, updateParams, cloneContextWithNoCleanupCompensation()); if (!result.getSucceeded()) { List<String> params = new ArrayList<>(); params.add("$action Update"); params.add("$type VM"); params.add(parseErrorMessage(result.getValidationMessages())); List<String> messages = backend.getErrorsTranslator().translateErrorText(params); failedUpgradeEntities.put(vm.getName(), getFailedMessage(messages)); } } }

Target:
private void updateVms() { for (VmStatic vm : vmsLockedForUpdate) { VmManagementParametersBase updateParams = new VmManagementParametersBase(vm); updateParams.setLockProperties(LockProperties.create(LockProperties.Scope.None)); updateParams.setClusterLevelChangeFromVersion(oldCluster.getCompatibilityVersion()); updateParams.setCompensationEnabled(true); ActionReturnValue result = runInternalAction( ActionType.UpdateVm, updateParams, cloneContextWithNoCleanupCompensation()); if (!result.getSucceeded()) { List<String> params = new ArrayList<>(); params.add("$action Update"); params.add("$type VM"); params.add(parseErrorMessage(result.getValidationMessages())); List<String> messages = backend.getErrorsTranslator().translateErrorText(params); failedUpgradeEntities.put(vm.getName(), getFailedMessage(messages)); } } }
Source:
private FileWriter getNextWriter() throws IOException { currentFileWriter.close(); File scriptOutputFile_renameFrom = new File(path + File.separator + baseName); File scriptOutputFile_renameTo = new File(path + File.separator + baseName.substring(0, baseName.indexOf("-")) + ".btrace." + (counter++)); if (scriptOutputFile_renameTo.exists()) { scriptOutputFile_renameTo.delete(); } scriptOutputFile_renameFrom.renameTo(scriptOutputFile_renameTo); scriptOutputFile_renameFrom = new File(path + File.separator + baseName); if (counter > settings.getFileRollMaxRolls()) { counter = 1; } return new FileWriter(scriptOutputFile_renameFrom); }

Target:
private FileWriter getNextWriter() throws IOException { currentFileWriter.close(); File scriptOutputFile_renameFrom = new File(path + File.separator + baseName); File scriptOutputFile_renameTo = new File(path + File.separator + baseName + "." + (counter++)); if (scriptOutputFile_renameTo.exists()) { scriptOutputFile_renameTo.delete(); } scriptOutputFile_renameFrom.renameTo(scriptOutputFile_renameTo); scriptOutputFile_renameFrom = new File(path + File.separator + baseName); if (counter > settings.getFileRollMaxRolls()) { counter = 1; } return new FileWriter(scriptOutputFile_renameFrom); }
Source:
public void testShadowedTests() { TestSuite suite = new TestSuite(OverrideTestCase.class); suite.run(fResult); assertEquals(1, fResult.runCount()); assertNotNull(fResult); }

Target:
public void testShadowedTests() { TestSuite suite = new TestSuite(OverrideTestCase.class); suite.run(fResult); assertEquals(1, fResult.runCount()); }
Source:
private InetSocketAddress startServer() throws TTransportException { Preconditions.checkState( curatorFramework != null && curatorFramework.getState() == CuratorFrameworkState.STARTED); if (env.getConfiguration().containsKey(FluoConfigurationImpl.ORACLE_PORT_PROP)) { port = env.getConfiguration().getInt(FluoConfigurationImpl.ORACLE_PORT_PROP); Preconditions.checkArgument(port >= 1 && port <= 65535, FluoConfigurationImpl.ORACLE_PORT_PROP + " must be valid port (1-65535)"); } else { port = PortUtils.getRandomFreePort(); } InetSocketAddress addr = new InetSocketAddress(port); TNonblockingServerSocket socket = new TNonblockingServerSocket(addr); THsHaServer.Args serverArgs = new THsHaServer.Args(socket); TProcessor processor = new OracleService.Processor<OracleService.Iface>(this); serverArgs.processor(processor); serverArgs.maxReadBufferBytes = ORACLE_MAX_READ_BUFFER_BYTES; serverArgs.inputProtocolFactory(new TCompactProtocol.Factory()); serverArgs.outputProtocolFactory(new TCompactProtocol.Factory()); server = new THsHaServer(serverArgs); Runnable st = () -> server.serve(); serverThread = new Thread(st); serverThread.setDaemon(true); serverThread.start(); return addr; }

Target:
private InetSocketAddress startServer() throws TTransportException { Preconditions.checkState( curatorFramework != null && curatorFramework.getState() == CuratorFrameworkState.STARTED); if (env.getConfiguration().containsKey(FluoConfigurationImpl.ORACLE_PORT_PROP)) { port = env.getConfiguration().getInt(FluoConfigurationImpl.ORACLE_PORT_PROP); Preconditions.checkArgument(port >= 1 && port <= 65535, FluoConfigurationImpl.ORACLE_PORT_PROP + " must be valid port (1-65535)"); } else { port = PortUtils.getRandomFreePort(); } InetSocketAddress addr = new InetSocketAddress(port); TNonblockingServerSocket socket = new TNonblockingServerSocket(addr); THsHaServer.Args serverArgs = new THsHaServer.Args(socket); TProcessor processor = new OracleService.Processor<OracleService.Iface>(this); serverArgs.processor(processor); serverArgs.maxReadBufferBytes = ORACLE_MAX_READ_BUFFER_BYTES; serverArgs.inputProtocolFactory(new TCompactProtocol.Factory()); serverArgs.outputProtocolFactory(new TCompactProtocol.Factory()); server = new THsHaServer(serverArgs); serverThread = new Thread(server::serve); serverThread.setDaemon(true); serverThread.start(); return addr; }
Source:
private void forgetInvocations(int segment, ForgetInvocationsCommand fic) { if (fic != null) { DistributionInfo info = dm.getCacheTopology().getDistributionForSegment(segment); rpcManager.invokeRemotelyAsync(info.writeOwners(), fic, forgetRpcOptions); if (info.isWriteOwner()) { fic.init(dataContainer); fic.setOrigin(rpcManager.getAddress()); if (trace) { log.tracef("Invoking %s", fic); } fic.invoke(); if (trace) { Set<Object> keys = new HashSet<>(Arrays.asList(fic.keys())); log.tracef("Invalidation completed: " + StreamSupport.stream(dataContainer.spliterator(), false) .filter(ice -> keys.contains(ice.getKey())).collect(Collectors.toList())); } } } }

Target:
private void forgetInvocations(int segment, ForgetInvocationsCommand fic) { if (fic != null) { DistributionInfo info = dm.getCacheTopology().getDistributionForSegment(segment); rpcManager.invokeRemotelyAsync(info.writeOwners(), fic, forgetRpcOptions); if (info.isWriteOwner()) { fic.init(dataContainer); fic.setOrigin(rpcManager.getAddress()); if (trace) { log.tracef("Invoking %s", fic); } fic.invoke(); if (trace) { Set<Object> keys = new HashSet<>(Arrays.asList(fic.keys())); log.tracef("Invalidation completed: " + StreamSupport.stream(dataContainer.spliterator(), false) .filter(ice -> keys.contains(ice.getKey())).map(String::valueOf).collect(Collectors.joining())); } } } }
Source:
List<MediaWikiDumpFile> findDailyDumpsOnline() { List<String> dumpFileDates = findDumpDatesOnline("other/incr/"); List<MediaWikiDumpFile> result = new ArrayList<MediaWikiDumpFile>(); for (String dateStamp : dumpFileDates) { result.add(new WmfOnlineDailyDumpFile(dateStamp, this.projectName, this.webResourceFetcher, this.dumpfileDirectoryManager)); } return result; }

Target:
List<MediaWikiDumpFile> findDailyDumpsOnline() { List<String> dumpFileDates = findDumpDatesOnline(WmfDumpFile.DAILY_WEB_DIRECTORY); List<MediaWikiDumpFile> result = new ArrayList<MediaWikiDumpFile>(); for (String dateStamp : dumpFileDates) { result.add(new WmfOnlineDailyDumpFile(dateStamp, this.projectName, this.webResourceFetcher, this.dumpfileDirectoryManager)); } return result; }
Source:
private static TimeGraphEntryModel getValueEntry(List<@NonNull TimeGraphEntryModel> treeModel, String name) { Long parentID = -2L; for (TimeGraphEntryModel entryModel : treeModel) { if (entryModel.getName().equals(name)) { parentID = entryModel.getId(); } if (entryModel.getParentId() == parentID && parentID != null) { return entryModel; } } return null; }

Target:
private static TimeGraphEntryModel getValueEntry(List<@NonNull TimeGraphEntryModel> treeModel, String name) { Long parentID = null; for (TimeGraphEntryModel entryModel : treeModel) { if (entryModel.getName().equals(name)) { parentID = entryModel.getId(); } if (entryModel.getParentId() == parentID && parentID != null) { return entryModel; } } return null; }
Source:
public void testprocessTokenResponseNegative() throws IOException { final AuthenticationRequest request = createAuthenticationRequest(TEST_AUTHORITY, "resource", "client", "redirect", "loginhint", null, null, null); final Oauth2 oauth2 = createOAuthInstance(request, new WebRequestHandler()); final String jsonResponse = "{invalid"; final HttpURLConnection mockedConnection = mock(HttpURLConnection.class); HttpUrlConnectionFactory.mockedConnection = mockedConnection; Util.prepareMockedUrlConnection(mockedConnection); when(mockedConnection.getOutputStream()).thenReturn(mock(OutputStream.class)); when(mockedConnection.getInputStream()).thenReturn( Util.createInputStream(jsonResponse)); when(mockedConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); try { oauth2.refreshToken("fakeRefresToken"); fail("must throw exception"); } catch (final AuthenticationException e) { assertNotNull(e); assertEquals(e.getCode(), ADALError.SERVER_INVALID_JSON_RESPONSE); assertNotNull(e.getCause()); assertTrue(e.getCause() instanceof JSONException); } }

Target:
public void testprocessTokenResponseNegative() throws IOException { final AuthenticationRequest request = createAuthenticationRequest(TEST_AUTHORITY, "resource", "client", "redirect", "loginhint", null, null, null); final Oauth2 oauth2 = createOAuthInstance(request, new WebRequestHandler()); final String jsonResponse = "{invalid"; final HttpURLConnection mockedConnection = mock(HttpURLConnection.class); HttpUrlConnectionFactory.mockedConnection = mockedConnection; Util.prepareMockedUrlConnection(mockedConnection); when(mockedConnection.getOutputStream()).thenReturn(mock(OutputStream.class)); when(mockedConnection.getInputStream()).thenReturn( Util.createInputStream(jsonResponse)); when(mockedConnection.getResponseCode()).thenReturn(HttpURLConnection.HTTP_OK); try { oauth2.refreshToken("fakeRefreshToken"); fail("must throw exception"); } catch (final AuthenticationException e) { assertNotNull(e); assertEquals(e.getCode(), ADALError.SERVER_INVALID_JSON_RESPONSE); assertNotNull(e.getCause()); assertTrue(e.getCause() instanceof JSONException); } }
Source:
public ResponseEntity<String> removeOrphanDocuments(@RequestParam(defaultValue = "12") Long hoursToKeep) throws SdkClientException, AmazonServiceException { Date startDateTime = null; if (hoursToKeep > 0) { Instant dateTime = Instant.now().minus(hoursToKeep, ChronoUnit.HOURS); startDateTime = Date.from(dateTime); } int numberOfOrphanDocuments = 0; List<String> fourCharacterIds = getDistinctFourCharacterIdsInBucket(); for (String fourCharacterId : fourCharacterIds) { List<String> documentNames = this.documents.findDocumentNamesByFourCharacterId(fourCharacterId); List<String> objectKeys = this.getObjectKeys(fourCharacterId, startDateTime); for (String objectKey : objectKeys) { if (!documentNames.contains(objectKey)) { DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(this.bucketName, objectKey); s3Client.deleteObject(deleteObjectRequest); numberOfOrphanDocuments++; } } } if (numberOfOrphanDocuments == 0) { return new ResponseEntity<String>(HttpStatus.OK); } else { log.info(numberOfOrphanDocuments + " orphan documents have been removed from " + this.bucketName); return new ResponseEntity<String>(HttpStatus.NO_CONTENT); } }

Target:
public ResponseEntity<String> removeOrphanDocuments(@RequestParam(defaultValue = "12") Long hoursToKeep) throws SdkClientException, AmazonServiceException { Date startDateTime = null; if (hoursToKeep > 0) { Instant dateTime = Instant.now().minus(hoursToKeep, ChronoUnit.HOURS); startDateTime = Date.from(dateTime); } List<String> objectKeys = this.getAllObjectKeys(startDateTime); List<Document> documents = this.documentRepository.findAll(); List<String> documentNames = documents.stream().map(d -> d.getName()).collect(Collectors.toList()); int numberOfOrphanDocuments = 0; for (String objectKey : objectKeys) { if (!documentNames.contains(objectKey)) { DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(this.bucketName, objectKey); s3Client.deleteObject(deleteObjectRequest); numberOfOrphanDocuments++; } } log.info(numberOfOrphanDocuments + " orphan documents have been removed"); return ResponseEntity.ok().body("Number of orphan documents removed: " + numberOfOrphanDocuments); }
Source:
public Hc4ProviderImpl( final ApplicationConfiguration applicationConfiguration, final UserAgentBuilder userAgentBuilder, final EventBus eventBus, final PoolingClientConnectionManagerMBeanInstaller jmxInstaller ) { this.applicationConfiguration = Preconditions.checkNotNull( applicationConfiguration ); this.userAgentBuilder = Preconditions.checkNotNull( userAgentBuilder ); this.jmxInstaller = Preconditions.checkNotNull( jmxInstaller ); this.sharedConnectionManager = createClientConnectionManager(); this.evictingThread = new EvictingThread( sharedConnectionManager, getConnectionPoolIdleTime() ); this.evictingThread.start(); this.eventBus = Preconditions.checkNotNull( eventBus ); this.eventBus.register( this ); this.jmxInstaller.register( sharedConnectionManager ); getLogger().info( "{} started up (connectionPoolMaxSize {}, connectionPoolSize {}, connectionPoolIdleTime ms, connectionPoolTimeout ms, keepAliveMaxDuration ms)", getClass().getSimpleName(), getConnectionPoolMaxSize(), getConnectionPoolSize(), getConnectionPoolIdleTime(), getConnectionPoolTimeout(), getKeepAliveMaxDuration() ); }

Target:
public Hc4ProviderImpl( final ApplicationConfiguration applicationConfiguration, final UserAgentBuilder userAgentBuilder, final EventBus eventBus, final PoolingClientConnectionManagerMBeanInstaller jmxInstaller ) { this.applicationConfiguration = Preconditions.checkNotNull( applicationConfiguration ); this.userAgentBuilder = Preconditions.checkNotNull( userAgentBuilder ); this.jmxInstaller = Preconditions.checkNotNull( jmxInstaller ); this.sharedConnectionManager = createClientConnectionManager(); this.evictingThread = new EvictingThread( sharedConnectionManager, getConnectionPoolIdleTime() ); this.evictingThread.start(); this.eventBus = Preconditions.checkNotNull( eventBus ); this.eventBus.register( this ); this.jmxInstaller.register( sharedConnectionManager ); getLogger().info( "{} started (connectionPoolMaxSize {}, connectionPoolSize {}, connectionPoolIdleTime ms, connectionPoolTimeout ms, keepAliveMaxDuration ms)", getClass().getSimpleName(), getConnectionPoolMaxSize(), getConnectionPoolSize(), getConnectionPoolIdleTime(), getConnectionPoolTimeout(), getKeepAliveMaxDuration() ); }
Source:
public void sessionChanged(Session session) { startPassiveScanThread(); getScanStatus().setScanCount(0); }

Target:
public void sessionChanged(Session session) { startPassiveScanThread(); if (View.isInitialised()) { getScanStatus().setScanCount(0); } }
Source:
public Stream<Output> bloomFulltextNodes( @Name( "terms" ) List<String> terms ) throws Exception { Stream<Output> stream; try ( ReadOnlyFulltext indexReader = provider.getReader( BLOOM_NODES, FulltextProvider.FulltextIndexType.NODES ) ) { stream = queryAsStream( terms, indexReader ); } return stream; }

Target:
public Stream<Output> bloomFulltextNodes( @Name( "terms" ) List<String> terms ) throws Exception { try ( ReadOnlyFulltext indexReader = provider.getReader( BLOOM_NODES, FulltextProvider.FulltextIndexType.NODES ) ) { return queryAsStream( terms, indexReader ); } }
Source:
public int hashCode() { return Objects.hashCode( referenceExpression ); }

Target:
public int hashCode() { return referenceExpression.hashCode(); }
Source:
public CloudObjectLocation createCloudObjectLocation(CloudBlobHolder cloudBlob) { try { return new CloudObjectLocation(cloudBlob.getContainerName(), cloudBlob.getName()); } catch (Exception e) { throw new RuntimeException(e); } }

Target:
public CloudObjectLocation createCloudObjectLocation(CloudBlobHolder cloudBlob) { try { return new CloudObjectLocation(cloudBlob.getContainerName(), cloudBlob.getName()); } catch (Exception e) { throw new RE(e); } }
Source:
public void addMediaFromChoice(AudioVideoImageTextLabel audioVideoImageTextLabel, int index, TextView textView, List<SelectChoice> items) { SelectChoice item = items.get(index); audioVideoImageTextLabel.setTag(getClipID(props.getPrompt(), item)); audioVideoImageTextLabel.setTextView(textView); String imageURI = getImageURI(index, items); String videoURI = props.getPrompt().getSpecialFormSelectChoiceText(item, "video"); String bigImageURI = props.getPrompt().getSpecialFormSelectChoiceText(item, "big-image"); String audioURI = getPlayableAudioURI(props.getPrompt(), item, props.getReferenceManager()); try { if (imageURI != null) { audioVideoImageTextLabel.setImage(new File(props.getReferenceManager().deriveReference(imageURI).getLocalURI())); } if (bigImageURI != null) { audioVideoImageTextLabel.setBigImage(new File(props.getReferenceManager().deriveReference(bigImageURI).getLocalURI())); } if (videoURI != null) { audioVideoImageTextLabel.setVideo(new File(props.getReferenceManager().deriveReference(videoURI).getLocalURI())); } if (audioURI != null) { audioVideoImageTextLabel.setAudio(audioURI, props.getAudioHelper()); } } catch (InvalidReferenceException e) { Timber.e(e, "Invalid image reference due to %s ", e.getMessage()); } textView.setGravity(Gravity.CENTER_VERTICAL); }

Target:
public void addMediaFromChoice(AudioVideoImageTextLabel audioVideoImageTextLabel, int index, TextView textView, List<SelectChoice> items) { SelectChoice item = items.get(index); audioVideoImageTextLabel.setTag(getClipID(prompt, item)); audioVideoImageTextLabel.setTextView(textView); String imageURI = getImageURI(index, items); String videoURI = prompt.getSpecialFormSelectChoiceText(item, "video"); String bigImageURI = prompt.getSpecialFormSelectChoiceText(item, "big-image"); String audioURI = getPlayableAudioURI(prompt, item, referenceManager); try { if (imageURI != null) { audioVideoImageTextLabel.setImage(new File(referenceManager.deriveReference(imageURI).getLocalURI())); } if (bigImageURI != null) { audioVideoImageTextLabel.setBigImage(new File(referenceManager.deriveReference(bigImageURI).getLocalURI())); } if (videoURI != null) { audioVideoImageTextLabel.setVideo(new File(referenceManager.deriveReference(videoURI).getLocalURI())); } if (audioURI != null) { audioVideoImageTextLabel.setAudio(audioURI, audioHelper); } } catch (InvalidReferenceException e) { Timber.d(e, "Invalid media reference due to %s ", e.getMessage()); } textView.setGravity(Gravity.CENTER_VERTICAL); }
Source:
public BVDesignOutput runBVDesign(final WorkbenchService workbenchService, final FieldbookProperties fieldbookProperties, final MainDesign design) throws IOException { final String bvDesignPath = fieldbookProperties.getBvDesignPath(); int returnCode = -1; if (bvDesignPath != null && design != null && design.getDesign() != null) { final String xml = this.getXMLStringForDesign(design); final String filepath = BVDesignRunner.writeToFile(xml, fieldbookProperties); final ProcessBuilder pb = new ProcessBuilder(bvDesignPath, "-i" + filepath); final Process p = pb.start(); final ProcessTimeoutThread processTimeoutThread = new ProcessTimeoutThread(p, BVDesignRunner.DESIGN_RUNNER_TIMEOUT_MILLIS); processTimeoutThread.start(); try { final InputStreamReader isr = new InputStreamReader(p.getInputStream()); final BufferedReader br = new BufferedReader(isr); String lineRead; while ((lineRead = br.readLine()) != null) { BVDesignRunner.LOG.debug(lineRead); } returnCode = p.waitFor(); } catch (final InterruptedException e) { BVDesignRunner.LOG.error(e.getMessage(), e); } finally { if (processTimeoutThread != null) { processTimeoutThread.interrupt(); } if (p != null) { p.getInputStream().close(); p.getOutputStream().close(); p.getErrorStream().close(); } } } final BVDesignOutput output = new BVDesignOutput(returnCode); if (returnCode == 0) { final File outputFile = new File(design.getDesign().getParameterValue(ExperimentDesignGenerator.OUTPUTFILE_PARAM)); final FileReader fileReader = new FileReader(outputFile); final CSVReader reader = new CSVReader(fileReader); final List<String[]> myEntries = reader.readAll(); output.setResults(myEntries); fileReader.close(); reader.close(); outputFile.delete(); } return output; }

Target:
public BVDesignOutput runBVDesign(final WorkbenchService workbenchService, final FieldbookProperties fieldbookProperties, final MainDesign design) throws IOException { final String bvDesignPath = fieldbookProperties.getBvDesignPath(); int returnCode = -1; if (bvDesignPath != null && design != null && design.getDesign() != null) { final String xml = this.getXMLStringForDesign(design); final String filepath = this.inputWriter.write(xml, fieldbookProperties); returnCode = this.processRunner.run(bvDesignPath, "-i" + filepath); } final BVDesignOutput output = new BVDesignOutput(returnCode); if (returnCode == 0) { output.setResults(outputReader.read(design.getDesign().getParameterValue(ExperimentDesignGenerator.OUTPUTFILE_PARAM))); } return output; }
Source:
private List<CramCompressionRecord> initRTRecords() { final List<CramCompressionRecord> initialRecords = new ArrayList<>(); CramCompressionRecord record = createRecord(); record.readBases = record.qualityScores = null; initialRecords.add(record); return initialRecords; }

Target:
private List<CramCompressionRecord> initRTRecords() { List<CramCompressionRecord> records = createRecords(); for (CramCompressionRecord record : records) { record.readBases = record.qualityScores = null; } return records; }
Source:
private void addOrUpdateDayTruncatedActivity(UserAnonymizedEntityHolder userAnonymizedHolder, ActivityPayload payload, GoalDto matchingGoal) { Optional<ActivityDto> lastRegisteredActivity = getLastRegisteredActivity(payload, matchingGoal); if (precedesLastRegisteredActivity(payload, lastRegisteredActivity)) { Optional<Activity> overlappingActivity = findOverlappingActivity(payload, matchingGoal); if (overlappingActivity.isPresent()) { updateTimeExistingActivity(userAnonymizedHolder, payload, overlappingActivity.get()); return; } } if (canCombineWithLastRegisteredActivity(payload, lastRegisteredActivity)) { if (payload.startTime.isBefore(lastRegisteredActivity.get().getStartTime()) || isBeyondSkipWindowAfterLastRegisteredActivity(payload, lastRegisteredActivity.get())) { updateTimeLastActivity(userAnonymizedHolder, payload, matchingGoal, lastRegisteredActivity.get()); } return; } addActivity(userAnonymizedHolder, payload, matchingGoal, lastRegisteredActivity); }

Target:
private void addOrUpdateDayTruncatedActivity(UserAnonymizedEntityHolder userAnonymizedHolder, ActivityPayload payload, GoalDto matchingGoal) { Optional<ActivityDto> lastRegisteredActivity = getLastRegisteredActivity(payload, matchingGoal); if (precedesLastRegisteredActivity(payload, lastRegisteredActivity)) { Optional<Activity> overlappingActivity = findOverlappingActivitySameApp(payload, matchingGoal); if (overlappingActivity.isPresent()) { updateTimeExistingActivity(userAnonymizedHolder, payload, overlappingActivity.get()); return; } } if (canCombineWithLastRegisteredActivity(payload, lastRegisteredActivity)) { if (payload.startTime.isBefore(lastRegisteredActivity.get().getStartTime()) || isBeyondSkipWindowAfterLastRegisteredActivity(payload, lastRegisteredActivity.get())) { updateTimeLastActivity(userAnonymizedHolder, payload, matchingGoal, lastRegisteredActivity.get()); } return; } addActivity(userAnonymizedHolder, payload, matchingGoal, lastRegisteredActivity); }
Source:
@Test public void retainsAccept() { server.enqueue(new MockResponse().setBody("" + "data: hey\n" + "\n").setHeader("content-type", "text/event-stream")); EventSource source = newEventSource("text/plain"); assertThat(source.request().url().encodedPath()).isEqualTo("/"); assertThat(source.request().header("Accept")).isEqualTo("text/plain"); listener.assertOpen(); listener.assertEvent(null, null, "hey"); listener.assertClose(); }

Target:
@Test public void retainsAccept() throws InterruptedException { server.enqueue(new MockResponse().setBody("" + "data: hey\n" + "\n").setHeader("content-type", "text/event-stream")); EventSource source = newEventSource("text/plain"); listener.assertOpen(); listener.assertEvent(null, null, "hey"); listener.assertClose(); assertThat(server.takeRequest().getHeader("Accept")).isEqualTo("text/plain"); }
Source:
public void postProcessRefresh(boolean succeeded) { try { try { moveVDSToMaintenanceIfNeeded(); saveDataToDb(); if (firstStatus != vds.getStatus() && vds.getStatus() == VDSStatus.Up) { vdsManager.cancelRecoveryJob(); log.debug("Host '{}' ({}) firing up event.", vds.getName(), vds.getId()); vdsManager.setIsSetNonOperationalExecuted(!getVdsEventListener().vdsUpEvent(vds)); } } finally { saveDataToDb(); } } catch (Throwable t) { logFailureMessage("ResourceManager::refreshVdsRunTimeInfo:", t); log.debug("Exception", t); } finally { vdsManager.afterRefreshTreatment(succeeded); } }

Target:
public void postProcessRefresh(boolean succeeded) { try { try { moveVDSToMaintenanceIfNeeded(); if (firstStatus != vds.getStatus() && vds.getStatus() == VDSStatus.Up) { vdsManager.cancelRecoveryJob(); log.debug("Host '{}' ({}) firing up event.", vds.getName(), vds.getId()); vdsManager.setIsSetNonOperationalExecuted(!getVdsEventListener().vdsUpEvent(vds)); } } finally { saveDataToDb(); } } catch (Throwable t) { logFailureMessage("ResourceManager::refreshVdsRunTimeInfo:", t); log.debug("Exception", t); } finally { vdsManager.afterRefreshTreatment(succeeded); } }
Source:
private DiffEntry bestPathMatch(DiffEntry src, List<DiffEntry> list) { DiffEntry best = null; int score = -1; for (DiffEntry d : list) { if (sameType(mode(d), mode(src))) { int tmp = SimilarityRenameDetector .nameScore(path(d), path(src)); if (tmp > score) { best = d; score = tmp; } } } return best; }

Target:
private static DiffEntry bestPathMatch(DiffEntry src, List<DiffEntry> list) { DiffEntry best = null; int score = -1; for (DiffEntry d : list) { if (sameType(mode(d), mode(src))) { int tmp = SimilarityRenameDetector .nameScore(path(d), path(src)); if (tmp > score) { best = d; score = tmp; } } } return best; }
Source:
public void afterTriggerCampaignForLeadsInBatch() { if (batchSize.getValue() > 300) { batchSize.setValue(300); } afterCampaignAction(); }

Target:
public void afterTriggerCampaignForLeadsInBatch() { if (batchSize.getValue() > REST_API_LIMIT) { batchSize.setValue(REST_API_LIMIT); } afterCampaignAction(); }
Source:
protected CreateIdentityZoneResponse getResponse() { return CreateIdentityZoneResponse.builder() .createdAt(new Date(1426258488910L)) .description("Like the Twilight Zone but tastier[testzone1].") .identityZoneId("testzone1") .name("The Twiglet Zone[testzone1]") .subDomain("testzone1") .version(0) .build(); }

Target:
protected CreateIdentityZoneResponse getResponse() { return CreateIdentityZoneResponse.builder() .createdAt(1426258488910L) .description("Like the Twilight Zone but tastier[testzone1].") .identityZoneId("testzone1") .name("The Twiglet Zone[testzone1]") .subDomain("testzone1") .version(0) .build(); }
Source:
public SwaggerParseResult readContents(String swaggerAsString, List<AuthorizationValue> auth, ParseOptions options) { SwaggerParseResult result = new SwaggerParseResult(); if(swaggerAsString != null && !"".equals(swaggerAsString.trim())) { ObjectMapper mapper; if(swaggerAsString.trim().startsWith("{")) { mapper = JSON_MAPPER; } else { mapper = YAML_MAPPER; } if(auth == null) { auth = new ArrayList<>(); } if(options != null) { if (options.isResolve()) { try { OpenAPIDeserializer deserializer = new OpenAPIDeserializer(); JsonNode rootNode = mapper.readTree(swaggerAsString.getBytes()); SwaggerParseResult deserializeOpenAPI = deserializer.deserialize(rootNode); OpenAPIResolver resolver = new OpenAPIResolver(deserializeOpenAPI.getOpenAPI(), auth, null); result.setOpenAPI(resolver.resolve()); } catch (Exception e) { result.setMessages(Arrays.asList(e.getMessage())); } } } } else { result.setMessages(Arrays.asList("No swagger supplied")); } return result; }

Target:
public SwaggerParseResult readContents(String swaggerAsString, List<AuthorizationValue> auth, ParseOptions options) { SwaggerParseResult result = new SwaggerParseResult(); if(swaggerAsString != null && !"".equals(swaggerAsString.trim())) { ObjectMapper mapper; if(swaggerAsString.trim().startsWith("{")) { mapper = JSON_MAPPER; } else { mapper = YAML_MAPPER; } if(auth == null) { auth = new ArrayList<>(); } if(options != null) { if (options.isResolve()) { try { OpenAPIDeserializer deserializer = new OpenAPIDeserializer(); JsonNode rootNode = mapper.readTree(swaggerAsString.getBytes()); SwaggerParseResult deserializeOpenAPI = deserializer.deserialize(rootNode); OpenAPIResolver resolver = new OpenAPIResolver(deserializeOpenAPI.getOpenAPI(), auth, null); result.setOpenAPI(resolver.resolve()); } catch (Exception e) { result.setMessages(Arrays.asList(e.getMessage())); } }else{ try { JsonNode rootNode = mapper.readTree(swaggerAsString.getBytes()); result = new OpenAPIDeserializer().deserialize(rootNode); } catch (Exception e) { result.setMessages(Arrays.asList(e.getMessage())); } } }else{ try { JsonNode rootNode = mapper.readTree(swaggerAsString.getBytes()); result = new OpenAPIDeserializer().deserialize(rootNode); } catch (Exception e) { result.setMessages(Arrays.asList(e.getMessage())); } } } else { result.setMessages(Arrays.asList("No swagger supplied")); } return result; }
Source:
boolean validatePluginAction(String pluginName, boolean allowWhileLoading) { Plugin plugin = getPlugin(pluginName); if (plugin == null) { return false; } boolean isInitializingOrInUse = plugin.isInState(PluginState.INITIALIZING) || plugin.isInState(PluginState.IN_USE); boolean isLoading = plugin.isInState(PluginState.LOADING); return allowWhileLoading ? (isLoading || isInitializingOrInUse) : isInitializingOrInUse; }

Target:
boolean validatePluginAction(String pluginName, boolean allowWhileLoading) { Plugin plugin = getPlugin(pluginName); if (plugin == null) { return false; } boolean isInitializingOrInUse = plugin.isInState(PluginState.INITIALIZING) || plugin.isInState(PluginState.IN_USE); boolean isLoading = plugin.isInState(PluginState.LOADING); return isInitializingOrInUse || (allowWhileLoading && isLoading); }