auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public MetacardType getMetacardType(SolrDocument doc) throws MetacardCreationException { String mTypeFieldName = doc.getFirstValue(SchemaFields.METACARD_TYPE_FIELD_NAME).toString(); MetacardType cachedMetacardType = metacardTypesCache.getIfPresent(mTypeFieldName); if (cachedMetacardType != null) { return cachedMetacardType; } byte[] bytes = (byte[]) doc.getFirstValue(SchemaFields.METACARD_TYPE_OBJECT_FIELD_NAME); try { cachedMetacardType = OBJECT_MAPPER.readValue(bytes, MetacardType.class); } catch (IOException e) { LOGGER.info("IO exception loading cached metacard type", e); throw new MetacardCreationException(COULD_NOT_READ_METACARD_TYPE_MESSAGE); } metacardTypeNameToSerialCache.put(mTypeFieldName, bytes); metacardTypesCache.put(mTypeFieldName, cachedMetacardType); addToFieldsCache(cachedMetacardType.getAttributeDescriptors()); return cachedMetacardType; }

Target:
public MetacardType getMetacardType(SolrDocument doc) throws MetacardCreationException { String mTypeFieldName = doc.getFirstValue(SchemaFields.METACARD_TYPE_FIELD_NAME).toString(); MetacardType cachedMetacardType = metacardTypesCache.getIfPresent(mTypeFieldName); if (cachedMetacardType != null) { return cachedMetacardType; } byte[] bytes = (byte[]) doc.getFirstValue(SchemaFields.METACARD_TYPE_OBJECT_FIELD_NAME); try { cachedMetacardType = METACARD_TYPE_MAPPER.readValue(bytes, MetacardType.class); } catch (IOException e) { LOGGER.info("IO exception loading cached metacard type", e); throw new MetacardCreationException(COULD_NOT_READ_METACARD_TYPE_MESSAGE); } metacardTypeNameToSerialCache.put(mTypeFieldName, bytes); metacardTypesCache.put(mTypeFieldName, cachedMetacardType); addToFieldsCache(cachedMetacardType.getAttributeDescriptors()); return cachedMetacardType; }
Source:
public synchronized void remove(int n) throws IOException { if (isEmpty()) throw new NoSuchElementException(); if (n == 1) { remove(); } else if (n >= elementCount) { clear(); } else { final int eraseStartPosition = first.position; int eraseTotalLength = 0; int newFirstPosition = first.position; int newFirstLength = first.length; for (int i = 0; i < n; i++) { eraseTotalLength += Element.HEADER_LENGTH + newFirstLength; newFirstPosition = wrapPosition(newFirstPosition + Element.HEADER_LENGTH + newFirstLength); ringRead(newFirstPosition, buffer, 0, Element.HEADER_LENGTH); newFirstLength = readInt(buffer, 0); } writeHeader(fileLength, elementCount - n, newFirstPosition, last.position); elementCount -= n; first = new Element(newFirstPosition, newFirstLength); ringErase(eraseStartPosition, eraseTotalLength); } }

Target:
public synchronized void remove(int n) throws IOException { if (isEmpty()) throw new NoSuchElementException(); if (n > elementCount) { throw new IllegalArgumentException( "Cannot remove more elements (" + n + ") than present in queue (" + elementCount + ")."); } if (n == elementCount) { clear(); return; } final int eraseStartPosition = first.position; int eraseTotalLength = 0; int newFirstPosition = first.position; int newFirstLength = first.length; for (int i = 0; i < n; i++) { eraseTotalLength += Element.HEADER_LENGTH + newFirstLength; newFirstPosition = wrapPosition(newFirstPosition + Element.HEADER_LENGTH + newFirstLength); ringRead(newFirstPosition, buffer, 0, Element.HEADER_LENGTH); newFirstLength = readInt(buffer, 0); } writeHeader(fileLength, elementCount - n, newFirstPosition, last.position); elementCount -= n; first = new Element(newFirstPosition, newFirstLength); ringErase(eraseStartPosition, eraseTotalLength); }
Source:
public void testNext() throws Exception { try (FeatureWriter writer = dataStore.getFeatureWriter(tname("ft1"), Transaction.AUTO_COMMIT)) { assertTrue(writer.hasNext()); final SimpleFeature feature = (SimpleFeature) writer.next(); assertTrue(feature.getAttribute(0).toString().equals("POINT (0 0)")); assertTrue((Integer) feature.getAttribute(1) == 0); assertTrue((Double) feature.getAttribute(2) == 0.0); assertTrue(((String) feature.getAttribute(3)).equals("zero")); } try (FeatureWriter writer = dataStore.getFeatureWriter(tname("ft1"), Transaction.AUTO_COMMIT)) { assertTrue(writer.hasNext()); final SimpleFeature feature = (SimpleFeature) writer.next(); assertTrue(feature.getAttribute(0).toString().equals("POINT (0 0)")); assertTrue((Integer) feature.getAttribute(1) == 0); assertTrue((Double) feature.getAttribute(2) == 0.0); assertTrue(((String) feature.getAttribute(3)).equals("zero")); } }

Target:
public void testNext() throws Exception { try (FeatureWriter writer = dataStore.getFeatureWriter(tname("ft1"), Transaction.AUTO_COMMIT)) { assertTrue(writer.hasNext()); final SimpleFeature feature = (SimpleFeature) writer.next(); assertTrue(feature.getAttribute(0).toString().equals("POINT (0 0)")); assertTrue((Integer) feature.getAttribute(1) == 0); assertTrue((Double) feature.getAttribute(2) == 0.0); assertTrue(((String) feature.getAttribute(3)).equals("zero")); } try (FeatureWriter writer = dataStore.getFeatureWriter(tname("ft1"), Transaction.AUTO_COMMIT)) { assertTrue(writer.hasNext()); final SimpleFeature feature = (SimpleFeature) writer.next(); final List<Object> attributes = feature.getAttributes(); for (int k = 0; k < attributes.size(); k++) { assertTrue(attributes.get(k) != null); } } }
Source:
public void filter(final MethodNode methodNode, final IFilterContext context, final IFilterOutput output) { if ((methodNode.access & Opcodes.ACC_SYNTHETIC) == 0) { return; } if (!KotlinGeneratedFilter.isKotlinClass(context)) { return; } if (isDefaultArgumentsMethodName(methodNode.name)) { new Matcher().match(methodNode, output, false); } else if (isDefaultArgumentsConstructor(methodNode)) { new Matcher().match(methodNode, output, true); } }

