auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { if (!ResourceDomainConfiguration.isResourceRequest(req) && ResourceDomainConfiguration.isResourceDomainConfigured()) { resourceRootUrlKey = ExtensionList.lookupSingleton(ResourceDomainRootAction.class).register(this, req); } try { serveFile(req,rsp,base,icon,serveDirIndex); } catch (InterruptedException e) { throw new IOException("interrupted",e); } }

Target:
public void generateResponse(StaplerRequest req, StaplerResponse rsp, Object node) throws IOException, ServletException { if (!ResourceDomainConfiguration.isResourceRequest(req) && ResourceDomainConfiguration.isResourceDomainConfigured()) { resourceToken = ResourceDomainRootAction.get().getToken(this, req); } try { serveFile(req,rsp,base,icon,serveDirIndex); } catch (InterruptedException e) { throw new IOException("interrupted",e); } }
Source:
public R invoke(InvokeContext context, M message, BiFunction<InvokeContext, M, R> invokeFunction) throws EntityUserException { if (trackerPolicy.test(message) && context.isValidClientInformation()) { ClientSourceId clientId = context.getClientSource(); int index = segmentationStrategy.applyAsInt(message); Tracker<R> messageTracker = clientMessageTrackers.get(index).getTracker(clientId); messageTracker.reconcile(context.getOldestTransactionId()); R response = messageTracker.getTrackedValue(context.getCurrentTransactionId()); if (sharedMessageTracker.getTrackedClients().contains(clientId)) { Tracker<R> sharedTracker = sharedMessageTracker.getTracker(clientId); sharedTracker.reconcile(context.getOldestTransactionId()); if (response == null) { response = sharedTracker.getTrackedValue(context.getCurrentTransactionId()); } } if (response != null) { return response; } response = invokeFunction.apply(context, message); messageTracker.track(context.getCurrentTransactionId(), message, response); return response; } else { return invokeFunction.apply(context, message); } }

Target:
public R invoke(InvokeContext context, M message, BiFunction<InvokeContext, M, R> invokeFunction) throws EntityUserException { if (trackerPolicy.test(message) && context.isValidClientInformation()) { ClientSourceId clientId = context.getClientSource(); int index = segmentationStrategy.applyAsInt(message); Tracker<R> messageTracker = clientMessageTrackers.get(index).getTracker(clientId); messageTracker.reconcile(context.getOldestTransactionId()); R response = messageTracker.getTrackedValue(context.getCurrentTransactionId()); if (response == null && sharedMessageTracker.getTrackedClients().contains(clientId)) { Tracker<R> sharedTracker = sharedMessageTracker.getTracker(clientId); sharedTracker.reconcile(context.getOldestTransactionId()); response = sharedTracker.getTrackedValue(context.getCurrentTransactionId()); } if (response != null) { return response; } response = invokeFunction.apply(context, message); messageTracker.track(context.getCurrentTransactionId(), message, response); return response; } else { return invokeFunction.apply(context, message); } }
Source:
private SqlSchema convertSchema(List<Schema.Field> fields) { SqlSchemaBuilder schemaBuilder = SqlSchemaBuilder.builder(); for (Schema.Field field : fields) { SqlFieldSchema fieldSchema = convertField(field.schema()); schemaBuilder.addField(field.name(), fieldSchema); } return schemaBuilder.build(); }

Target:
private SqlSchema convertSchema(List<Schema.Field> fields) { Validate.notEmpty(fields, "Fields cannot be empty"); SqlSchemaBuilder schemaBuilder = SqlSchemaBuilder.builder(); for (Schema.Field field : fields) { SqlFieldSchema fieldSchema = convertField(field.schema()); schemaBuilder.addField(field.name(), fieldSchema); } return schemaBuilder.build(); }
Source:
public void activate(final BundleContext bundleContext, final Map<String, Object> configuration) { logger.debug("activate()"); try { startup(PanStampBindingSettings.parseConfig(configuration)); } catch (ValueException e) { logger.error(e.getMessage()); } }

Target:
public void activate(final BundleContext bundleContext, final Map<String, Object> configuration) { logger.debug("activate()"); try { startup(PanStampBindingSettings.parseConfig(configuration)); } catch (ValueException e) { logger.error("Configuration error: ", e.getMessage()); } }
Source:
default File resolve(File path) { return path.isAbsolute() ? path : new VoltFile(getVoltDBRoot(), path.getPath()); }

Target:
default File resolve(File path) { return path.isAbsolute() ? path : new File(getVoltDBRoot(), path.getPath()); }
Source:
public List<AttestationValue> attestHosts(Set<String> hosts){ String pollURI = Config.<String> GetValue(ConfigValues.PollUri); List<AttestationValue> values = new ArrayList<AttestationValue>(); PostMethod postMethod = new PostMethod("/" +pollURI); try { postMethod.setRequestEntity(new StringRequestEntity(writeListJson(hosts))); postMethod.addRequestHeader("Accept",CONTENT_TYPE); postMethod.addRequestHeader("Content-type", CONTENT_TYPE); HttpClient httpClient = getClient(); int statusCode = httpClient.executeMethod(postMethod); String strResponse = postMethod.getResponseBodyAsString(); log.debug("return attested result:" +strResponse); if (statusCode == 200){ values = parsePostedResp(strResponse); } else{ String fault = strResponse; log.error("attestation error:" +fault); } }catch (UnsupportedEncodingException e) { log.error(e.getMessage(), e); }catch (IOException e) { log.error(e.getMessage(), e); }finally { postMethod.releaseConnection(); } return values; }

Target:
public List<AttestationValue> attestHosts(Set<String> hosts) { String pollURI = Config.<String> GetValue(ConfigValues.PollUri); List<AttestationValue> values = new ArrayList<AttestationValue>(); PostMethod postMethod = new PostMethod("/" + pollURI); try { postMethod.setRequestEntity(new StringRequestEntity(writeListJson(hosts))); postMethod.addRequestHeader("Accept", CONTENT_TYPE); postMethod.addRequestHeader("Content-type", CONTENT_TYPE); HttpClient httpClient = getClient(); int statusCode = httpClient.executeMethod(postMethod); String strResponse = postMethod.getResponseBodyAsString(); log.debug("return attested result:" + strResponse); if (statusCode == 200) { values = parsePostedResp(strResponse); } else { String fault = strResponse; log.error("attestation error:" + fault); } } catch (JsonParseException e) { log.error(String.format("Failed to parse result: [%s]", e.getMessage()), e); } catch (IOException e) { log.error(String.format("Failed to attest hosts: [%s], make sure hosts are up and reachable", e.getMessage()), e); } finally { postMethod.releaseConnection(); } return values; }
Source:
public static OsAppCredentials anonymous() { return new OsAppCredentials(nativeCreate(TYPE_ANONYMOUS), Credentials.IdentityProvider.ANONYMOUS); }