Target:
public void filter(final MethodNode methodNode, final IFilterContext context, final IFilterOutput output) { if ((methodNode.access & Opcodes.ACC_SYNTHETIC) == 0) { return; } if (!KotlinGeneratedFilter.isKotlinClass(context)) { return; } if (isDefaultArgumentsMethod(methodNode)) { new Matcher().match(methodNode, output, false); } else if (isDefaultArgumentsConstructor(methodNode)) { new Matcher().match(methodNode, output, true); } }
Source:
private void createMasterFile(boolean isActive) throws IOException { String fileName = masterName.replaceAll(":", "_"); Path path = null; if (isActive) { path = new Path(activePath, fileName); } else { path = new Path(backupPath, fileName); } StringBuilder sb = new StringBuilder(); InetSocketAddress address = getHostAddress(HAConstants.MASTER_CLIENT_RPC_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_"); address = getHostAddress(HAConstants.RESOURCE_TRACKER_RPC_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_"); address = getHostAddress(HAConstants.CATALOG_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_"); address = getHostAddress(HAConstants.MASTER_INFO_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()); FSDataOutputStream out = fs.create(path); try { out.writeUTF(sb.toString()); out.hsync(); out.close(); } catch (FileAlreadyExistsException e) { createMasterFile(false); } if (isActive) { isActiveStatus = true; Path backupFile = new Path(backupPath, fileName); if (fs.exists(backupFile)) { fs.delete(backupFile, true); } } else { isActiveStatus = false; Path activeFile = new Path(activePath, fileName); if (fs.exists(activeFile)) { fs.delete(activeFile, true); } } startPingChecker(); }

Target:
private void createMasterFile(boolean isActive) throws IOException { String fileName = masterName.replaceAll(":", "_"); Path path = null; if (isActive) { path = new Path(activePath, fileName); } else { path = new Path(backupPath, fileName); } StringBuilder sb = new StringBuilder(); InetSocketAddress address = getHostAddress(HAConstants.MASTER_CLIENT_RPC_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_"); address = getHostAddress(HAConstants.RESOURCE_TRACKER_RPC_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_"); address = getHostAddress(HAConstants.CATALOG_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()).append("_"); address = getHostAddress(HAConstants.MASTER_INFO_ADDRESS); sb.append(address.getAddress().getHostAddress()).append(":").append(address.getPort()); FSDataOutputStream out = fs.create(path); try { out.writeUTF(sb.toString()); out.hsync(); out.close(); } catch (FileAlreadyExistsException e) { createMasterFile(false); } Path file = null; if (isActive) { isActiveStatus = true; file = new Path(backupPath, fileName); } else { isActiveStatus = false; file = new Path(activePath, fileName); } if (fs.exists(file)) { fs.delete(file, true); } startPingChecker(); }
Source:
void validateSanityForUndelete(StoreKey key, List<IndexValue> values, short lifeVersion) throws StoreException { if (values == null || values.isEmpty()) { throw new StoreException("Id " + key + " not present in index " + dataDir, StoreErrorCodes.ID_Not_Found); } if (!IndexValue.hasLifeVersion(lifeVersion)) { validateSanityForUndeleteWithoutLifeVersion(key, values); return; } IndexValue firstValue = values.get(values.size() - 1); IndexValue lastValue = values.get(0); if (!firstValue.isPut()) { throw new StoreException("Id " + key + " requires first value to be a put in index " + dataDir, StoreErrorCodes.ID_Deleted_Permanently); } if (lastValue.getLifeVersion() >= lifeVersion) { throw new StoreException( "LifeVersion conflict in index. Id " + key + " LifeVersion: " + lastValue.getLifeVersion() + " Undelete LifeVersion: " + lifeVersion, StoreErrorCodes.Life_Version_Conflict); } }

Target:
void validateSanityForUndelete(StoreKey key, List<IndexValue> values, short lifeVersion) throws StoreException { if (values == null || values.isEmpty()) { throw new StoreException("Id " + key + " not present in index " + dataDir, StoreErrorCodes.ID_Not_Found); } if (!IndexValue.hasLifeVersion(lifeVersion)) { validateSanityForUndeleteWithoutLifeVersion(key, values); return; } IndexValue firstValue = values.get(0); IndexValue lastValue = values.get(values.size() - 1); if (!lastValue.isPut()) { throw new StoreException("Id " + key + " requires first value to be a put in index " + dataDir, StoreErrorCodes.ID_Deleted_Permanently); } if (firstValue.getLifeVersion() >= lifeVersion) { throw new StoreException( "LifeVersion conflict in index. Id " + key + " LifeVersion: " + firstValue.getLifeVersion() + " Undelete LifeVersion: " + lifeVersion, StoreErrorCodes.Life_Version_Conflict); } maybeChangeExpirationDate(lastValue, values); if (isExpired(lastValue)) { throw new StoreException("Id " + key + " already expired in index " + dataDir, StoreErrorCodes.TTL_Expired); } }
Source:
public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == R.id.export_logcat) { AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); alertBuilder.setTitle("Warning!").setMessage("Logs may contain sensitive information"); alertBuilder.setPositiveButton("Continue", (dialog, which) -> { try { File filename = new File(UserPreferences.getDataFolder(null), "full-logs.txt"); filename.createNewFile(); String cmd = "logcat -d -f " + filename.getAbsolutePath(); Runtime.getRuntime().exec(cmd); try { Intent i = new Intent(Intent.ACTION_SEND); i.setType("text/*"); String authString = getString(de.danoeh.antennapod.core.R.string.provider_authority); Uri fileUri = FileProvider.getUriForFile(this, authString, filename); i.putExtra(Intent.EXTRA_STREAM, fileUri); i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { PackageManager pm = getPackageManager(); List<ResolveInfo> resInfos = pm.queryIntentActivities(i, PackageManager.MATCH_DEFAULT_ONLY); for (ResolveInfo resolveInfo : resInfos) { String packageName = resolveInfo.activityInfo.packageName; grantUriPermission(packageName, fileUri, Intent.FLAG_GRANT_READ_URI_PERMISSION); } } String chooserTitle = getString(de.danoeh.antennapod.core.R.string.share_file_label); startActivity(Intent.createChooser(i, chooserTitle)); } catch (Exception e) { e.printStackTrace(); int strResId = R.string.log_file_share_exception; Snackbar.make(findViewById(android.R.id.content), strResId, Snackbar.LENGTH_LONG) .show(); } } catch (IOException e) { e.printStackTrace(); Snackbar.make(findViewById(android.R.id.content), e.getMessage(), Snackbar.LENGTH_LONG).show(); } dialog.dismiss(); }); alertBuilder.setNegativeButton("Cancel", (dialog, which) -> dialog.cancel()); alertBuilder.create(); alertBuilder.show(); return true; } return super.onOptionsItemSelected(item); }