Target:
public static OsAppCredentials anonymous() { return new OsAppCredentials(nativeCreate(TYPE_ANONYMOUS)); }
Source:
private void updateNextRunConfiguration() { final VmStatic nextRunConfigurationStatic = runInternalQuery( VdcQueryType.GetVmNextRunConfiguration, new IdQueryParameters(getVmId())) .<VM>getReturnValue() .getStaticData(); final int newMemorySize = nextRunConfigurationStatic.getMemSizeMb() - getUnpluggedDeviceSize(); if (newMemorySize <= 0) { return; } if (getVm().getMemSizeMb() != nextRunConfigurationStatic.getMemSizeMb()) { return; } nextRunConfigurationStatic.setMemSizeMb(newMemorySize); if (newMemorySize < nextRunConfigurationStatic.getMinAllocatedMem()) { nextRunConfigurationStatic.setMinAllocatedMem(newMemorySize); } vmHandler.createNextRunSnapshot( getVm(), nextRunConfigurationStatic, null, getCompensationContext()); }

Target:
private void updateNextRunConfiguration() { final VmStatic nextRunConfigurationStatic = getNextRunConfiguration(); if (nextRunConfigurationStatic == null) { return; } final int newMemorySize = nextRunConfigurationStatic.getMemSizeMb() - getUnpluggedDeviceSize(); if (newMemorySize <= 0) { return; } if (getVm().getMemSizeMb() != nextRunConfigurationStatic.getMemSizeMb()) { return; } nextRunConfigurationStatic.setMemSizeMb(newMemorySize); if (newMemorySize < nextRunConfigurationStatic.getMinAllocatedMem()) { nextRunConfigurationStatic.setMinAllocatedMem(newMemorySize); } vmHandler.createNextRunSnapshot( getVm(), nextRunConfigurationStatic, null, getCompensationContext()); }
Source:
private static boolean attemptInstantiation() { if (instantiated == false) { lock.lock(); try { if (instantiated == false) { asyncHttpClientImplClass = AsyncImplHelper .getAsyncImplClass(AsyncImplHelper.ASYNC_HTTP_CLIENT_IMPL_SYSTEM_PROPERTY); instantiated = true; } } finally { lock.unlock(); } } return (asyncHttpClientImplClass != null); }

Target:
private static boolean attemptInstantiation() { if (!instantiated) { lock.lock(); try { if (!instantiated) { asyncHttpClientImplClass = AsyncImplHelper .getAsyncImplClass(AsyncImplHelper.ASYNC_HTTP_CLIENT_IMPL_SYSTEM_PROPERTY); instantiated = true; } } finally { lock.unlock(); } } return asyncHttpClientImplClass != null; }
Source:
public void validate_shouldFailIfTheConceptClassIsNull() throws Exception { Concept concept = new Concept(); concept.addName(new ConceptName("some name",Context.getLocale())); concept.addDescription(new ConceptDescription("some description",null)); concept.setDatatype(new ConceptDatatype()); Errors errors = new BindException(concept, "concept"); new ConceptValidator().validate(concept, errors); Assert.assertTrue(errors.hasErrors()); }

Target:
public void validate_shouldFailIfTheConceptClassIsNull() throws Exception { Concept concept = new Concept(); concept.addName(new ConceptName("some name",Context.getLocale())); concept.addDescription(new ConceptDescription("some description",null)); concept.setDatatype(new ConceptDatatype(1)); Errors errors = new BindException(concept, "concept"); new ConceptValidator().validate(concept, errors); Assert.assertEquals(errors.getFieldError("conceptClass").getCode(), "Concept.conceptClass.empty"); }
Source:
public void testMetricsCacheClientService() throws Exception { MetricsCacheSink metricsCacheSink = new MetricsCacheSink(); Map<String, Object> serviceConfig = buildServiceConfig(); metricsCacheSink.createSimpleMetricsCacheClientService(serviceConfig); metricsCacheSink.startNewMetricsCacheClient(getMetricsCacheLocation(0)); SysUtils.sleep(RESTART_WAIT_INTERVAL); assertTrue(metricsCacheSink.getMetricsCacheStartedAttempts() >= (RESTART_WAIT_INTERVAL.getSeconds() - 2 * RECONNECT_INTERVAL.getSeconds())); metricsCacheSink.close(); }

Target:
public void testMetricsCacheClientService() throws Exception { MetricsCacheSink metricsCacheSink = new MetricsCacheSink(); Map<String, Object> serviceConfig = buildServiceConfig(); metricsCacheSink.createSimpleMetricsCacheClientService(serviceConfig); metricsCacheSink.startNewMetricsCacheClient(getMetricsCacheLocation(0)); SysUtils.sleep(RESTART_WAIT_INTERVAL); assertTrue(metricsCacheSink.getMetricsCacheStartedAttempts() >= (RESTART_WAIT_INTERVAL.getSeconds() / RECONNECT_INTERVAL.getSeconds() / 2)); metricsCacheSink.close(); }
Source:
public Key(Text row) { this(row.getBytes()); }

Target:
public Key(Text row) { init(row.getBytes(), 0, row.getLength(), EMPTY_BYTES, 0, 0, EMPTY_BYTES, 0, 0, EMPTY_BYTES, 0, 0, Long.MAX_VALUE, false, true); }
Source:
public void setUp() throws Exception { ApplicationConfiguration configuration = ApplicationConfiguration.defaultConfiguration() .withSource(Publisher.METABROADCAST, SourceStatus.AVAILABLE_ENABLED) .copyWithWritableSources(ImmutableList.of(Publisher.METABROADCAST)); inputBytes = "{ content: }".getBytes(); DelegatingServletInputStream inputStream = new DelegatingServletInputStream( new ByteArrayInputStream(inputBytes) ); Item content = new Item(); content.setCanonicalUri("uri"); content.setPublisher(Publisher.METABROADCAST); inputContent = new ContentWriteExecutor.InputContent(content, "item"); contentId = 0L; when(configurationFetcher.configurationFor(request)).thenReturn(Maybe.just(configuration)); when(request.getInputStream()).thenReturn(inputStream); when(writeExecutor.parseInputStream(any(InputStream.class), anyBoolean())).thenReturn(inputContent); when(idGenerator.getId(any(Content.class))).thenReturn(contentId); when(response.getOutputStream()).thenReturn(outputStream); when(lookupEntry.uri()).thenReturn(uri); ArrayList<LookupEntry> entryList = new ArrayList<>(); entryList.add(lookupEntry); when(lookupEntryStore.entriesForIds(anyList())) .thenReturn(entryList); when(contentResolver.findByCanonicalUris(Lists.newArrayList(uri))) .thenReturn(resolvedContent); controller = new ContentWriteController( configurationFetcher, writeExecutor, idGenerator, messageSender, modelWriter, lookupEntryStore, contentResolver, contentWriter ); }

Target:
public void setUp() throws Exception { ApplicationConfiguration configuration = ApplicationConfiguration.defaultConfiguration() .withSource(Publisher.METABROADCAST, SourceStatus.AVAILABLE_ENABLED) .copyWithWritableSources(ImmutableList.of(Publisher.METABROADCAST)); inputBytes = "{ content: }".getBytes(); DelegatingServletInputStream inputStream = new DelegatingServletInputStream( new ByteArrayInputStream(inputBytes) ); Item content = new Item(); content.setCanonicalUri("uri"); content.setPublisher(Publisher.METABROADCAST); inputContent = new ContentWriteExecutor.InputContent(content, "item"); contentId = 0L; when(configurationFetcher.configurationFor(request)).thenReturn(Maybe.just(configuration)); when(request.getInputStream()).thenReturn(inputStream); when(writeExecutor.parseInputStream(any(InputStream.class), anyBoolean())).thenReturn(inputContent); when(idGenerator.getId(any(Content.class))).thenReturn(contentId); when(response.getOutputStream()).thenReturn(outputStream); when(lookupEntry.uri()).thenReturn(uri); ImmutableList<LookupEntry> entryList = ImmutableList.of(lookupEntry); when(lookupEntryStore.entriesForIds(anyList())) .thenReturn(entryList); when(contentResolver.findByCanonicalUris(Lists.newArrayList(uri))) .thenReturn(resolvedContent); controller = ContentWriteController.create( configurationFetcher, writeExecutor, idGenerator, messageSender, modelWriter, lookupEntryStore, contentResolver, contentWriter ); }
Source:
public void onLoaded() { wa.contextDestroyed(null); throw new Error(); }

Target:
public void onLoaded() { wa.contextDestroyed(null); }
Source:
public void run() { if(thread == null || !Thread.currentThread().equals(thread)) { thread = new Thread(this); thread.start(); } else { try { if (logger.isInfoEnabled()) logger.info("Start reconnecting " + provider); provider.register( getUIService().getDefaultSecurityAuthority(provider)); } catch (OperationFailedException ex) { logger.error("cannot re-register provider will keep going", ex); } } }

Target:
public void run() { try { if (logger.isInfoEnabled()) logger.info("Start reconnecting " + provider); provider.register( getUIService().getDefaultSecurityAuthority(provider)); } catch (OperationFailedException ex) { logger.error("cannot re-register provider will keep going", ex); } }
Source:
public long saveSequencerPartitionContainer(SequencerPartitionContainer<SequencerPoolPartition>container) throws IOException { if (sequencerPartitionContainerStore != null) { if (container.getId() == AbstractSequencerPartitionContainer.UNSAVED_ID) { return sequencerPartitionContainerStore.save(container); } else { SequencerPartitionContainer<SequencerPoolPartition> managed = getSequencerPartitionContainerById(container.getId()); managed.setIdentificationBarcode(container.getIdentificationBarcode()); managed.setLocationBarcode(container.getLocationBarcode()); managed.setValidationBarcode(container.getValidationBarcode()); Collection<Run> runs = new HashSet<>(); for (Run run : container.getRuns()) { if (run != null) runs.add(getRunById(run.getId())); } managed.setRuns(runs); managed.setPlatform(container.getPlatform()); updatePartitionPools(container, managed); return sequencerPartitionContainerStore.save(managed); } } else { throw new IOException("No sequencerPartitionContainerStore available. Check that it has been declared in the Spring config."); } }

Target:
public long saveSequencerPartitionContainer(SequencerPartitionContainer<SequencerPoolPartition>container) throws IOException { if (sequencerPartitionContainerStore != null) { if (container.getId() == AbstractSequencerPartitionContainer.UNSAVED_ID) { return sequencerPartitionContainerStore.save(container); } else { SequencerPartitionContainer<SequencerPoolPartition> managed = getSequencerPartitionContainerById(container.getId()); managed.setIdentificationBarcode(container.getIdentificationBarcode()); managed.setLocationBarcode(container.getLocationBarcode()); managed.setValidationBarcode(container.getValidationBarcode()); updatePartitionPools(container, managed); return sequencerPartitionContainerStore.save(managed); } } else { throw new IOException("No sequencerPartitionContainerStore available. Check that it has been declared in the Spring config."); } }
Source:
public Observable<MessageConnection> connect() { return resolver.resolve() .take(1) .map(new Func1<Server, RxClient<Object, Object>>() { @Override public RxClient<Object, Object> call(Server server) { RxClient<Object, Object> client = clients.get(server); if (null == client) { client = RxNetty.createTcpClient(server.getHost(), server.getPort(), pipelineConfigurator); clients.put(server, client); } logger.info("Connecting to server {}", server); return client; } }) .flatMap(new Func1<RxClient<Object, Object>, Observable<MessageConnection>>() { @Override public Observable<MessageConnection> call(final RxClient<Object, Object> client) { return client.connect() .map(new Func1<ObservableConnection<Object, Object>, MessageConnection>() { @Override public MessageConnection call( ObservableConnection<Object, Object> conn) { return new SelfClosingConnection( new HeartBeatConnection( new BaseMessageConnection(clientId, conn, metrics), config.getHeartbeatIntervalMs(), 3, Schedulers.computation() ), config.getConnectionAutoTimeoutMs() ); } }); } }); }