Target:
public boolean onOptionsItemSelected(@NonNull MenuItem item) { if (item.getItemId() == R.id.export_logcat) { AlertDialog.Builder alertBuilder = new AlertDialog.Builder(this); alertBuilder.setMessage(R.string.confirm_export_log_dialog_message); alertBuilder.setPositiveButton(R.string.confirm_label, (dialog, which) -> { exportLog(); dialog.dismiss(); }); alertBuilder.setNegativeButton(R.string.cancel_label, null); alertBuilder.show(); return true; } return super.onOptionsItemSelected(item); }
Source:
public GenericEdge(GenericEdge copyMe) { this(new GenericVertex(copyMe.source), new GenericVertex(copyMe.target), new HashMap<>(copyMe.getProperties())); }

Target:
public GenericEdge(GenericEdge copyMe) { this(new GenericVertex(copyMe.source), new GenericVertex(copyMe.target), new HashMap<>(copyMe.properties)); }
Source:
public boolean shouldBackup() { return true; }

Target:
public boolean shouldBackup() { return mapContainer.getTotalBackupCount() > 0; }
Source:
private boolean executeSshSoftFencingCommand(String version) { boolean ret = false; try ( final EngineSSHClient sshClient = new EngineSSHClient(); final ByteArrayOutputStream cmdOut = new ByteArrayOutputStream(); final ByteArrayOutputStream cmdErr = new ByteArrayOutputStream(); ) { try { log.info("Opening SSH Soft Fencing session on host '{}'", getVds().getHostName()); sshClient.setVds(getVds()); sshClient.useDefaultKeyPair(); sshClient.connect(); sshClient.authenticate(); log.info("Executing SSH Soft Fencing command on host '{}'", getVds().getHostName()); sshClient.executeCommand( Config.<String> getValue(ConfigValues.SshSoftFencingCommand, version), null, cmdOut, cmdErr ); ret = true; } catch (Exception ex) { log.error("SSH Soft Fencing command failed on host '{}': {}\nStdout: {}\nStderr: {}", getVds().getHostName(), ex.getMessage(), cmdOut.toString(), cmdErr.toString()); log.debug("Exception", ex); } } catch(IOException e) { log.error("IOException", e); } return ret; }

Target:
private boolean executeSshSoftFencingCommand(String version) { boolean ret = false; try ( final EngineSSHClient sshClient = new EngineSSHClient(); final ByteArrayOutputStream cmdOut = new ByteArrayOutputStream(); final ByteArrayOutputStream cmdErr = new ByteArrayOutputStream(); ) { try { log.info("Opening SSH Soft Fencing session on host '{}'", getVds().getHostName()); sshClient.setVds(getVds()); sshClient.useDefaultKeyPair(); sshClient.connect(); sshClient.authenticate(); log.info("Executing SSH Soft Fencing command on host '{}'", getVds().getHostName()); sshClient.executeCommand( Config.<String> getValue(ConfigValues.SshSoftFencingCommand, version), null, cmdOut, cmdErr ); ret = true; } catch (Exception ex) { log.error("SSH Soft Fencing command failed on host '{}': {}\nStdout: {}\nStderr: {}", getVds().getHostName(), ex.getMessage(), cmdOut, cmdErr); log.debug("Exception", ex); } } catch(IOException e) { log.error("IOException", e); } return ret; }
Source:
public void startBackgroundTasks() { scheduler.schedule(paCompletePeopleUpdater().withName("PA Complete People Updater"), PEOPLE_COMPLETE_INGEST); scheduler.schedule(paDailyPeopleUpdater().withName("PA People Updater"), PEOPLE_INGEST); scheduler.schedule(paFeaturesUpdater().withName("PA Features Updater"), FEATURES_INGEST); scheduler.schedule(paFileUpdater().withName("PA File Updater"), RECENT_FILE_DOWNLOAD); scheduler.schedule(paCompleteUpdater().withName("PA Complete Updater"), COMPLETE_INGEST); scheduler.schedule(paRecentUpdater().withName("PA Recent Updater"), RECENT_FILE_INGEST); log.record(new AdapterLogEntry(Severity.INFO).withDescription("PA update scheduled task installed").withSource(PaCompleteUpdater.class)); }

Target:
public void startBackgroundTasks() { if (peopleEnabled) { scheduler.schedule(paCompletePeopleUpdater().withName("PA Complete People Updater"), PEOPLE_COMPLETE_INGEST); scheduler.schedule(paDailyPeopleUpdater().withName("PA People Updater"), PEOPLE_INGEST); } scheduler.schedule(paChannelsUpdater().withName("PA Channels Updater"), CHANNELS_INGEST); scheduler.schedule(paFeaturesUpdater().withName("PA Features Updater"), FEATURES_INGEST); scheduler.schedule(paFileUpdater().withName("PA File Updater"), RECENT_FILE_DOWNLOAD); scheduler.schedule(paCompleteUpdater().withName("PA Complete Updater"), COMPLETE_INGEST); scheduler.schedule(paRecentUpdater().withName("PA Recent Updater"), RECENT_FILE_INGEST); log.record(new AdapterLogEntry(Severity.INFO).withDescription("PA update scheduled task installed").withSource(PaCompleteUpdater.class)); }
Source:
public ValidationResult diskImagesNotExist() { List<String> disksNotExistInDbIds = new ArrayList<>(); for (Guid diskGuid : diskGuids) { if (!isDiskExists(diskGuid)) { disksNotExistInDbIds.add(diskGuid.toString()); } } if (!disksNotExistInDbIds.isEmpty()) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_DISKS_NOT_EXIST, String.format("$diskIds %s", StringUtils.join(disksNotExistInDbIds, ", "))); } return ValidationResult.VALID; }

Target:
public ValidationResult diskImagesNotExist() { List<String> disksNotExistInDbIds = diskGuids.stream() .filter(guid -> !isDiskExists(guid)) .map(Guid::toString) .collect(Collectors.toList()); if (!disksNotExistInDbIds.isEmpty()) { return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_DISKS_NOT_EXIST, String.format("$diskIds %s", StringUtils.join(disksNotExistInDbIds, ", "))); } return ValidationResult.VALID; }
Source:
public void addUserMetaData(Map<String, String> userMetaDataMap) { StringBuilder userMetadata = new StringBuilder("?SDK=Android&Version=" + SDK_VERSION); int baseLength = userMetadata.length(); if (userMetaDataMap != null) { LOGGER.warn("Keynames 'SDK' and 'Version' are reserved and will be skipped"); for (Map.Entry<String, String> metaData : userMetaDataMap.entrySet()) { if (!(metaData.getKey().equals("SDK") || metaData.getKey().equals("Version"))) { userMetadata.append("&" + metaData.getKey() + "=" + metaData.getValue()); } } } if(userMetadata.length() > 255) { LOGGER.warn("Too many characters. User metadata was truncated.", new IllegalArgumentException("Total number of characters in user metadata" + " cannot exceed " + (255 - baseLength))); this.userMetaData = userMetadata.substring(0, 255); } else { this.userMetaData = userMetadata.toString(); } }