Target:
public Observable<MessageConnection> connect() { return resolver.resolve() .take(1) .map(new Func1<Server, RxClient<Object, Object>>() { @Override public RxClient<Object, Object> call(Server server) { RxClient<Object, Object> client = clients.get(server); if (null == client) { client = RxNetty.createTcpClient(server.getHost(), server.getPort(), pipelineConfigurator); clients.put(server, client); } logger.info("Connecting to server {}", server); return client; } }) .flatMap(new Func1<RxClient<Object, Object>, Observable<MessageConnection>>() { @Override public Observable<MessageConnection> call(final RxClient<Object, Object> client) { return client.connect() .map(new Func1<ObservableConnection<Object, Object>, MessageConnection>() { @Override public MessageConnection call( ObservableConnection<Object, Object> conn) { String clientInstanceId = clientId + '#' + clientInstanceIdx.incrementAndGet(); return new SelfClosingConnection( new HeartBeatConnection( new BaseMessageConnection(clientInstanceId, conn, metrics), config.getHeartbeatIntervalMs(), 3, Schedulers.computation() ), config.getConnectionAutoTimeoutMs() ); } }); } }); }
Source:
private MoveOrCopyImageGroupParameters buildMoveOrCopyImageGroupParametersForMemoryDumpImage( Guid containerID, Guid storageDomainId, Guid imageId, Guid volumeId) { MoveOrCopyImageGroupParameters params = new MoveOrCopyImageGroupParameters(containerID, imageId, volumeId, getParameters().getStorageDomainId(), getMoveOrCopyImageOperation()); params.setParentCommand(getActionType()); params.setCopyVolumeType(CopyVolumeType.LeafVol); params.setForceOverride(getParameters().getForceOverride()); params.setSourceDomainId(storageDomainId); params.setEntityInfo(getParameters().getEntityInfo()); params.setParentParameters(getParameters()); if (getStorageDomain().getStorageType().isBlockDomain()) { params.setUseCopyCollapse(true); params.setVolumeType(VolumeType.Sparse); params.setVolumeFormat(VolumeFormat.RAW); } return params; }

Target:
private MoveOrCopyImageGroupParameters buildMoveOrCopyImageGroupParametersForMemoryDumpImage( Guid containerID, Guid storageDomainId, Guid imageId, Guid volumeId) { MoveOrCopyImageGroupParameters params = new MoveOrCopyImageGroupParameters(containerID, imageId, volumeId, getParameters().getStorageDomainId(), getMoveOrCopyImageOperation()); params.setParentCommand(getActionType()); params.setCopyVolumeType(CopyVolumeType.LeafVol); params.setForceOverride(getParameters().getForceOverride()); params.setSourceDomainId(storageDomainId); params.setEntityInfo(getParameters().getEntityInfo()); params.setParentParameters(getParameters()); StorageDomainStatic sourceDomain = getStorageDomainStaticDAO().get(storageDomainId); if (sourceDomain.getStorageType().isBlockDomain()) { params.setUseCopyCollapse(true); params.setVolumeType(VolumeType.Sparse); params.setVolumeFormat(VolumeFormat.RAW); } return params; }
Source:
public HttpResponse doPlatformPluginList() throws IOException { jenkins.install.SetupWizard setupWizard = Jenkins.getInstance().getSetupWizard(); if (setupWizard != null) { if (InstallState.UPGRADE.equals(Jenkins.getInstance().getInstallState())) { JSONArray initialPluginData = getPlatformPluginUpdates(); if(initialPluginData != null) { return hudson.util.HttpResponses.okJSON(initialPluginData); } } else { JSONArray initialPluginData = getPlatformPluginList(); if(initialPluginData != null) { return hudson.util.HttpResponses.okJSON(initialPluginData); } } } return hudson.util.HttpResponses.okJSON(); }

Target:
public HttpResponse doPlatformPluginList() throws IOException { jenkins.install.SetupWizard setupWizard = Jenkins.getInstance().getSetupWizard(); if (setupWizard != null) { if (InstallState.UPGRADE.equals(Jenkins.getInstance().getInstallState())) { JSONArray initialPluginData = getPlatformPluginUpdates(); if(initialPluginData != null) { return HttpResponses.okJSON(initialPluginData); } } else { JSONArray initialPluginData = getPlatformPluginList(); if(initialPluginData != null) { return HttpResponses.okJSON(initialPluginData); } } } return HttpResponses.okJSON(); }
Source:
private void testVerifyAtLeastOneInstructorIsDisplayed() throws Exception { ______TS("success: at least one instructor is displayed to students"); String courseId = "idOfTypicalCourse1"; String courseIdWithNoInstructorsDisplayed = "idOfTestingInstructorsDisplayedCourse"; boolean isEditedInstructorDisplayed = true; boolean isOriginalInstructorDisplayed = true; instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(isOriginalInstructorDisplayed, courseId, isEditedInstructorDisplayed); instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(isOriginalInstructorDisplayed, courseId, !isEditedInstructorDisplayed); instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(!isOriginalInstructorDisplayed, courseId, !isEditedInstructorDisplayed); instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(!isOriginalInstructorDisplayed, courseIdWithNoInstructorsDisplayed, !isEditedInstructorDisplayed); ______TS("failure: No instructors displayed to students"); InvalidParametersException ive = assertThrows(InvalidParametersException.class, () -> instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(isOriginalInstructorDisplayed, courseIdWithNoInstructorsDisplayed, !isEditedInstructorDisplayed)); assertEquals("At least one instructor must be displayed to students", ive.getMessage()); ______TS("failure: null parameter"); AssertionError ae = assertThrows(AssertionError.class, () -> instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(isOriginalInstructorDisplayed, null, isEditedInstructorDisplayed)); AssertHelper.assertContains("Supplied parameter was null", ae.getMessage()); }

Target:
private void testVerifyAtLeastOneInstructorIsDisplayed() throws Exception { ______TS("success: at least one instructor is displayed to students"); String courseId = "idOfTypicalCourse1"; String courseIdWithNoInstructorsDisplayed = "idOfTestingInstructorsDisplayedCourse"; instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(courseId, true, true); instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(courseId, true, false); instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(courseId, false, false); instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(courseIdWithNoInstructorsDisplayed, false, false); ______TS("failure: No instructors displayed to students"); InvalidParametersException ive = assertThrows(InvalidParametersException.class, () -> instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(courseIdWithNoInstructorsDisplayed, true, false)); assertEquals("At least one instructor must be displayed to students", ive.getMessage()); ______TS("failure: null parameter"); AssertionError ae = assertThrows(AssertionError.class, () -> instructorsLogic.verifyAtLeastOneInstructorIsDisplayed(null, true, true)); AssertHelper.assertContains("Supplied parameter was null", ae.getMessage()); }
Source:
private void testUpdate(Checksum checksum, ByteBufChecksum wrapped, ByteBuf buf, int off, int len) { checksum.reset(); wrapped.reset(); checksum.update(BYTE_ARRAY, off, len); wrapped.update(buf, off, len); assertEquals(checksum.getValue(), wrapped.getValue()); }

Target:
private static void testUpdate(Checksum checksum, ByteBufChecksum wrapped, ByteBuf buf, int off, int len) { checksum.reset(); wrapped.reset(); checksum.update(BYTE_ARRAY, off, len); wrapped.update(buf, off, len); assertEquals(checksum.getValue(), wrapped.getValue()); }
Source:
default Optional<float[]> getFloatArrayAttribute(final String tag) { final Optional<Object> attr = getAttribute(tag); if (!attr.isPresent()) { return Optional.empty(); } final Object val = attr.get(); if (val instanceof float[]) { return Optional.of((float[])val); } throw new SAMException("Value for tag " + tag + " is not a byte[]: " + val.getClass()); }

Target:
default Optional<float[]> getFloatArrayAttribute(final String tag) { final Optional<Object> attr = getAttribute(tag); if (!attr.isPresent()) { return Optional.empty(); } final Object val = attr.get(); if (val instanceof float[]) { return Optional.of((float[])val); } throw new SAMException("Value for tag " + tag + " is not a float[]: " + val.getClass()); }
Source:
public InputReader(InputStream inputStream) { fResult = new StringBuilder(); fReader = new InputStreamReader(inputStream); fThread = new Thread() { @Override public void run() { final char[] buffer = new char[1024]; int read; try { while (!fDone && (read = fReader.read(buffer)) > 0) { fResult.append(buffer, 0, read); } } catch (IOException e) { } } }; fThread.start(); }

Target:
public InputReader(InputStream inputStream) { fResult = new StringBuilder(); fReader = new InputStreamReader(inputStream); fThread = new Thread() { @Override public void run() { final char[] buffer = new char[BYTES_PER_KB]; int read; try { while (!fDone && (read = fReader.read(buffer)) > 0) { fResult.append(buffer, 0, read); } } catch (IOException e) { } } }; fThread.start(); }
Source:
public TmfRGB(short red, short green, short blue) { if ((red > 255) || (red < 0) || (green > 255) || (green < 0) || (blue > 255) || (blue < 0)) { throw new IllegalArgumentException("Red, green and blue component must be between 0 and 255"); } fRed = red; fGreen = green; fBlue = blue; }

Target:
public TmfRGB(short red, short green, short blue) { if ((red > 255) || (red < 0)) { throw new IllegalArgumentException("Red component must be between 0 and 255"); } if ((green > 255) || (green < 0)) { throw new IllegalArgumentException("Green component must be between 0 and 255"); } if ((blue > 255) || (blue < 0)) { throw new IllegalArgumentException("Blue component must be between 0 and 255"); } fRed = red; fGreen = green; fBlue = blue; }
Source:
public void setHits(long hits) { this.hits = hits; }

Target:
protected void setHits(long hits) { HITS_UPDATER.set(this, hits); }
Source:
public static byte[] buildAndSaveKeystore(final String alias, final String cert, final String privateKey, final String storePassword) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, IOException { final KeyStore ks = buildKeystore(alias, cert, privateKey, storePassword); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { ks.store(os, storePassword != null ? storePassword.toCharArray() : null); return os.toByteArray(); } }

Target:
public static byte[] buildAndSaveKeystore(final String alias, final String cert, final String privateKey, final String storePassword) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, IOException { Preconditions.checkArgument(!Strings.isNullOrEmpty(alias), "Certificate alias cannot be blank"); Preconditions.checkArgument(!Strings.isNullOrEmpty(cert), "Certificate cannot be blank"); Preconditions.checkArgument(!Strings.isNullOrEmpty(privateKey), "Private key cannot be blank"); final KeyStore ks = buildKeystore(alias, cert, privateKey, storePassword); try (final ByteArrayOutputStream os = new ByteArrayOutputStream()) { ks.store(os, storePassword != null ? storePassword.toCharArray() : null); return os.toByteArray(); } }
Source:
public AppendBlobItem(final String eTag, final OffsetDateTime lastModified, final byte[] contentMd5, final boolean isServerEncrypted, final String encryptionKeySha256, final String blobAppendOffset, final Integer blobCommittedBlockCount) { this.eTag = eTag; this.lastModified = lastModified; this.contentMd5 = CoreUtils.clone(contentMd5); this.isServerEncrypted = isServerEncrypted; this.encryptionKeySha256 = encryptionKeySha256; this.encryptionScope = null; this.blobAppendOffset = blobAppendOffset; this.blobCommittedBlockCount = blobCommittedBlockCount; }

Target:
public AppendBlobItem(final String eTag, final OffsetDateTime lastModified, final byte[] contentMd5, final boolean isServerEncrypted, final String encryptionKeySha256, final String blobAppendOffset, final Integer blobCommittedBlockCount) { this(eTag, lastModified, contentMd5, isServerEncrypted, encryptionKeySha256, null, blobAppendOffset, blobCommittedBlockCount); }
Source:
private List<String> getErrors() { List<String> errors = new ArrayList<>(); if (!exportDir.isPresent()) errors.add("Export directory was not specified."); if (!exportDir.filter(path -> Files.exists(path)).isPresent()) errors.add(DIR_NOT_EXIST); if (!exportDir.filter(path -> Files.isDirectory(path)).isPresent()) errors.add(DIR_NOT_DIRECTORY); if (!exportDir.filter(path -> !isUnderODKFolder(path.toFile())).isPresent()) errors.add(DIR_INSIDE_ODK_DEVICE_DIRECTORY); if (!exportDir.filter(path -> !isUnderBriefcaseFolder(path.toFile())).isPresent()) errors.add(DIR_INSIDE_BRIEFCASE_STORAGE); if (startDate.isPresent() && !endDate.isPresent()) errors.add("Missing date range end definition"); if (!startDate.isPresent() && endDate.isPresent()) errors.add("Missing date range start definition"); if (!isDateRangeValid()) errors.add(INVALID_DATE_RANGE_MESSAGE); if (!isPemFilePresent()) errors.add(INVALID_PEM_FILE); return errors; }