Target:
public void addUserMetaData(Map<String, String> userMetaDataMap) { StringBuilder userMetadata = new StringBuilder("?SDK=Android&Version=" + SDK_VERSION); int baseLength = userMetadata.length(); if (userMetaDataMap != null) { for (Map.Entry<String, String> metaData : userMetaDataMap.entrySet()) { if (!(metaData.getKey().equals("SDK") || metaData.getKey().equals("Version"))) { userMetadata.append("&" + metaData.getKey() + "=" + metaData.getValue()); } else { LOGGER.warn("Keynames 'SDK' and 'Version' are reserved and will be skipped"); } } } if(userMetadata.length() > 255) { LOGGER.warn("Too many characters. User metadata was truncated.", new IllegalArgumentException("Total number of characters in user metadata" + " cannot exceed " + (255 - baseLength))); this.userMetaData = userMetadata.substring(0, 255); } else { this.userMetaData = userMetadata.toString(); } }
Source:
protected AttributesImpl cloneWithGmlId(AttributesImpl atts, String gmlId) { if (gmlId == null) { return atts; } AttributesImpl result; if (atts == null) { result = new AttributesImpl(); } else { result = new AttributesImpl(atts); } if (encodeGmlId) addGmlId(result, gmlId); return result; }

Target:
protected AttributesImpl cloneWithGmlId(AttributesImpl atts, String gmlId) { if (gmlId == null || !encodeGmlId) { return atts; } AttributesImpl result; if (atts == null) { result = new AttributesImpl(); } else { result = new AttributesImpl(atts); } addGmlId(result, gmlId); return result; }
Source:
public void clickRemoveInstructorFromCourse(String courseId) { List<WebElement> instructorRows = instructorTable.findElement(By.tagName("tbody")).findElements(By.tagName("tr")); WebElement deleteButton = null; for (WebElement instructorRow : instructorRows) { List<WebElement> cells = instructorRow.findElements(By.tagName("td")); if (cells.get(0).getText().startsWith("[" + courseId + "]")) { deleteButton = cells.get(1).findElement(By.className("btn-danger")); } } if (deleteButton == null) { fail("Instructor to be deleted is not found"); } click(deleteButton); waitForPageToLoad(true); verifyStatusMessage("Instructor is successfully deleted from course \"" + courseId + "\""); }

Target:
public void clickRemoveInstructorFromCourse(String courseId) { List<WebElement> instructorRows = instructorTable.findElement(By.tagName("tbody")).findElements(By.tagName("tr")); WebElement deleteButton = null; for (WebElement instructorRow : instructorRows) { List<WebElement> cells = instructorRow.findElements(By.tagName("td")); if (cells.get(0).getText().startsWith("[" + courseId + "]")) { deleteButton = cells.get(1).findElement(By.className("btn-danger")); } } if (deleteButton == null) { fail("Instructor to be deleted is not found"); } click(deleteButton); waitForPageToLoad(true); }
Source:
public HttpRequests(HttpParams params, String username, String password, Map<String, String> customHeaders){ this.jsonHelper = new JSONHelper(); this.context = new BasicHttpContext(); HttpProtocolParams.setUserAgent(params, this.getUserAgent()); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRoute() { @Override public int getMaxForRoute(HttpRoute route) { return CONN_PER_ROUT; } }); ClientConnectionManager manager = getClientConnectionManager(params); DefaultHttpClient httpClient = new DefaultHttpClient(manager,params); addDebuggingInterceptor(httpClient); this.httpClient = httpClient; String authHeaderValue = null; if (!Strings.isNullOrEmpty(username) && !Strings.isNullOrEmpty(password)) { String authString = username + ":" + password; Base64 base64 = new Base64(); authHeaderValue = "Basic " + new String(base64.encode(authString.getBytes())); } if (customHeaders != null) { this.requestHeaders = customHeaders; if (customHeaders.containsKey("authorization")) { if (authHeaderValue != null) { logger.warning("custom header \"authorization\" and username/password are both set; will use the value from custom header"); } } else { if (authHeaderValue != null) { this.requestHeaders = new HashMap<String, String>(); customHeaders.putAll(customHeaders); customHeaders.put("authorization", authHeaderValue); } } } }

Target:
public HttpRequests(HttpParams params, String username, String password, Map<String, String> customHeaders){ this.jsonHelper = new JSONHelper(); this.context = new BasicHttpContext(); HttpProtocolParams.setUserAgent(params, this.getUserAgent()); ConnManagerParams.setMaxConnectionsPerRoute(params, new ConnPerRoute() { @Override public int getMaxForRoute(HttpRoute route) { return CONN_PER_ROUT; } }); ClientConnectionManager manager = getClientConnectionManager(params); DefaultHttpClient httpClient = new DefaultHttpClient(manager,params); addDebuggingInterceptor(httpClient); this.httpClient = httpClient; String authHeaderValue = null; if (!Strings.isNullOrEmpty(username) && !Strings.isNullOrEmpty(password)) { String authString = username + ":" + password; Base64 base64 = new Base64(); authHeaderValue = "Basic " + new String(base64.encode(authString.getBytes())); } this.requestHeaders = new HashMap<String, String>(); if (customHeaders != null) { for (Map.Entry<String, String> header : customHeaders.entrySet()) { this.requestHeaders.put(header.getKey().toLowerCase(), header.getValue()); } } if (authHeaderValue != null) { if (this.requestHeaders.containsKey("authorization")) { logger.warning( "custom header \"authorization\" and username/password are both set; will use the value from custom header" ); } else { this.requestHeaders.put("authorization", authHeaderValue); } } }
Source:
public void configure(RuntimeHarness harness, File workingDir) throws IOException, URISyntaxException { File dest = new File(workingDir, "web/root.war/WEB-INF/"); dest.mkdirs(); dest = new File(workingDir + "/web/root.war/WEB-INF/", "web.xml"); try (InputStream in = getResource("test-web.xml").openStream()) { FileUtils.copyInputStreamToFile(in, dest); } try (InputStream in = getResource("test-oauth2Grant.jsp").openStream()) { FileUtils.copyInputStreamToFile(in, new File(workingDir, "web/root.war/oauth2Grant.jsp")); } }

Target:
public void configure(RuntimeHarness harness, File workingDir) throws IOException, URISyntaxException { File webInf = new File(workingDir, "web/root.war/WEB-INF/"); if (!webInf.mkdirs()) { throw new IOException(String.format("Unable to create %s directory", webInf.getAbsolutePath())); } Files.copy(Paths.get(getResource("test-web.xml").toURI()), webInf.toPath().resolve("web.xml")); Files.copy(Paths.get(getResource("test-oauth2Grant.jsp").toURI()), workingDir.toPath().resolve("web/root.war/oauth2Grant.jsp")); }
Source:
public synchronized void executeDiagnoserIncr(String diagnoser) { executeDiagnoserCount.scope(diagnoser); }

Target:
public synchronized void executeDiagnoserIncr(String diagnoser) { executeDiagnoserCount.scope(diagnoser).incr(); }
Source:
final void writeRawValue(Object value) { ByteString byteString = (ByteString) value; Binary binary = Binary.fromUnmodifiedByteArray(byteString.toByteArray()); recordConsumer.addBinary(binary); }

Target:
final void writeRawValue(Object value) { ByteString byteString = (ByteString) value; Binary binary = Binary.fromConstantByteArray(byteString.toByteArray()); recordConsumer.addBinary(binary); }
Source:
public void setup(){ broker = new EmbeddedActiveMQBroker(); broker.start(); flowTestRule.withFlow((Flow) moduleUnderTest.getFlow("Jms Flow")); }

Target:
public void setup() { flowTestRule.withFlow(moduleUnderTest.getFlow("Jms Flow")); }
Source:
private void revertPreviousHandlers() { getParameters().decrementExecutionIndex(); if (canRevertTasks()) { logRollbackedTask(); getParameters().setExecutionReason(CommandExecutionReason.ROLLBACK_FLOW); getCurrentTaskHandler().compensate(); if (!hasRevertTask()) { revertPreviousHandlers(); } } else { setSucceeded(true); } }

Target:
private void revertPreviousHandlers() { getParameters().decrementExecutionIndex(); if (hasStepsToRevert()) { logRollbackedTask(); getParameters().setExecutionReason(CommandExecutionReason.ROLLBACK_FLOW); getCurrentTaskHandler().compensate(); if (!hasRevertTask()) { revertPreviousHandlers(); } } else { setSucceeded(true); } }
Source:
public void registerLayers(MapActivity activity) { if(parkingLayer != null) { activity.getMapView().removeLayer(parkingLayer); } parkingLayer = new ParkingPositionLayer(activity, this); registerWidget(activity); }

Target:
public void registerLayers(MapActivity activity) { registerWidget(activity); }
Source:
void load(File file) throws IOException { long start = Time.monotonicNow(); FSImageFormatProtobuf.Loader.DigestThread dt = new FSImageFormatProtobuf.Loader.DigestThread(file); dt.start(); RandomAccessFile raFile = new RandomAccessFile(file, "r"); FileInputStream fin = new FileInputStream(file); try { loadInternal(raFile, fin); try { dt.join(); imgDigest = dt.getDigest(); if (dt.getException() != null) { throw dt.getException(); } } catch (InterruptedException ie) { throw new IOException(ie); } long end = Time.monotonicNow(); LOG.info("Loaded FSImage in seconds.", (end - start) / 1000); } finally { fin.close(); raFile.close(); } }

Target:
void load(File file) throws IOException { long start = Time.monotonicNow(); DigestThread dt = new DigestThread(file); dt.start(); RandomAccessFile raFile = new RandomAccessFile(file, "r"); FileInputStream fin = new FileInputStream(file); try { loadInternal(raFile, fin); try { dt.join(); imgDigest = dt.getDigest(); } catch (InterruptedException ie) { throw new IOException(ie); } long end = Time.monotonicNow(); LOG.info("Loaded FSImage in seconds.", (end - start) / 1000); } finally { fin.close(); raFile.close(); } }
Source:
protected String getDescriptivePayeeTypesAsString(Collection<String> payeeTypeCodes) { List<String> payeeTypeDescriptions = new ArrayList<>(); for (String payeeTypeCode : payeeTypeCodes) { String description = disbursementVoucherPayeeService.getPayeeTypeDescription(payeeTypeCode); if (payeeTypeDescriptions.indexOf(description) == -1) { payeeTypeDescriptions.add(description); } } return this.convertListToString(payeeTypeDescriptions); }

Target:
protected String getDescriptivePayeeTypesAsString(Collection<String> payeeTypeCodes) { List<String> payeeTypeDescriptions = new ArrayList<>(); for (String payeeTypeCode : payeeTypeCodes) { String description = disbursementVoucherPayeeService.getPayeeTypeDescription(payeeTypeCode); if (payeeTypeDescriptions.indexOf(description) == -1) { payeeTypeDescriptions.add(description); } } return convertListToString(payeeTypeDescriptions); }
Source:
public String getViewSql(String tableName, String schemaName) { return "SELECT DISTINCT COLUMN_FAMILY, TENANT_ID FROM " + "SYSTEM.CHILD_LINK " + "WHERE TABLE_NAME = \'" + tableName + "\' " + (!StringUtil.EMPTY_STRING.equals(schemaName) ? "AND TABLE_SCHEM = \'" + schemaName + "\' " : "") + "AND LINK_TYPE = " + PTable.LinkType.CHILD_TABLE.getSerializedValue(); }

Target:
public String getViewSql(String tableName, String schemaName) { return "SELECT DISTINCT COLUMN_FAMILY, TENANT_ID FROM " + "SYSTEM.CHILD_LINK " + "WHERE TABLE_NAME = \'" + tableName + "\'" + (!Strings.isNullOrEmpty(schemaName) ? " AND TABLE_SCHEM = \'" + schemaName + "\'" : "") + " AND LINK_TYPE = " + PTable.LinkType.CHILD_TABLE.getSerializedValue(); }
Source:
public Result<K, T> execute(Query<K, T> query) throws GoraException { String[] avFields = getFieldsToQuery(query.getFields()); List<String> dbFields = new ArrayList<>(); for (String af : avFields) { dbFields.add(kuduMapping.getFields().get(af).getName()); } try { ColumnSchema column = table.getSchema().getColumn(kuduMapping.getPrimaryKey().get(0).getName()); dbFields.add(kuduMapping.getPrimaryKey().get(0).getName()); KuduScanner.KuduScannerBuilder scannerBuilder = client.newScannerBuilder(table); if (query.getLimit() != -1) { scannerBuilder.limit(query.getLimit()); } scannerBuilder.setProjectedColumnNames(dbFields); List<KuduPredicate> rangePredicates = KuduClientUtils.createRangePredicate(column, query.getStartKey(), query.getEndKey()); for (KuduPredicate predicate : rangePredicates) { scannerBuilder.addPredicate(predicate); } scannerBuilder.addPredicate(KuduPredicate.newIsNotNullPredicate(column)); KuduScanner build = scannerBuilder.build(); KuduResult<K, T> kuduResult = new KuduResult<>(this, query, build); return kuduResult; } catch (Exception e) { throw new GoraException(e); } }