Target:
private List<String> getErrors() { List<String> errors = new ArrayList<>(); if (!exportDir.isPresent()) errors.add("Export directory was not specified."); if (!exportDir.filter(path -> Files.exists(path)).isPresent()) errors.add(DIR_NOT_EXIST); if (!exportDir.filter(path -> Files.isDirectory(path)).isPresent()) errors.add(DIR_NOT_DIRECTORY); if (!exportDir.filter(path -> !isUnderODKFolder(path.toFile())).isPresent()) errors.add(DIR_INSIDE_ODK_DEVICE_DIRECTORY); if (!exportDir.filter(path -> !isUnderBriefcaseFolder(path.toFile())).isPresent()) errors.add(DIR_INSIDE_BRIEFCASE_STORAGE); if (startDate.isPresent() && !endDate.isPresent()) errors.add("Missing date range end definition"); if (!startDate.isPresent() && endDate.isPresent()) errors.add("Missing date range start definition"); if (!isDateRangeValid()) errors.add(INVALID_DATE_RANGE_MESSAGE); if (formNeedsPrivateKey.orElse(false) && !isPemFilePresent()) errors.add(INVALID_PEM_FILE); return errors; }
Source:
private void addGroups(Map<String, Map<ServerLocationAndMemberId, LoadHolder>> map, String[] groups, LoadHolder holder, String memberId) { for (String group : groups) { Map<ServerLocationAndMemberId, LoadHolder> groupMap = map.computeIfAbsent(group, k -> new HashMap<>()); groupMap.put(new ServerLocationAndMemberId(holder.getLocation(), memberId), holder); } if (!(groups.length > 0 && groups[0].equals(GatewayReceiver.RECEIVER_GROUP))) { Map<ServerLocationAndMemberId, LoadHolder> groupMap = map.computeIfAbsent(null, k -> new HashMap<>()); groupMap.put(new ServerLocationAndMemberId(holder.getLocation(), memberId), holder); } }

Target:
void addGroups(Map<String, Map<ServerLocationAndMemberId, LoadHolder>> map, String[] groups, LoadHolder holder, String memberId) { for (String group : groups) { Map<ServerLocationAndMemberId, LoadHolder> groupMap = map.computeIfAbsent(group, k -> new HashMap<>()); groupMap.put(new ServerLocationAndMemberId(holder.getLocation(), memberId), holder); } if (!(groups.length > 0 && groups[0].equals(GatewayReceiver.RECEIVER_GROUP))) { Map<ServerLocationAndMemberId, LoadHolder> groupMap = map.computeIfAbsent(null, k -> new HashMap<>()); groupMap.put(new ServerLocationAndMemberId(holder.getLocation(), memberId), holder); } }
Source:
public List<TileEntity> getBaseTilesFor(TileEntity tile) { List<TileEntity> tiles = new ArrayList<TileEntity>(1); tiles.add(tile); return tiles; }

Target:
public List<TileEntity> getBaseTilesFor(TileEntity tile) { List<TileEntity> tiles = new ArrayList<TileEntity>(1); if(tile instanceof IGridHost){ IGridHost host = (IGridHost) tile; IGridNode node = host.getGridNode(ForgeDirection.UNKNOWN); if(node != null){ TileEntity base = getBaseTileEntity(node); if(base != null){ tiles.add(base); return tiles; } } } tiles.add(tile); return tiles; }
Source:
private Planner getPlanner(List<RelTraitDef> traitDefs, SqlParser.Config parserConfig, Program... programs) { final SchemaPlus rootSchema = Frameworks.createRootSchema(true); final FrameworkConfig config = Frameworks.newConfigBuilder() .parserConfig(parserConfig) .defaultSchema( CalciteAssert.addSchema(rootSchema, SchemaSpec.HR)) .traitDefs(traitDefs) .programs(programs) .build(); return Frameworks.getPlanner(config); }

Target:
private Planner getPlanner(List<RelTraitDef> traitDefs, SqlParser.Config parserConfig, Program... programs) { final SchemaPlus rootSchema = Frameworks.createRootSchema(true); final FrameworkConfig config = Frameworks.newConfigBuilder() .parserConfig(parserConfig) .defaultSchema( CalciteAssert.addSchema(rootSchema, CalciteAssert.SchemaSpec.HR)) .traitDefs(traitDefs) .programs(programs) .build(); return Frameworks.getPlanner(config); }
Source:
public URI uploadSegment(File segmentFile, LLCSegmentName segmentName) { if (_segmentStoreUriStr == null || _segmentStoreUriStr.isEmpty()) { return null; } Callable<URI> uploadTask = () -> { try { PinotFS pinotFS = PinotFSFactory.create(new URI(_segmentStoreUriStr).getScheme()); URI destUri = new URI(StringUtil .join(File.separator, _segmentStoreUriStr, segmentName.getTableName(), segmentName.getSegmentName())); if (pinotFS.exists(destUri)) { pinotFS.delete(destUri, true); } pinotFS.copyFromLocalFile(segmentFile, destUri); return destUri; } catch (Exception e) { LOGGER.warn("Failed copy segment tar file to segment store {}: {}", segmentFile.getName(), e); } return null; }; Future<URI> future = _executorService.submit(uploadTask); try { URI segmentLocation = future.get(_timeoutInMs, TimeUnit.MILLISECONDS); return segmentLocation; } catch (InterruptedException e) { LOGGER.info("Interrupted while waiting for segment upload."); Thread.currentThread().interrupt(); } catch (Exception e) { LOGGER .warn("Failed to upload file of segment for table ", segmentFile.getAbsolutePath(), segmentName, e); } return null; }

Target:
public URI uploadSegment(File segmentFile, LLCSegmentName segmentName) { if (_segmentStoreUriStr == null || _segmentStoreUriStr.isEmpty()) { return null; } Callable<URI> uploadTask = () -> { URI destUri = new URI(StringUtil .join(File.separator, _segmentStoreUriStr, segmentName.getTableName(), segmentName.getSegmentName())); try { PinotFS pinotFS = PinotFSFactory.create(new URI(_segmentStoreUriStr).getScheme()); if (pinotFS.exists(destUri)) { pinotFS.delete(destUri, true); } pinotFS.copyFromLocalFile(segmentFile, destUri); return destUri; } catch (Exception e) { LOGGER.warn("Failed copy segment tar file to segment store {}: {}", segmentFile.getName(), destUri, e); } return null; }; Future<URI> future = _executorService.submit(uploadTask); try { URI segmentLocation = future.get(_timeoutInMs, TimeUnit.MILLISECONDS); return segmentLocation; } catch (InterruptedException e) { LOGGER.info("Interrupted while waiting for segment upload of to {}.", segmentName, _segmentStoreUriStr); Thread.currentThread().interrupt(); } catch (Exception e) { LOGGER .warn("Failed to upload file of segment for table ", segmentFile.getAbsolutePath(), segmentName, e); } return null; }
Source:
private AllocatedEvaluator launchContainerForExecutor(final HeronWorker worker) { Future<AllocatedEvaluator> result = executor.submit(new Callable<AllocatedEvaluator>() { @Override public AllocatedEvaluator call() throws Exception { AllocatedEvaluator evaluator = allocateContainer(worker.workerId, worker.cores, worker.mem); if (evaluator == null) { LOG.log(Level.WARNING, "Could not allocate container for id {0}", worker.workerId); return null; } Configuration context = createContextConfig(worker.workerId); LOG.log(Level.INFO, "Activating container {0} for heron executor, id: {1}", new Object[]{evaluator.getId(), worker.workerId}); evaluator.submitContext(context); multiKeyWorkerMap.assignEvaluatorToWorker(worker, evaluator); return evaluator; } }); try { return result.get(); } catch (InterruptedException e) { LOG.log(Level.SEVERE, "Interrupted while waiting for container", e); } catch (ExecutionException e) { LOG.log(Level.SEVERE, "Error while waiting for container", e); } return null; }