Target:
public Result<K, T> execute(Query<K, T> query) throws GoraException { String[] avFields = getFieldsToQuery(query.getFields()); List<String> dbFields = new ArrayList<>(); for (String af : avFields) { dbFields.add(kuduMapping.getFields().get(af).getName()); } try { ColumnSchema column = table.getSchema().getColumn(kuduMapping.getPrimaryKey().get(0).getName()); dbFields.add(kuduMapping.getPrimaryKey().get(0).getName()); List<KuduPredicate> rangePredicates = KuduClientUtils.createRangePredicate(column, query.getStartKey(), query.getEndKey()); rangePredicates.add(KuduPredicate.newIsNotNullPredicate(column)); KuduScanner build = createScanner(rangePredicates, dbFields, query.getLimit()); return new KuduResult<>(this, query, build); } catch (Exception e) { throw new GoraException(e); } }
Source:
private static String getContent(String location) throws IOException { return IOUtils.toString(ClassPathBasedPatentServiceFacade.class.getResourceAsStream(location), "utf8"); }

Target:
private static String getContent(String location) throws IOException { return IOUtils.toString(ClassPathBasedPatentServiceFacade.class.getResourceAsStream(location), StandardCharsets.UTF_8); }
Source:
private IllegalStateException methodInvocationReturnedNull(Object[] args) { return new IllegalStateException( "method invocation returned null: " + getName() + Tuple.copyOf(Arrays.asList(args))); }

Target:
private NullPointerException methodInvocationReturnedNull(Object[] args) { return new NullPointerException( "method invocation returned null: " + getName() + Tuple.of(args)); }
Source:
public static void main(String[] args) { if (args.length != 1) { System.err .println("usage: java edu.illinois.cs.cogcomp.lbj.pos.POSTagPlain <text file>"); System.exit(1); } String testingFile = args[0]; POSTagger tagger = new POSTagger(); Parser parser = new PlainToTokenParser(new WordSplitter(new SentenceSplitter(testingFile))); String sentence = ""; for (Token word = (Token) parser.next(); word != null; word = (Token) parser.next()) { String tag = tagger.discreteValue(word); sentence += " (" + tag + " " + word.form + ")"; if (word.next == null) { logger.info(sentence.substring(1)); sentence = ""; } } }

Target:
public static void main(String[] args) { if (args.length != 1) { System.err .println("usage: java edu.illinois.cs.cogcomp.lbj.pos.POSTagPlain <text file>"); System.exit(1); } String testingFile = args[0]; POSTagger tagger = new POSTagger(); Parser parser = new PlainToTokenParser(new WordSplitter(new SentenceSplitter(testingFile))); String sentence = ""; for (Token word = (Token) parser.next(); word != null; word = (Token) parser.next()) { String tag = tagger.discreteValue(word); sentence += " (" + tag + " " + word.form + ")"; if (word.next == null) { System.out.println(sentence.substring(1)); sentence = ""; } } }
Source:
public void aFirmware(final Map<String, String> settings) { DeviceModel deviceModel = this.deviceModelRepo .findByModelCode(getString(settings, PlatformKeys.DEVICEMODEL_MODELCODE)); if (deviceModel == null) { deviceModel = this.deviceModelSteps.aDeviceModel(settings); } String comm = getString(settings, PlatformKeys.FIRMWARE_MODULE_VERSION_COMM, PlatformDefaults.FIRMWARE_MODULE_VERSION_COMM); comm = (comm.equals("")) ? null : comm; String func = getString(settings, PlatformKeys.FIRMWARE_MODULE_VERSION_FUNC, PlatformDefaults.FIRMWARE_MODULE_VERSION_FUNC); func = (func.equals("")) ? null : func; String ma = getString(settings, PlatformKeys.FIRMWARE_MODULE_VERSION_MA, PlatformDefaults.FIRMWARE_MODULE_VERSION_MA); ma = (ma.equals("")) ? null : ma; String mbus = getString(settings, PlatformKeys.FIRMWARE_MODULE_VERSION_MBUS, PlatformDefaults.FIRMWARE_MODULE_VERSION_MBUS); mbus = (mbus.equals("")) ? null : mbus; String sec = getString(settings, PlatformKeys.FIRMWARE_MODULE_VERSION_SEC, PlatformDefaults.FIRMWARE_MODULE_VERSION_SEC); sec = (sec.equals("")) ? null : sec; final FirmwareModuleData firmwareModuleData = new FirmwareModuleData(comm, func, ma, mbus, sec); final Firmware entity = new Firmware(deviceModel, getString(settings, PlatformKeys.FIRMWARE_FILENAME, ""), getString(settings, PlatformKeys.FIRMWARE_DESCRIPTION, PlatformDefaults.FIRMWARE_DESCRIPTION), getBoolean(settings, PlatformKeys.FIRMWARE_PUSH_TO_NEW_DEVICES, PlatformDefaults.FIRMWARE_PUSH_TO_NEW_DEVICE), firmwareModuleData); this.firmwareRepo.save(entity); }

Target:
public void aFirmware(final Map<String, String> settings) { DeviceModel deviceModel = this.deviceModelRepo .findByModelCode(getString(settings, PlatformKeys.DEVICEMODEL_MODELCODE)); if (deviceModel == null) { deviceModel = this.deviceModelSteps.aDeviceModel(settings); } final String comm = getNullOrNonEmptyString(settings, PlatformKeys.FIRMWARE_MODULE_VERSION_COMM, PlatformDefaults.FIRMWARE_MODULE_VERSION_COMM); final String func = getNullOrNonEmptyString(settings, PlatformKeys.FIRMWARE_MODULE_VERSION_FUNC, PlatformDefaults.FIRMWARE_MODULE_VERSION_FUNC); final String ma = getNullOrNonEmptyString(settings, PlatformKeys.FIRMWARE_MODULE_VERSION_MA, PlatformDefaults.FIRMWARE_MODULE_VERSION_MA); final String mbus = getNullOrNonEmptyString(settings, PlatformKeys.FIRMWARE_MODULE_VERSION_MBUS, PlatformDefaults.FIRMWARE_MODULE_VERSION_MBUS); final String sec = getNullOrNonEmptyString(settings, PlatformKeys.FIRMWARE_MODULE_VERSION_SEC, PlatformDefaults.FIRMWARE_MODULE_VERSION_SEC); final FirmwareModuleData firmwareModuleData = new FirmwareModuleData(comm, func, ma, mbus, sec); final Firmware entity = new Firmware(deviceModel, getString(settings, PlatformKeys.FIRMWARE_FILENAME, ""), getString(settings, PlatformKeys.FIRMWARE_DESCRIPTION, PlatformDefaults.FIRMWARE_DESCRIPTION), getBoolean(settings, PlatformKeys.FIRMWARE_PUSH_TO_NEW_DEVICES, PlatformDefaults.FIRMWARE_PUSH_TO_NEW_DEVICE), firmwareModuleData); this.firmwareRepo.save(entity); }
Source:
protected abstract void serializeOperatorState(OperatorState operatorState, DataOutputStream dos) throws IOException; protected abstract OperatorState deserializeOperatorState(DataInputStream dis) throws IOException; protected void serializeSubtaskState(OperatorSubtaskState subtaskState, DataOutputStream dos) throws IOException { serializeSingleton(subtaskState.getManagedOperatorState(), dos, MetadataV2V3SerializerBase::serializeOperatorStateHandle); serializeSingleton(subtaskState.getRawOperatorState(), dos, MetadataV2V3SerializerBase::serializeOperatorStateHandle); serializeKeyedStateCol(subtaskState.getManagedKeyedState(), dos); serializeKeyedStateCol(subtaskState.getRawKeyedState(), dos); serializeCollection(subtaskState.getInputChannelState(), dos, this::serializeInputChannelStateHandle); serializeCollection(subtaskState.getResultSubpartitionState(), dos, this::serializeResultSubpartitionStateHandle); }

Target:
protected abstract void serializeOperatorState(OperatorState operatorState, DataOutputStream dos) throws IOException; protected abstract OperatorState deserializeOperatorState(DataInputStream dis) throws IOException; protected void serializeSubtaskState(OperatorSubtaskState subtaskState, DataOutputStream dos) throws IOException { serializeSingleton(subtaskState.getManagedOperatorState(), dos, MetadataV2V3SerializerBase::serializeOperatorStateHandle); serializeSingleton(subtaskState.getRawOperatorState(), dos, MetadataV2V3SerializerBase::serializeOperatorStateHandle); serializeKeyedStateCol(subtaskState.getManagedKeyedState(), dos); serializeKeyedStateCol(subtaskState.getRawKeyedState(), dos); }
Source:
public ApacheClient(HttpClient client) { this.client = client; ProxyRedirectHandler proxyRedirectHandler = null; if (client instanceof DefaultHttpClient) { DefaultHttpClient defaultHttpClient = (DefaultHttpClient) client; proxyRedirectHandler = new ProxyRedirectHandler(defaultHttpClient.getRedirectHandler()); defaultHttpClient.setRedirectHandler(proxyRedirectHandler); } redirectHandler = proxyRedirectHandler; }

Target:
public ApacheClient(HttpClient client) { this.client = client; ProxyRedirectHandler proxyRedirectHandler = null; if (client instanceof AbstractHttpClient) { AbstractHttpClient defaultHttpClient = (AbstractHttpClient) client; proxyRedirectHandler = new ProxyRedirectHandler(defaultHttpClient.getRedirectHandler()); defaultHttpClient.setRedirectHandler(proxyRedirectHandler); } redirectHandler = proxyRedirectHandler; }
Source:
private static Map<String, TumorType> getUnmodifiableTumorTypesByVersion(Map<String, TumorType> tumorTypeMap) { Map<String, TumorType> unmodifiableTumorTypeMap = new HashMap<String, TumorType>(tumorTypeMap.size()); for (Map.Entry<String, TumorType> entry : tumorTypeMap.entrySet()) { unmodifiableTumorTypeMap.put(entry.getKey(), new TumorType(entry.getValue())); } return Collections.unmodifiableMap(unmodifiableTumorTypeMap); }

Target:
private static Map<String, TumorType> getUnmodifiableTumorTypesByVersion(Map<String, TumorType> tumorTypeMap) { Map<String, TumorType> unmodifiableTumorTypeMap = new HashMap<String, TumorType>(tumorTypeMap.size()); for (Map.Entry<String, TumorType> entry : tumorTypeMap.entrySet()) { unmodifiableTumorTypeMap.put(entry.getKey(), entry.getValue().deepCopy()); } return Collections.unmodifiableMap(unmodifiableTumorTypeMap); }
Source:
public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException, DataAccessException { UserDetails userDetails = userDetailsService.loadUserByUsername(userId); return (SocialUserDetails) userDetails; }

Target:
public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException, DataAccessException { return (SocialUserDetails) userDetailsService.loadUserByUsername(userId); }
Source:
private static boolean parentUseValue(Tree child) { Tree parent = child.getParent(); if (parent == null) { return false; } if (parent.is(Tree.Kind.PARENTHESISED_EXPRESSION, Tree.Kind.ERROR_CONTROL)) { return parentUseValue(parent); } else if (parent.is(Tree.Kind.EXPRESSION_STATEMENT)) { return false; } else if (parent.is(Tree.Kind.FOR_STATEMENT)) { SeparatedList<ExpressionTree> conditions = ((ForStatementTree) parent).condition(); ExpressionTree lastCondition = conditions.isEmpty() ? null : conditions.get(conditions.size() - 1); return child.equals(lastCondition); } return true; }

Target:
private static boolean parentUseValue(Tree child) { Tree parent = child.getParent(); Preconditions.checkNotNull(parent); if (parent.is(Tree.Kind.PARENTHESISED_EXPRESSION, Tree.Kind.ERROR_CONTROL)) { return parentUseValue(parent); } else if (parent.is(Tree.Kind.EXPRESSION_STATEMENT)) { return false; } else if (parent.is(Tree.Kind.FOR_STATEMENT)) { SeparatedList<ExpressionTree> conditions = ((ForStatementTree) parent).condition(); ExpressionTree lastCondition = conditions.isEmpty() ? null : conditions.get(conditions.size() - 1); return child.equals(lastCondition); } return true; }
Source:
protected final void layoutChildren() { double width = rectangle.getWidth(); double height = rectangle.getHeight(); double fontWidth = text.getLayoutBounds().getWidth(); text.setFont(Font.font(FONTNAME, (HORIZONTALSCALE) * width / fontWidth)); text.setLayoutX(width / 2 - text.getLayoutBounds().getWidth() / 2); text.setLayoutY(height / 2); if ((HORIZONTALSCALE * width / fontWidth) < MINTEXTSIZE) { text.setVisible(false); } else { text.setVisible(true); } clip.setWidth(width); clip.setHeight(height); clip.setLayoutX(0); clip.setLayoutY(-height / 2); }