Target:
private AllocatedEvaluator launchContainerForExecutor(final HeronWorker worker) throws ContainerAllocationException { Future<AllocatedEvaluator> result = executor.submit(new Callable<AllocatedEvaluator>() { @Override public AllocatedEvaluator call() throws Exception { AllocatedEvaluator evaluator = allocateContainer(worker.workerId, worker.cores, worker.mem); Configuration context = createContextConfig(worker.workerId); LOG.log(Level.INFO, "Activating container {0} for heron executor, id: {1}", new Object[]{evaluator.getId(), worker.workerId}); evaluator.submitContext(context); multiKeyWorkerMap.assignEvaluatorToWorker(worker, evaluator); return evaluator; } }); try { return result.get(); } catch (InterruptedException e) { throw new ContainerAllocationException("Interrupted while waiting for container", e); } catch (ExecutionException e) { throw new ContainerAllocationException("Error while allocating container", e); } }
Source:
public Iterable<SignedIdentifier> getAccessPolicy() { return client.getAccessPolicy().collectList().block(); }

Target:
public Iterable<SignedIdentifier> getAccessPolicy() { return client.getAccessPolicy().toIterable(); }
Source:
public void testRoomDoesNotAllowsBlankTextForDisplayName() { HomeAdminPage homeAdminPage = new HomeAdminPage(); roomsPage = homeAdminPage.clickConferenceRoomsLink(); JsonReader jsonReader = new JsonReader(); String roomJsonFilePath = "\\src\\tests\\Room1.json"; String specialCharacters = jsonReader.readJsonFile("customName" , roomJsonFilePath); roomsPage.clickConferenceRoomsLink(); roomInfoPage = roomsPage.doubleClickOverRoomName(roomName); roomsPage = roomInfoPage.setDisplayName(specialCharacters) .clickSaveBtn(); roomInfoPage = roomsPage.doubleClickOverRoomName(specialCharacters); Assert.assertTrue(roomsPage.getRoomDisplayName(specialCharacters).contains(specialCharacters)); }

Target:
public void testRoomDoesNotAllowsBlankTextForDisplayName() { HomeAdminPage homeAdminPage = new HomeAdminPage(); roomsPage = homeAdminPage.clickConferenceRoomsLink(); JsonReader jsonReader = new JsonReader(); String specialCharacters = jsonReader.readJsonFile("customName" , ROOM1_PATH); roomsPage.clickConferenceRoomsLink(); roomInfoPage = roomsPage.doubleClickOverRoomName(roomName); roomsPage = roomInfoPage.setDisplayName(specialCharacters) .clickSaveBtn(); roomInfoPage = roomsPage.doubleClickOverRoomName(specialCharacters); Assert.assertTrue(roomsPage.getRoomDisplayName(specialCharacters).contains(specialCharacters)); }
Source:
public DatabaseRow poll() throws SQLException { if (_queryResultSet == null) { executeFirstChunkedQuery(); _queryStmt = _connection.prepareStatement(_chunkedQuery); _queryStmt.setFetchSize(_fetchSize); _queryStmt.setQueryTimeout(_queryTimeoutSecs); } if (!_queryResultSet.next()) { if (_endOfFile) { return null; } if (numRowsInResult < _chunkSize) { _endOfFile = true; return null; } numRowsInResult = 0; prepareChunkedQuery(); executeChunkedQuery(); if (!_queryResultSet.next()) { _endOfFile = true; return null; } } return getNextRow(); }

Target:
public DatabaseRow poll() throws SQLException { if (!_initialized) { throw new DatastreamRuntimeException("call start before calling poll for records"); } if (_queryResultSet == null) { executeFirstChunkedQuery(); _queryStmt = _connection.prepareStatement(_chunkedQuery); _queryStmt.setFetchSize(_fetchSize); _queryStmt.setQueryTimeout(_queryTimeoutSecs); } if (!_queryResultSet.next()) { if (numRowsInResult < _chunkSize) { return null; } numRowsInResult = 0; prepareChunkedQuery(); executeChunkedQuery(); if (!_queryResultSet.next()) { return null; } } return getNextRow(); }
Source:
public boolean processStateMessage(Message message) { if (super.processStateMessage(message) == HANDLED) { return HANDLED; } switch (message.what) { case CMD_HANDLE_RECEIVED_RESPONSE: try { ReceivedResponse resp = (ReceivedResponse) message.obj; validateDeleteRespPayloadAndExchangeType( resp.responsePayloads, resp.exchangeType); boolean currentSaSpiFound = hasRemoteChildSpiForDelete( resp.responsePayloads, mCurrentChildSaRecord); if (!currentSaSpiFound) { loge( "Found no remote SPI for current SA in received Delete" + " response. Shutting down anyways."); } } catch (IkeProtocolException e) { loge( "Received Delete response with invalid syntax or error" + " notifications. Shutting down anyways.", e); } finishRekey(); transitionTo(mIdle); return HANDLED; default: return NOT_HANDLED; } }

Target:
public boolean processStateMessage(Message message) { if (super.processStateMessage(message) == HANDLED) { return HANDLED; } switch (message.what) { case CMD_HANDLE_RECEIVED_RESPONSE: try { ReceivedResponse resp = (ReceivedResponse) message.obj; validateDeleteRespPayloadAndExchangeType( resp.responsePayloads, resp.exchangeType); boolean currentSaSpiFound = hasRemoteChildSpiForDelete( resp.responsePayloads, mCurrentChildSaRecord); if (!currentSaSpiFound) { loge( "Found no remote SPI for current SA in received Delete" + " response. Shutting down old SA and finish rekey."); } } catch (IkeProtocolException e) { loge( "Received Delete response with invalid syntax or error" + " notifications. Shutting down old SA and finish rekey.", e); } finishRekey(); transitionTo(mIdle); return HANDLED; default: return NOT_HANDLED; } }
Source:
public void testConnectTimeout() throws IOException, StripeException { Stripe.overrideApiBase("<LINK_0>"); thrown.expect(APIConnectionException.class); thrown.expectMessage("connect timed out"); final RequestOptions options = RequestOptions.builder().setConnectTimeout(1).build(); Balance.retrieve(options); }