Target:
protected final void layoutChildren() { double width = rectangle.getWidth(); double height = rectangle.getHeight(); double fontWidth = text.getLayoutBounds().getWidth(); text.setFont(Font.font(FONTNAME, (HORIZONTALSCALE) * width / fontWidth)); text.setLayoutX(width / 2 - text.getLayoutBounds().getWidth() / 2); text.setLayoutY(height / 2); text.setVisible(HORIZONTALSCALE * width / fontWidth >= MINTEXTSIZE); clip.setWidth(width); clip.setHeight(height); clip.setLayoutX(0); clip.setLayoutY(-height / 2); }
Source:
private void authorise3DSSource(ChargeEntity charge, String notificationEventType) { try { final StripeNotificationType type = StripeNotificationType.byType(notificationEventType); if (AUTHORISATION_3DS_REQUIRED.equals(ChargeStatus.fromString(charge.getStatus()))) { updateChargeStatus(charge, AUTHORISATION_3DS_READY); } Auth3dsDetails auth3dsDetails = new Auth3dsDetails(); auth3dsDetails.setAuth3dsResult(getMappedAuth3dsResult(type)); card3dsResponseAuthService.process3DSecureAuthorisationWithoutLocking(charge.getExternalId(), auth3dsDetails); } catch (OperationAlreadyInProgressRuntimeException e) { } }

Target:
private void authorise3DSSource(ChargeEntity charge, String notificationEventType) { try { final StripeNotificationType type = StripeNotificationType.byType(notificationEventType); if (AUTHORISATION_3DS_REQUIRED.equals(ChargeStatus.fromString(charge.getStatus()))) { logger.info("Updating charge for notification - " + "charge_external_id={}, status={}, status_to={}, transaction_id={}, " + "account_id={}, provider={}, provider_type={}", charge.getExternalId(), charge.getStatus(), charge.getStatus(), charge.getGatewayTransactionId(), charge.getGatewayAccount().getId(), charge.getGatewayAccount().getGatewayName(), charge.getGatewayAccount().getType()); chargeService.lockChargeForProcessing(charge.getExternalId(), AUTHORISATION_3DS); } Auth3dsDetails auth3dsDetails = new Auth3dsDetails(); auth3dsDetails.setAuth3dsResult(getMappedAuth3dsResult(type)); card3dsResponseAuthService.process3DSecureAuthorisationWithoutLocking(charge.getExternalId(), auth3dsDetails); } catch (OperationAlreadyInProgressRuntimeException e) { } }
Source:
private int bagSizePower() throws IOException { int avgObjectSize = (int) (valuesOut.getCount() / numWritten); File f = ioPeon.getFile(makeFilename("headerLong")); Preconditions.checkNotNull(f, "header file missing."); try (RandomAccessFile headerFile = new RandomAccessFile(f, "r")) { for (int i = 31; i >= 0; --i) { if ((1L << i) * avgObjectSize <= fileSizeLimit) { if (actuallyFits(i, headerFile)) { return i; } } } } throw new ISE( "no value split found with fileSizeLimit [%d], avgObjectSize [%d] while serializing [%s]", fileSizeLimit, avgObjectSize, filenameBase ); }

Target:
private int bagSizePower() throws IOException { long avgObjectSize = (valuesOut.getCount() + numWritten - 1) / numWritten; File f = ioPeon.getFile(makeFilename("headerLong")); Preconditions.checkNotNull(f, "header file missing."); try (RandomAccessFile headerFile = new RandomAccessFile(f, "r")) { for (int i = 31; i >= 0; --i) { if ((1L << i) * avgObjectSize <= fileSizeLimit) { if (actuallyFits(i, headerFile)) { return i; } } } } throw new ISE( "no value split found with fileSizeLimit [%d], avgObjectSize [%d] while serializing [%s]", fileSizeLimit, avgObjectSize, filenameBase ); }
Source:
public void testSetscopedInstance_rootWithTargetChild() throws InterruptedException { AgentMessageProcessor processor = (AgentMessageProcessor) this.agent.getMessagingClient().getMessageProcessor(); TestApplicationTemplate app = new TestApplicationTemplate(); app.getTomcat().getComponent().installerName( Constants.TARGET_INSTALLER ); Assert.assertNull( processor.scopedInstance ); processor.processMessage( new MsgCmdSetScopedInstance( app.getTomcatVm())); Assert.assertEquals( app.getTomcatVm(), processor.scopedInstance ); Assert.assertEquals( InstanceStatus.DEPLOYED_STARTED, processor.scopedInstance.getStatus()); Assert.assertEquals( "Expected a message for the Tomcat VM (children were removed).", 0, this.client.messagesForAgents.size()); Assert.assertEquals( 1, InstanceHelpers.buildHierarchicalList( app.getTomcatVm()).size()); }

Target:
public void testSetscopedInstance_rootWithTargetChild() { AgentMessageProcessor processor = (AgentMessageProcessor) this.agent.getMessagingClient().getMessageProcessor(); TestApplicationTemplate app = new TestApplicationTemplate(); app.getTomcat().getComponent().installerName( Constants.TARGET_INSTALLER ); Assert.assertNull( processor.scopedInstance ); processor.processMessage( new MsgCmdSetScopedInstance( app.getTomcatVm())); Assert.assertEquals( app.getTomcatVm(), processor.scopedInstance ); Assert.assertEquals( InstanceStatus.DEPLOYED_STARTED, processor.scopedInstance.getStatus()); Assert.assertEquals( "Expected a message for the Tomcat VM (children were removed).", 0, this.client.messagesForAgents.size()); Assert.assertEquals( 1, InstanceHelpers.buildHierarchicalList( app.getTomcatVm()).size()); }
Source:
public ResponseEntity updateSampleListFolderName(@PathVariable final String crop, @RequestParam final String newFolderName, @PathVariable final Integer folderId) { Map<String, Object> map; try { map = this.sampleListService.updateSampleListFolderName(folderId, newFolderName); } catch (final MiddlewareException e) { final ErrorResponse response = new ErrorResponse(); response.addError("Something went wrong, please try again"); return new ResponseEntity<>(response, HttpStatus.CONFLICT); } return new ResponseEntity<>(map, HttpStatus.OK); }

Target:
public ResponseEntity updateSampleListFolderName(@PathVariable final String crop, @RequestParam final String newFolderName, @PathVariable final Integer folderId) { final Map<String, Object> map; try { map = this.sampleListService.updateSampleListFolderName(folderId, newFolderName); } catch (final MiddlewareException e) { final ErrorResponse response = new ErrorResponse(); response.addError("Something went wrong, please try again"); return new ResponseEntity<>(response, HttpStatus.CONFLICT); } return new ResponseEntity<>(map, HttpStatus.OK); }