Target:
public void testConnectTimeout() throws IOException, StripeException { Stripe.overrideApiBase("<LINK_1>"); thrown.expect(APIConnectionException.class); thrown.expectMessage("connect timed out"); final RequestOptions options = RequestOptions.builder().setConnectTimeout(1).build(); Balance.retrieve(options); }
Source:
public void agentStatus() { LinkedBlockingQueue<Message> agentQueue = this.messagingClient.getMessageProcessor().getMessageQueue(); if( agentQueue.isEmpty() ) { System.out.println( "There is no message being processed in agent queue" ); } else { System.out.println( "The number total of messages in agent queue is : "+agentQueue.size() ); System.out.println( "The types of messages being processed are : " ); for( Message msg : agentQueue ) { System.out.println( msg.getClass().getSimpleName() ); } } }

Target:
public String agentStatus() { StringBuilder sb = new StringBuilder(); LinkedBlockingQueue<Message> agentQueue = this.messagingClient.getMessageProcessor().getMessageQueue(); if( agentQueue.isEmpty() ) { sb.append( "There is no message being processed in agent queue\n" ); } else { sb.append( "Agent " + getScopedInstancePath() + " (" + getApplicationName() + ")\n" ); sb.append( "The number total of messages in agent queue is : " + agentQueue.size() + "\n" ); sb.append( "The types of messages being processed are : " + "\n"); for( Message msg : agentQueue ) { sb.append( msg.getClass().getSimpleName() + "\n" ); } } return sb.toString(); }
Source:
public static void testSetInts() { byte[] destination = new byte[POSITIONS_PER_PAGE * ARRAY_INT_INDEX_SCALE]; int copiedBytes = setInts(destination, 0, IntStream.range(0, POSITIONS_PER_PAGE).toArray(), 0, POSITIONS_PER_PAGE); assertEquals(copiedBytes, POSITIONS_PER_PAGE * ARRAY_INT_INDEX_SCALE); assertCopied( IntStream.range(0, POSITIONS_PER_PAGE).boxed().collect(Collectors.toList()), destination, ARRAY_INT_INDEX_SCALE, ByteArrays::getInt); }

Target:
public static void testSetInts() { byte[] destination = new byte[POSITIONS_PER_PAGE * ARRAY_INT_INDEX_SCALE]; int copiedBytes = setInts(destination, 0, IntStream.range(0, POSITIONS_PER_PAGE).toArray(), 0, POSITIONS_PER_PAGE); assertEquals(copiedBytes, POSITIONS_PER_PAGE * ARRAY_INT_INDEX_SCALE); assertCopied( IntStream.range(0, POSITIONS_PER_PAGE).boxed().collect(toImmutableList()), destination, ARRAY_INT_INDEX_SCALE, ByteArrays::getInt); }
Source:
public String retrieveArtifact(String APIId, String gatewayLabel, String gatewayInstruction) throws ArtifactSynchronizerException { try { String baseURL = APIConstants.HTTPS_PROTOCOL_URL_PREFIX + System.getProperty(APIConstants.KEYMANAGER_HOSTNAME) + ":" + System.getProperty(APIConstants.KEYMANAGER_PORT) + APIConstants.INTERNAL_WEB_APP_EP; String endcodedgatewayLabel= URLEncoder.encode(gatewayLabel, APIConstants.DigestAuthConstants.CHARSET); String path = APIConstants.GatewayArtifactSynchronizer.SYNAPSE_ARTIFACTS + "?apiId=" + APIId + "&gatewayInstruction=" + gatewayInstruction +"&gatewayLabel="+ endcodedgatewayLabel; String endpoint = baseURL + path; HttpResponse httpResponse = invokeService(endpoint); return EntityUtils.toString(httpResponse.getEntity(), APIConstants.DigestAuthConstants.CHARSET); } catch (IOException e) { String msg = "Error while executing the http client " ; log.error(msg, e); throw new ArtifactSynchronizerException(msg, e); } }

Target:
public String retrieveArtifact(String APIId, String gatewayLabel, String gatewayInstruction) throws ArtifactSynchronizerException { CloseableHttpResponse httpResponse = null; try { String baseURL = eventHubConfigurationDto.getServiceUrl(); String endcodedgatewayLabel= URLEncoder.encode(gatewayLabel, APIConstants.DigestAuthConstants.CHARSET); String path = APIConstants.GatewayArtifactSynchronizer.SYNAPSE_ARTIFACTS + "?apiId=" + APIId + "&gatewayInstruction=" + gatewayInstruction + "&gatewayLabel="+ endcodedgatewayLabel; String endpoint = baseURL + path; httpResponse = invokeService(endpoint); String gatewayRuntimeArtifact = null; if (httpResponse.getEntity() != null ) { gatewayRuntimeArtifact = EntityUtils.toString(httpResponse.getEntity(), APIConstants.DigestAuthConstants.CHARSET); httpResponse.close(); } else { throw new ArtifactSynchronizerException("HTTP response is empty"); } return gatewayRuntimeArtifact; } catch (IOException e) { String msg = "Error while executing the http client"; log.error(msg, e); throw new ArtifactSynchronizerException(msg, e); } }
Source:
public static String resourceTypeNameByRemovingProfileSuffix(String resourceTypeName) { if (resourceTypeName.length() > PROFILE_SUFFIX.length() && resourceTypeName .substring(resourceTypeName.length() - PROFILE_SUFFIX.length(), resourceTypeName.length()) .equals(PROFILE_SUFFIX)) { resourceTypeName = resourceTypeName.substring(0, resourceTypeName.length() - PROFILE_SUFFIX.length()); } return resourceTypeName; }

Target:
public static String resourceTypeNameByRemovingProfileSuffix(String resourceTypeName) { if (resourceTypeName.endsWith(PROFILE_SUFFIX)) { resourceTypeName = resourceTypeName.substring(0, resourceTypeName.length() - PROFILE_SUFFIX.length()); } return resourceTypeName; }