auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testLogS3GuardDisabled() throws Exception { <START> final Logger localLogger = LoggerFactory.getLogger( <END> TestS3Guard.class.toString() + UUID.randomUUID()); S3Guard.logS3GuardDisabled(localLogger, S3Guard.DisabledWarnLevel.SILENT.toString(), "bucket"); S3Guard.logS3GuardDisabled(localLogger, S3Guard.DisabledWarnLevel.INFORM.toString(), "bucket"); S3Guard.logS3GuardDisabled(localLogger, S3Guard.DisabledWarnLevel.WARN.toString(), "bucket"); LambdaTestUtils.intercept(UnsupportedOperationException.class, S3Guard.DISABLED_LOG_MSG, () -> S3Guard.logS3GuardDisabled( localLogger, S3Guard.DisabledWarnLevel.FAIL.toString(), "bucket")); LambdaTestUtils.intercept(IllegalArgumentException.class, S3Guard.UNKNOWN_WARN_LEVEL, () -> S3Guard.logS3GuardDisabled( localLogger, "FOO_BAR_LEVEL", "bucket")); }</code><technical_language>Verify case in sensitivity; "inform" work</technical_language>

Target:
public void testLogS3GuardDisabled() throws Exception { final Logger localLogger = LoggerFactory.getLogger( TestS3Guard.class.toString() + UUID.randomUUID()); S3Guard.logS3GuardDisabled(localLogger, S3Guard.DisabledWarnLevel.SILENT.toString(), "bucket"); S3Guard.logS3GuardDisabled(localLogger, S3Guard.DisabledWarnLevel.INFORM.toString(), "bucket"); S3Guard.logS3GuardDisabled(localLogger, S3Guard.DisabledWarnLevel.WARN.toString(), "bucket"); S3Guard.logS3GuardDisabled(localLogger, S3Guard.DisabledWarnLevel.WARN.toString() .toLowerCase(Locale.US), "bucket"); LambdaTestUtils.intercept(UnsupportedOperationException.class, S3Guard.DISABLED_LOG_MSG, () -> S3Guard.logS3GuardDisabled( localLogger, S3Guard.DisabledWarnLevel.FAIL.toString(), "bucket")); LambdaTestUtils.intercept(IllegalArgumentException.class, S3Guard.UNKNOWN_WARN_LEVEL, () -> S3Guard.logS3GuardDisabled( localLogger, "FOO_BAR_LEVEL", "bucket")); }
Source:
<code>static long calculateContentLength(final long plaintextSize, final int blockBytes, final int tagOrHmacBytes, final boolean hasIV) { if (plaintextSize <= 0) { return (long)blockBytes + tagOrHmacBytes; } long calculatedContentLength = plaintextSize; long padding = 0L; if (plaintextSize > blockBytes) { padding = plaintextSize % blockBytes; } else { calculatedContentLength = blockBytes; } if (padding > 0) { calculatedContentLength = (plaintextSize - padding) + blockBytes; } if (!hasIV && plaintextSize >= blockBytes) { <START> final long blocks = Math.floorDiv(plaintextSize, ((long) blockBytes)); <END> calculatedContentLength = ((blocks + 1) * blockBytes); } calculatedContentLength += tagOrHmacBytes; return calculatedContentLength; }</code><technical_language>this a separate PR commit. This is type of change want highly visible</technical_language>

Target:
static long calculateContentLength(final long plaintextSize, final int blockBytes, final int tagOrHmacBytes, final boolean hasIV) { if (plaintextSize <= 0) { return (long)blockBytes + tagOrHmacBytes; } long calculatedContentLength = plaintextSize; long padding = 0L; if (plaintextSize > blockBytes) { padding = plaintextSize % blockBytes; } else { calculatedContentLength = blockBytes; } if (padding > 0) { calculatedContentLength = (plaintextSize - padding) + blockBytes; } if (!hasIV && plaintextSize >= blockBytes) { final double blocks = Math.floor(plaintextSize / ((long) blockBytes)); calculatedContentLength = (((long)blocks + 1) * blockBytes); } calculatedContentLength += tagOrHmacBytes; return calculatedContentLength; }
Source:
<code>public Ds3Client newForNode(final JobNode node) { final ConnectionDetails newConnectionDetails; try { newConnectionDetails = ((NetworkClient)getNetClientMethod.invoke(this)).getConnectionDetails(); final NetworkClient newNetClient = new NetworkClientImpl(newConnectionDetails); return new Ds3ClientShim(newNetClient); <START> } catch (IllegalAccessException | InvocationTargetException e) { <END> fail("Failure trying to create Ds3Client used in verifying putObject retries: " + e.getMessage()); } return null; }</code><technical_language>Missing final</technical_language>

Target:
public Ds3Client newForNode(final JobNode node) { final ConnectionDetails newConnectionDetails; try { newConnectionDetails = ((NetworkClient)getNetClientMethod.invoke(this)).getConnectionDetails(); final NetworkClient newNetClient = new NetworkClientImpl(newConnectionDetails); return new Ds3ClientShim(newNetClient); } catch (final IllegalAccessException | InvocationTargetException e) { fail("Failure trying to create Ds3Client used in verifying putObject retries: " + e.getMessage()); } return null; }
Source:
<code>public boolean filterOut(final SAMRecord first, final SAMRecord second) { <START> throw new UnsupportedOperationException("IntervalKeepPairFilter(record) keeps both of a pair if either passes the filter."); <END> }</code><technical_language>implement this</technical_language>

Target:
public boolean filterOut(final SAMRecord first, final SAMRecord second) { return filterOut(first) && filterOut(second); }
Source:
<code>private void initializeItem(Item item) throws IllegalArgumentException { <START> if (ItemUtil.isValidItemName(item.getName())) { <END> if (item instanceof GenericItem) { GenericItem genericItem = (GenericItem) item; genericItem.setEventPublisher(eventPublisher); genericItem.setStateDescriptionProviders(stateDescriptionProviders); genericItem.initialize(); } if (item instanceof GroupItem) { addMembersToGroupItem((GroupItem) item); } addToGroupItems(item, item.getGroupNames()); } else { throw new IllegalArgumentException( "Ignoring item '" + item.getName() + "' as it does not comply with" + " the naming convention."); } }</code><technical_language>assert, else branch throws IAE</technical_language>

Target:
private void initializeItem(Item item) throws IllegalArgumentException { ItemUtil.assertValidItemName(item.getName()); if (item instanceof GenericItem) { GenericItem genericItem = (GenericItem) item; genericItem.setEventPublisher(eventPublisher); genericItem.setStateDescriptionProviders(stateDescriptionProviders); genericItem.initialize(); } if (item instanceof GroupItem) { addMembersToGroupItem((GroupItem) item); } addToGroupItems(item, item.getGroupNames()); }
Source:
<code><START> static Long getXid(InstanceConfig instanceConfig) { <END> String xid = instanceConfig.getRecord().getSimpleField(XID_STR); return xid == null ? Long.MIN_VALUE : Long.valueOf(xid); }</code><technical_language>minor: some of variables this long some Long. I long good everywhere? (since this null)</technical_language>

Target:
static long getXid(InstanceConfig instanceConfig) { String xid = instanceConfig.getRecord().getSimpleField(XID_STR); return xid == null ? Long.MIN_VALUE : Long.valueOf(xid); }
Source:
<code>public void testGdbSyncServiceCanSwitchGDBStackFrame() throws Throwable { ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<MIStoppedEvent>(fMultiRunControl.getSession(), MIStoppedEvent.class); SyncUtil.addBreakpoint(SOURCE_NAME + ":" + getLineForTag("LINE_MAIN_ALL_THREADS_STARTED"), false); SyncUtil.addBreakpoint("36", false); SyncUtil.resumeAll(); IMIExecutionDMContext[] threads = SyncUtil.getExecutionContexts(); System.out.println(threads.toString()); eventWaitor.waitForEvent(2000); eventWaitor.waitForEvent(2000); eventWaitor.waitForEvent(2000); eventWaitor.waitForEvent(2000); <START> eventWaitor.waitForEvent(2000); <END> for (int i = 0; i < 2; i++) { fGdbSync.setCurrentGDBStackFrame(SyncUtil.getStackFrame(1, 1)); assertEquals("1", getCurrentStackFrameLevel()); fGdbSync.setCurrentGDBStackFrame(SyncUtil.getStackFrame(1, 0)); assertEquals("0", getCurrentStackFrameLevel()); } }</code><technical_language>massageTimeout instead,</technical_language>

Target:
public void testGdbSyncServiceCanSwitchGDBStackFrame() throws Throwable { ServiceEventWaitor<MIStoppedEvent> eventWaitor = new ServiceEventWaitor<MIStoppedEvent>(fMultiRunControl.getSession(), MIStoppedEvent.class); SyncUtil.addBreakpoint(SOURCE_NAME + ":" + getLineForTag("LINE_MAIN_ALL_THREADS_STARTED"), false); SyncUtil.addBreakpoint("36", false); SyncUtil.resumeAll(); IMIExecutionDMContext[] threads = SyncUtil.getExecutionContexts(); System.out.println(threads.toString()); eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); eventWaitor.waitForEvent(TestsPlugin.massageTimeout(2000)); for (int i = 0; i < 2; i++) { fGdbSync.setCurrentGDBStackFrame(SyncUtil.getStackFrame(1, 1)); assertEquals("1", getCurrentStackFrameLevel()); fGdbSync.setCurrentGDBStackFrame(SyncUtil.getStackFrame(1, 0)); assertEquals("0", getCurrentStackFrameLevel()); } }
Source:
<code><START> protected String buildUrl() { <END> if (isEmpty(serverURL)) { throw new IllegalStateException("server can not be null"); } final StringBuilder sb = new StringBuilder(); sb.append(serverURL).append("rest/sender/"); return sb.toString(); }</code><technical_language>I returning "rest/sender/" is simpler, StringBuilder</technical_language>

Target:
protected String buildUrl() { if (isEmpty(serverURL)) { throw new IllegalStateException("server can not be null"); } return serverURL + "rest/sender/"; }
Source:
<code>private static JSONObject contact(Patient patient) { String name = "PhenomeCentral"; String institution = "PhenomeCentral"; String href = "mailto:matchmaker@phenomecentral.org"; PatientData<String> data = patient.getData("contact"); if (data != null && data.isNamed()) { name = data.get("name"); <START> institution = data.get("institution"); <END> String email = data.get("email"); if (!StringUtils.isBlank(email)) { href = "mailto:" + email; } } JSONObject contactJson = new JSONObject(); contactJson.put(ApiConfiguration.JSON_CONTACT_NAME, name); contactJson.put(ApiConfiguration.JSON_CONTACT_INSTITUTION, institution); contactJson.put(ApiConfiguration.JSON_CONTACT_HREF, href); return contactJson; }</code><technical_language>Do institution defined in PT/PC? check for isBlank() replace default (PhenomeCentral) if blank? blank is expected (as in "no institution")</technical_language>

Target:
private static JSONObject contact(Patient patient) { String name = "PhenomeCentral Support"; String institution = "PhenomeCentral"; String href = "mailto:matchmaker@phenomecentral.org"; PatientData<String> data = patient.getData("contact"); if (data != null && data.isNamed()) { String contactName = data.get("name"); if (!StringUtils.isBlank(contactName)) { name = contactName; } institution = data.get("institution"); String email = data.get("email"); if (!StringUtils.isBlank(email)) { href = "mailto:" + email; } } JSONObject contactJson = new JSONObject(); contactJson.put(ApiConfiguration.JSON_CONTACT_NAME, name); if (!StringUtils.isBlank(institution)) { contactJson.put(ApiConfiguration.JSON_CONTACT_INSTITUTION, institution); } contactJson.put(ApiConfiguration.JSON_CONTACT_HREF, href); return contactJson; }
Source:
<code>private void handleSentImage(Intent intent) { Uri imageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); if (imageUri != null) { displayFAB(false); displayChatBox(true); String loadingMsg = getResources().getString(R.string.uploading_message); sendingMessage(true, loadingMsg); String imageFilePath = FilePathHelper.getPath(this, imageUri); uploadFile(imageFilePath); } else { <START> Toast.makeText(this, "Could not find the image", Toast.LENGTH_SHORT).show(); <END> } }</code><technical_language>Strings belong in strings.xml</technical_language>

Target:
private void handleSentImage(Intent intent) { mImageUri = (Uri) intent.getParcelableExtra(Intent.EXTRA_STREAM); if (mImageUri != null) { if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, PERMISSION_REQUEST_READ_CONTACTS); } else { startFileUpload(); } } else { Toast.makeText(this, R.string.cannot_find_image, Toast.LENGTH_SHORT).show(); } }
Source:
<code>private void test(byte[] input) throws IOException { random.nextBytes(input); byte[][] split = fragmenter.split(input); for (byte[] bytes : split) { int length = bytes.length; <START> assertTrue(length >= 0); <END> assertTrue(length <= Fragment.MAX_LENGTH); } byte[] recombine = fragmenter.recombine(split, input.length); assertTrue("recombine(split(input)) = input", Arrays.equals(input, recombine)); }</code><technical_language>In case is this zero</technical_language>

Target:
private void test(byte[] input) throws IOException { random.nextBytes(input); byte[][] split = fragmenter.split(input); for (byte[] bytes : split) { int length = bytes.length; assertTrue(length > 0); assertTrue(length <= Fragment.MAX_LENGTH); } byte[] recombine = fragmenter.recombine(split, input.length); assertTrue("recombine(split(input)) = input", Arrays.equals(input, recombine)); }
Source:
<code>protected void killProcess(String[] killCommand, List<ProcessInfo> process) throws ProcessHandlerException { try { for (ProcessInfo eachProcess : process) { log.info("Killing process : " + eachProcess); <START> String[] cmd = new String[killCommand.length + 1]; <END> cmd[cmd.length] = eachProcess.getProcessId(); Process output = Runtime.getRuntime().exec(cmd); int returnCode = output.waitFor(); if (returnCode != 0) { log.info("Printing possible errors " + convertStreamToString(output.getErrorStream())); } output.destroy(); } log.info("Successfully killed all stalled processes"); } catch (IOException | InterruptedException e) { throw new ProcessHandlerException(e); } }</code><technical_language>need copy kill command array cmd</technical_language>

Target:
protected void killProcess(String[] killCommand, List<ProcessInfo> process) throws ProcessHandlerException { try { for (ProcessInfo eachProcess : process) { log.info("Killing process : " + eachProcess); String[] cmd = Arrays.copyOf(killCommand, killCommand.length + 1); cmd[cmd.length] = eachProcess.getProcessId(); Process output = Runtime.getRuntime().exec(cmd); int returnCode = output.waitFor(); if (returnCode != 0) { log.info("Printing possible errors " + convertStreamToString(output.getErrorStream())); } output.destroy(); } log.info("Successfully killed all stalled processes"); } catch (IOException | InterruptedException e) { throw new ProcessHandlerException(e); } }
Source:
<code>private static boolean isLegacyConnectorOptions( CatalogTable catalogTable, CatalogSchemaTable schemaTable) { if (catalogTable.getOptions().containsKey(ConnectorDescriptorValidator.CONNECTOR_TYPE)) { return true; } else { <START> try { <END> TableFactoryUtil.findAndCreateTableSource( schemaTable.getCatalog(), schemaTable.getTableIdentifier(), catalogTable, new Configuration()); return true; } catch (Throwable e) { return false; } } }</code><technical_language>I consider case sensitivity here</technical_language>

Target:
private static boolean isLegacyConnectorOptions( CatalogTable catalogTable, CatalogSchemaTable schemaTable) { DescriptorProperties properties = new DescriptorProperties(true); properties.putProperties(catalogTable.getOptions()); if (properties.containsKey(ConnectorDescriptorValidator.CONNECTOR_TYPE)) { return true; } else { try { TableFactoryUtil.findAndCreateTableSource( schemaTable.getCatalog(), schemaTable.getTableIdentifier(), catalogTable, new Configuration()); return true; } catch (Throwable e) { return false; } } }
Source:
<code>public void update() { if (toolItem != null) { <START> toolItem.setEnabled(canCreateNewForm() || canEditForm()); <END> final PageFlow pageFlow = unwrap(selectionProvider.getSelection()); if (pageFlow != null) { if (pageFlow instanceof Pool) { toolItem.setToolTipText(NLS.bind(Messages.newFormTooltip, Messages.pool)); } else { toolItem.setToolTipText(NLS.bind(Messages.newFormTooltip, Messages.task)); } } } }</code><technical_language>I button is enabled. form is defined -> new form A form is defined -> open form</technical_language>

Target:
public void update() { if (toolItem != null) { toolItem.setEnabled(true); final PageFlow pageFlow = unwrap(selectionProvider.getSelection()); if (pageFlow != null) { if (pageFlow instanceof Pool) { toolItem.setToolTipText(NLS.bind(Messages.newFormTooltip, Messages.pool)); } else { toolItem.setToolTipText(NLS.bind(Messages.newFormTooltip, Messages.task)); } } } }
Source:
<code>public void subscribeToConnection(ConnectionSubscriber subscriber) { BufferedReader receiver = null; try { receiver = new BufferedReader( new InputStreamReader(mSocket.getInputStream())); } catch (IOException e) { subscriber.updateOnConnectionProblem(e); return; } String pushMessage = null; do { try { pushMessage = receiver.readLine(); if(pushMessage != null) { Log.d("Y:" + this.getClass().getName(), "response : " + pushMessage); Response response = new Response(pushMessage); subscriber.updateOn(response); } } catch (IOException e) { subscriber.updateOnConnectionProblem(e); } catch (JSONException e) { subscriber.updateOnParsingProblem(e); } } while (pushMessage != null); try { this.close(); } catch (IOException e) { Log.d("Y:" + this.getClass().getName(),"Connection was already closed."); } finally { <START> subscriber.updateOnConnectionProblem(new IOException("Server imput is shutdown")); <END> } }</code><technical_language>Typo : "input" "imput"</technical_language>

Target:
public void subscribeToConnection(ConnectionSubscriber subscriber) { BufferedReader receiver = null; try { receiver = new BufferedReader( new InputStreamReader(mSocket.getInputStream())); } catch (IOException e) { subscriber.updateOnConnectionProblem(e); return; } String pushMessage = null; do { try { pushMessage = receiver.readLine(); if(pushMessage != null) { Log.d("Y:" + this.getClass().getName(), "response : " + pushMessage); Response response = new Response(pushMessage); subscriber.updateOn(response); } } catch (IOException e) { subscriber.updateOnConnectionProblem(e); } catch (JSONException e) { subscriber.updateOnParsingProblem(e); } } while (pushMessage != null); try { this.close(); } catch (IOException e) { Log.d("Y:" + this.getClass().getName(),"Connection was already closed."); } finally { subscriber.updateOnConnectionProblem(new IOException("Server input is shutdown")); } }
Source:
<code>public void setUp() throws Exception { super.setUp(); Transaction tx = openSession().beginTransaction(); <START> A a = new A(); <END> a.value = "1"; getSession().save( a ); tx.commit(); getSession().close(); this.fullTextSession = Search.getFullTextSession( openSession() ); }</code><technical_language>do need a for Elasticsearch</technical_language>

Target:
public void setUp() throws Exception { super.setUp(); Transaction tx = openSession().beginTransaction(); getSession().save( new A() ); tx.commit(); getSession().close(); this.fullTextSession = Search.getFullTextSession( openSession() ); }
Source:
<code>public void testVideoType() { <START> DocumentType videoType = session.getDocumentType(VideoConstants.VIDEO_TYPE); <END> assertNotNull("Does our type exist?", videoType); DocumentModel docModel = session.createDocumentModel("/", "doc", VideoConstants.VIDEO_TYPE); assertNotNull(docModel); assertNull(docModel.getPropertyValue("common:icon")); assertNull(docModel.getPropertyValue("dc:title")); assertNull(docModel.getPropertyValue("picture:credit")); assertNull(docModel.getPropertyValue("uid:uid")); assertNull(docModel.getPropertyValue(VideoConstants.DURATION_PROPERTY)); docModel.setPropertyValue("common:icon", "/icons/video.png"); docModel.setPropertyValue("dc:title", "testTitle"); docModel.setPropertyValue("picture:credit", "testUser"); docModel.setPropertyValue("uid:uid", "testUid"); DocumentModel docModelResult = session.createDocument(docModel); assertNotNull(docModelResult); assertEquals("/icons/video.png", docModelResult.getPropertyValue("common:icon")); assertEquals("testTitle", docModelResult.getPropertyValue("dc:title")); assertEquals("testUser", docModelResult.getPropertyValue("picture:credit")); assertEquals("testUid", docModelResult.getPropertyValue("uid:uid")); docModelResult = session.getDocument(docModelResult.getRef()); assertNull(docModelResult.getPropertyValue(VideoConstants.DURATION_PROPERTY)); assertEquals(Collections.emptyList(), docModel.getPropertyValue(VideoConstants.STORYBOARD_PROPERTY)); assertEquals(Collections.emptyList(), docModel.getPropertyValue(VideoConstants.TRANSCODED_VIDEOS_PROPERTY)); }</code><technical_language>Worth adding VideoConstants.* static import</technical_language>

Target:
public void testVideoType() { DocumentType videoType = session.getDocumentType(VIDEO_TYPE); assertNotNull("Does our type exist?", videoType); DocumentModel docModel = session.createDocumentModel("/", "doc", VIDEO_TYPE); assertNotNull(docModel); assertNull(docModel.getPropertyValue("common:icon")); assertNull(docModel.getPropertyValue("dc:title")); assertNull(docModel.getPropertyValue("picture:credit")); assertNull(docModel.getPropertyValue("uid:uid")); assertNull(docModel.getPropertyValue(DURATION_PROPERTY)); docModel.setPropertyValue("common:icon", "/icons/video.png"); docModel.setPropertyValue("dc:title", "testTitle"); docModel.setPropertyValue("picture:credit", "testUser"); docModel.setPropertyValue("uid:uid", "testUid"); DocumentModel docModelResult = session.createDocument(docModel); assertNotNull(docModelResult); assertEquals("/icons/video.png", docModelResult.getPropertyValue("common:icon")); assertEquals("testTitle", docModelResult.getPropertyValue("dc:title")); assertEquals("testUser", docModelResult.getPropertyValue("picture:credit")); assertEquals("testUid", docModelResult.getPropertyValue("uid:uid")); docModelResult = session.getDocument(docModelResult.getRef()); assertNull(docModelResult.getPropertyValue(DURATION_PROPERTY)); assertEquals(Collections.emptyList(), docModel.getPropertyValue(STORYBOARD_PROPERTY)); assertEquals(Collections.emptyList(), docModel.getPropertyValue(TRANSCODED_VIDEOS_PROPERTY)); }
Source:
<code>private void startNewDispatcherLeaderProcess(UUID leaderSessionID) { try { stopDispatcherLeaderProcess(); dispatcherLeaderProcess = createNewDispatcherLeaderProcess(leaderSessionID); final DispatcherLeaderProcess newDispatcherLeaderProcess = dispatcherLeaderProcess; FutureUtils.assertNoException( previousDispatcherLeaderProcessTerminationFuture.thenRun(newDispatcherLeaderProcess::start)); } catch (Throwable t) { <START> terminationFuture.completeExceptionally(t); throw t; <END> } }</code><technical_language>is this needed</technical_language>

Target:
private void startNewDispatcherLeaderProcess(UUID leaderSessionID) { stopDispatcherLeaderProcess(); dispatcherLeaderProcess = createNewDispatcherLeaderProcess(leaderSessionID); final DispatcherLeaderProcess newDispatcherLeaderProcess = dispatcherLeaderProcess; FutureUtils.assertNoException( previousDispatcherLeaderProcessTerminationFuture.thenRun(newDispatcherLeaderProcess::start)); }
Source:
<code>protected void addVmStatic() { logImportEvents(); getVm().getStaticData().setId(getVmId()); getVm().getStaticData().setCreationDate(new Date()); getVm().getStaticData().setClusterId(getParameters().getClusterId()); getVm().getStaticData().setMinAllocatedMem(computeMinAllocatedMem()); getVm().getStaticData().setQuotaId(getParameters().getQuotaId()); if (!vmHandler.validateDedicatedVdsExistOnSameCluster(getVm().getStaticData()).isValid()) { getVm().setDedicatedVmForVdsList(Collections.emptyList()); } if (getVm().getOriginalTemplateGuid() != null && !VmTemplateHandler.BLANK_VM_TEMPLATE_ID.equals(getVm().getOriginalTemplateGuid())) { VmTemplate originalTemplate = vmTemplateDao.get(getVm().getOriginalTemplateGuid()); if (originalTemplate != null) { getVm().getStaticData().setOriginalTemplateName(originalTemplate.getName()); } } if (getParameters().getCopyCollapse()) { getVm().setVmtGuid(VmTemplateHandler.BLANK_VM_TEMPLATE_ID); } <START> vmHandler.autoSelectResumeBehavior(getVm().getStaticData(), getCluster().getCompatibilityVersion()); <END> vmStaticDao.save(getVm().getStaticData()); getCompensationContext().snapshotNewEntity(getVm().getStaticData()); }</code><technical_language>need autoSelectResumeBehavior set default, no</technical_language>

Target:
protected void addVmStatic() { logImportEvents(); getVm().getStaticData().setId(getVmId()); getVm().getStaticData().setCreationDate(new Date()); getVm().getStaticData().setClusterId(getParameters().getClusterId()); getVm().getStaticData().setMinAllocatedMem(computeMinAllocatedMem()); getVm().getStaticData().setQuotaId(getParameters().getQuotaId()); if (!vmHandler.validateDedicatedVdsExistOnSameCluster(getVm().getStaticData()).isValid()) { getVm().setDedicatedVmForVdsList(Collections.emptyList()); } if (getVm().getOriginalTemplateGuid() != null && !VmTemplateHandler.BLANK_VM_TEMPLATE_ID.equals(getVm().getOriginalTemplateGuid())) { VmTemplate originalTemplate = vmTemplateDao.get(getVm().getOriginalTemplateGuid()); if (originalTemplate != null) { getVm().getStaticData().setOriginalTemplateName(originalTemplate.getName()); } } if (getParameters().getCopyCollapse()) { getVm().setVmtGuid(VmTemplateHandler.BLANK_VM_TEMPLATE_ID); } vmHandler.autoSelectResumeBehavior(getVm().getStaticData(), getCluster()); vmStaticDao.save(getVm().getStaticData()); getCompensationContext().snapshotNewEntity(getVm().getStaticData()); }
Source:
<code>public static Integer getDp(Object obj) { if (obj instanceof Number) { <START> return (Integer) obj; <END> } else if (obj.getClass().equals(String.class)) { String str = (String) obj; if (str.substring(Math.max(str.length() - 2, 0)).equals("px")) { try { int px = Integer.parseInt(str.substring(0, str.length() - 2)); return (int) ( (int)px * 1f / (ScanditSDK.DISPLAY.densityDpi / 160f)); } catch (NumberFormatException e) { Log.e("ScanditSDK", "Can not recognize dp value of String " + str + " - returning 0"); return 0; } } else { try { return Integer.parseInt(str); } catch (NumberFormatException e) { Log.e("ScanditSDK", "Can not recognize dp value of String " + str + " - returning 0"); return 0; } } } else { Log.e("ScanditSDK", "Can not recognize dp value - returning 0"); return 0; } }</code><technical_language>This cast safe. obj a double/float</technical_language>

Target:
public static Integer getDp(Object obj) { if (obj instanceof Number) { return ((Number) obj).intValue(); } else if (obj.getClass().equals(String.class)) { String str = (String) obj; if (str.substring(Math.max(str.length() - 2, 0)).equals("px")) { try { int px = Integer.parseInt(str.substring(0, str.length() - 2)); return (int) ( (int)px * 1f / (ScanditSDK.DISPLAY.densityDpi / 160f)); } catch (NumberFormatException e) { Log.e("ScanditSDK", "Can not recognize dp value of String " + str + " - returning 0"); return 0; } } else { try { return Integer.parseInt(str); } catch (NumberFormatException e) { Log.e("ScanditSDK", "Can not recognize dp value of String " + str + " - returning 0"); return 0; } } } else { Log.e("ScanditSDK", "Can not recognize dp value - returning 0"); return 0; } }
Source:
<code>public Set<String> undocumentedThrownExceptions() { Map<String, List<String>> thrownExceptionsMap = getJavadocExceptions(); List<String> exceptionNames = elementExceptionNames; if (exceptionNames.size() == 1 && GENERIC_EXCEPTIONS.contains(toSimpleName(exceptionNames.get(0))) && !thrownExceptionsMap.isEmpty()) { return thrownExceptionsMap.entrySet().stream() .filter(e -> isEmptyDescription(e.getValue())) .map(Map.Entry::getKey) .map(Javadoc::toSimpleName) <START> .collect(Collectors.toSet()); <END> } return exceptionNames.stream() .map(Javadoc::toSimpleName) .filter(simpleName -> noDescriptionForException(thrownExceptionsMap, simpleName)) .collect(Collectors.toSet()); }</code><technical_language>I collect a List</technical_language>

Target:
public List<String> undocumentedThrownExceptions() { return undocumentedNamedTags.computeIfAbsent(BlockTag.EXCEPTIONS, key -> computeUndocumentedThrownExceptions()); }
Source:
<code>public VmManagementParametersBase(VmStatic vmStatic) { super(vmStatic.getId()); _vmStatic = vmStatic; privateStorageDomainId = Guid.Empty; <START> consoleEnabled = false; <END> balloonEnabled = true; }</code><technical_language>consoleEnabled = Boolean.FALSE, in default ctor</technical_language>

Target:
public VmManagementParametersBase(VmStatic vmStatic) { super(vmStatic.getId()); _vmStatic = vmStatic; privateStorageDomainId = Guid.Empty; consoleEnabled = Boolean.FALSE; balloonEnabled = true; }
Source:
<code>public static ConversationKey fromJsonString(String json) { <START> if(json.equals("Other")) { <END> return forOther(); } final Object[] array = gson.fromJson(json, Object[].class); if (array.length != 5) { throw new IllegalArgumentException("Invalid conversation key string: " + json); } return new ConversationKey((String)array[0], ((Number)array[1]).intValue(), (String)array[2], (String)array[3], (String)array[4]); }</code><technical_language>This sneaky</technical_language>

Target:
public static ConversationKey fromJsonString(String json) { final Object[] array = gson.fromJson(json, Object[].class); if (array.length != 5) { throw new IllegalArgumentException("Invalid conversation key string: " + json); } return new ConversationKey((String)array[0], ((Number)array[1]).intValue(), (String)array[2], (String)array[3], (String)array[4]); }
Source:
<code>private Subfield.PathElement matchUnquotedSubscript() { int start = index; while (hasNextCharacter() && isUnquotedSubscriptCharacter(peekCharacter())) { nextCharacter(); } int end = index; String token = path.substring(start, end); if (token.isEmpty()) { throw invalidSubfieldPath(); } <START> return new Subfield.LongSubscript(Long.valueOf(token)); <END> }</code><technical_language>need check if token is a legit long. For example a[b]</technical_language>

Target:
private Subfield.PathElement matchUnquotedSubscript() { int start = index; while (hasNextCharacter() && isUnquotedSubscriptCharacter(peekCharacter())) { nextCharacter(); } int end = index; String token = path.substring(start, end); if (token.isEmpty()) { throw invalidSubfieldPath(); } long index; try { index = Long.valueOf(token); } catch (NumberFormatException e) { throw invalidSubfieldPath(); } return new Subfield.LongSubscript(index); }
Source:
<code>public RecordReader<E, Void> asRecordReader() { Preconditions.checkArgument(incoming instanceof FSDataInputStream, "Cannot use in a record reader", incoming.getClass()); <START> return new CSVRecordReader(); <END> }</code><technical_language>Rename JsonRecordReader</technical_language>

Target:
public RecordReader<E, Void> asRecordReader() { Preconditions.checkArgument(incoming instanceof FSDataInputStream, "Cannot use in a record reader", incoming.getClass()); return new JSONRecordReader(); }
Source:
<code>public void handle(HttpExchange exchange) throws IOException { ClassLoader loader = StaticHandler.class.getClassLoader(); InputStream is = loader.getResourceAsStream(mResourceName); if (is == null) { exchange.getResponseHeaders().add("Content-Type", "text/html"); exchange.sendResponseHeaders(404, 0); PrintStream ps = new PrintStream(exchange.getResponseBody()); HtmlDoc doc = new HtmlDoc(ps, DocString.text("ahat"), DocString.uri("style.css")); doc.big(DocString.text("Resource not found.")); doc.close(); } else { exchange.getResponseHeaders().add("Content-Type", mContentType); exchange.sendResponseHeaders(200, 0); OutputStream os = exchange.getResponseBody(); int read; byte[] buf = new byte[4096]; <START> while ((read = is.read(buf)) > 0) { <END> os.write(buf, 0, read); } is.close(); os.close(); } }</code><technical_language>matter in practice, is.read() returns -1 if stream is finished 0 if for some reason read characters stream is live. implementation returns 0, want check > -1 instead of > 0</technical_language>

Target:
public void handle(HttpExchange exchange) throws IOException { ClassLoader loader = StaticHandler.class.getClassLoader(); InputStream is = loader.getResourceAsStream(mResourceName); if (is == null) { exchange.getResponseHeaders().add("Content-Type", "text/html"); exchange.sendResponseHeaders(404, 0); PrintStream ps = new PrintStream(exchange.getResponseBody()); HtmlDoc doc = new HtmlDoc(ps, DocString.text("ahat"), DocString.uri("style.css")); doc.big(DocString.text("Resource not found.")); doc.close(); } else { exchange.getResponseHeaders().add("Content-Type", mContentType); exchange.sendResponseHeaders(200, 0); OutputStream os = exchange.getResponseBody(); int read; byte[] buf = new byte[4096]; while ((read = is.read(buf)) >= 0) { os.write(buf, 0, read); } is.close(); os.close(); } }
Source:
<code>private static boolean checkArtifactUsingHttp(String url, String username, String password) { try { HttpURLConnection.setFollowRedirects(false); HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("HEAD"); if (!username.isEmpty() && !password.isEmpty()) { String usernameColonPassword = username + ":" + password; String basicAuthPayload = "Basic " + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes()); con.addRequestProperty("Authorization", basicAuthPayload); } return (con.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { <START> LOGGER.debug("Artifact doesn't exist" + e); <END> return false; } }</code><technical_language>formatting</technical_language>

Target:
private static boolean checkArtifactUsingHttp(String url, String username, String password) { try { HttpURLConnection.setFollowRedirects(false); HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection(); con.setRequestMethod("HEAD"); if (!username.isEmpty() && !password.isEmpty()) { String usernameColonPassword = username + ":" + password; String basicAuthPayload = "Basic " + Base64.getEncoder().encodeToString(usernameColonPassword.getBytes()); con.addRequestProperty("Authorization", basicAuthPayload); } return (con.getResponseCode() == HttpURLConnection.HTTP_OK); } catch (Exception e) { LOGGER.debug("Artifact doesn't exist: " + url, e); return false; } }
Source:
<code>public AzureProfile(AzureEnvironment environment, boolean loadEnvironmentVariables) { Objects.requireNonNull(environment); if (loadEnvironmentVariables) { <START> Configuration configuration = Configuration.getGlobalConfiguration().clone(); <END> this.tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); this.subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); } }</code><technical_language>need clone it</technical_language>

Target:
public AzureProfile(AzureEnvironment environment, boolean loadEnvironmentVariables) { Objects.requireNonNull(environment); this.environment = environment; if (loadEnvironmentVariables) { Configuration configuration = Configuration.getGlobalConfiguration(); this.tenantId = configuration.get(Configuration.PROPERTY_AZURE_TENANT_ID); this.subscriptionId = configuration.get(Configuration.PROPERTY_AZURE_SUBSCRIPTION_ID); } }
Source:
<code>public void testTextBinding() { CredentialsPage mc = new CredentialsPage(jenkins, ManagedCredentials.DEFAULT_DOMAIN); mc.open(); StringCredentials cred = mc.add(StringCredentials.class); cred.scope.select("GLOBAL"); cred.secret.set(SECRET_TEXT); mc.create(); FreeStyleJob job = jenkins.jobs.create(); job.configure(); job.check("Use secret text(s) or file(s)"); ManagedCredentialsBinding mcb = new ManagedCredentialsBinding(job); SecretStringCredentialsBinding cb = mcb.addCredentialBinding(SecretStringCredentialsBinding.class); cb.variable.set("BINDED_SECRET"); ShellBuildStep shell = job.addBuildStep(ShellBuildStep.class); shell.command("if [ \"$BINDED_SECRET\" = \"" + SECRET_TEXT + "\" ] \n then \n echo \"true\" \n fi"); job.save(); Build b = job.scheduleBuild(); b.shouldSucceed(); <START> assertThat(b.getConsole(), containsString("true")); <END> }</code><technical_language>a more specific text? console displays "true" for other reasons</technical_language>

Target:
public void testTextBinding() { CredentialsPage mc = new CredentialsPage(jenkins, ManagedCredentials.DEFAULT_DOMAIN); mc.open(); StringCredentials cred = mc.add(StringCredentials.class); cred.scope.select("GLOBAL"); cred.secret.set(SECRET_TEXT); mc.create(); FreeStyleJob job = jenkins.jobs.create(); job.configure(); job.check("Use secret text(s) or file(s)"); ManagedCredentialsBinding mcb = new ManagedCredentialsBinding(job); SecretStringCredentialsBinding cb = mcb.addCredentialBinding(SecretStringCredentialsBinding.class); cb.variable.set("BINDED_SECRET"); ShellBuildStep shell = job.addBuildStep(ShellBuildStep.class); shell.command("if [ \"$BINDED_SECRET\" = \"" + SECRET_TEXT + "\" ] \n then \n echo \"" + SECRET_OUTPUT + "\" \n fi"); job.save(); Build b = job.scheduleBuild(); b.shouldSucceed(); assertThat(b.getConsole(), containsString(SECRET_OUTPUT)); }
Source:
<code>public Optional<UUID> getId() { <START> if (id == null) { <END> return Optional.empty(); } return Optional.of(id); }</code><technical_language>This simplified Optional.ofNullable(id)</technical_language>

Target:
public Optional<UUID> getId() { return Optional.ofNullable(id); }
Source:
<code>public static HistoryFileType getHistoryFileType(QualifiedJobId qualifiedJobId, byte[] historyFileContents) { <START> if (historyFileContents == null) <END> throw new IllegalArgumentException("Null job history file"); if ((qualifiedJobId != null) && Constants.FRAMEWORK_CONF_SPARK_VALUE .equalsIgnoreCase(qualifiedJobId.getJobPrefix())) { return HistoryFileType.SPARK; } if(historyFileContents.length > HADOOP2_VERSION_LENGTH) { String version2Part = new String(historyFileContents, 0, HADOOP2_VERSION_LENGTH); if (StringUtils.equalsIgnoreCase(version2Part, HADOOP2_VERSION_STRING)) { return HistoryFileType.TWO; } else { if(historyFileContents.length > HADOOP1_VERSION_LENGTH) { String version1Part = new String(historyFileContents, 0,HADOOP1_VERSION_LENGTH); if (StringUtils.equalsIgnoreCase(version1Part, HADOOP1_VERSION_STRING)) { return HistoryFileType.ONE; } } } } throw new IllegalArgumentException(" Unknown format of job history file: " + historyFileContents); }</code><technical_language>Nit: I hRaven coding style (which is Hadoop's) is braces for if's...</technical_language>

Target:
public static HistoryFileType getHistoryFileType(QualifiedJobId qualifiedJobId, byte[] historyFileContents) { if (historyFileContents == null) { throw new IllegalArgumentException("Null job history file"); } if ((qualifiedJobId != null) && Constants.FRAMEWORK_CONF_SPARK_VALUE .equalsIgnoreCase(qualifiedJobId.getJobPrefix())) { return HistoryFileType.SPARK; } if(historyFileContents.length > HADOOP2_VERSION_LENGTH) { String version2Part = new String(historyFileContents, 0, HADOOP2_VERSION_LENGTH); if (StringUtils.equalsIgnoreCase(version2Part, HADOOP2_VERSION_STRING)) { return HistoryFileType.TWO; } else { if(historyFileContents.length > HADOOP1_VERSION_LENGTH) { String version1Part = new String(historyFileContents, 0,HADOOP1_VERSION_LENGTH); if (StringUtils.equalsIgnoreCase(version1Part, HADOOP1_VERSION_STRING)) { return HistoryFileType.ONE; } } } } throw new IllegalArgumentException(" Unknown format of job history file: " + historyFileContents); }
Source:
<code>public void deserialize(ConsumerRecord<byte[], byte[]> record, Collector<T> collector) throws IOException { if (deserializer == null) { <START> try (TemporaryClassLoaderContext ignored = TemporaryClassLoaderContext.of(userCodeClassLoader)) { <END> deserializer = (Deserializer<T>) InstantiationUtil.instantiate( deserializerClass, Deserializer.class, getClass().getClassLoader()); if (deserializer instanceof Configurable) { ((Configurable) deserializer).configure(config); } } catch (Exception e) { throw new IOException( "Failed to instantiate the deserializer of class " + deserializerClass, e); } } T value = deserializer.deserialize(record.topic(), record.value()); LOG.trace("Deserialized [partition: {}-{}, offset: {}, timestamp: {}, value: {}]", record.topic(), record.partition(), record.offset(), record.timestamp(), value); collector.collect(value); }</code><technical_language>this initialization moved open method? If not, good move init logic separate method, main method code paths small, for JIT friendlyness</technical_language>

Target:
public void deserialize(ConsumerRecord<byte[], byte[]> record, Collector<T> collector) throws IOException { if (deserializer == null) { throw new IllegalStateException( "The deserializer has not been created. Make sure the open() method has been " + "invoked."); } T value = deserializer.deserialize(record.topic(), record.value()); LOG.trace("Deserialized [partition: {}-{}, offset: {}, timestamp: {}, value: {}]", record.topic(), record.partition(), record.offset(), record.timestamp(), value); collector.collect(value); }
Source:
<code>protected void internalExecute(ScenarioSimulationContext context) { final ScenarioSimulationContext.Status status = context.getStatus(); SimulationDescriptor simulationDescriptor = status.getSimulation().getSimulationDescriptor(); int columnIndex = status.getColumnIndex(); FactMapping factMapping = simulationDescriptor.getFactMappingByIndex(columnIndex); <START> String placeholder = ScenarioSimulationUtils.isExpressionType(factMapping) ? ScenarioSimulationEditorConstants.INSTANCE.insertExpression() : ScenarioSimulationUtils.getPlaceholder(factMapping.getClassName()); <END> context.getModel().setCellValue(status.getRowIndex(), columnIndex, new ScenarioGridCellValue(status.getGridCellValue(), placeholder)); context.getModel().resetError(status.getRowIndex(), columnIndex); }</code><technical_language>I prefer placeholder logic ScenarioSimulationUtils.getPlaceholder. refactor method accept FactMapping instead of className do checks there. Wdyt</technical_language>

Target:
protected void internalExecute(ScenarioSimulationContext context) { final ScenarioSimulationContext.Status status = context.getStatus(); ScesimModelDescriptor simulationDescriptor = status.getSimulation().getScesimModelDescriptor(); int columnIndex = status.getColumnIndex(); FactMapping factMapping = simulationDescriptor.getFactMappingByIndex(columnIndex); ScenarioGridColumn selectedColumn = (ScenarioGridColumn) context.getSelectedScenarioGridModel().getColumns().get(columnIndex); String placeholder = ScenarioSimulationUtils.getPlaceHolder(selectedColumn.isInstanceAssigned(), selectedColumn.isPropertyAssigned(), factMapping.getFactMappingValueType(), factMapping.getClassName()); context.getSelectedScenarioGridModel().setCellValue(status.getRowIndex(), columnIndex, new ScenarioGridCellValue(status.getGridCellValue(), placeholder)); context.getSelectedScenarioGridModel().resetError(status.getRowIndex(), columnIndex); }
Source:
<code>public BlockFamilyDefinitionFormat(AssetManager assetManager, BlockFamilyRegistry blockFamilyRegistry) { super("block"); this.assetManager = assetManager; this.blockFamilyRegistry = blockFamilyRegistry; gson = new GsonBuilder() .registerTypeAdapterFactory(new CaseInsensitiveEnumTypeAdapterFactory()) .registerTypeAdapterFactory(new AssetTypeAdapterFactory(assetManager)) .registerTypeAdapter(BlockFamilyDefinitionData.class, new BlockFamilyDefinitionDataHandler()) .registerTypeAdapter(Vector3f.class, new Vector3fTypeAdapter()) .registerTypeAdapter(Vector4f.class, new Vector4fTypeAdapter()) <START> .registerTypeAdapter(Class.class, new BlockFamilyHandler(blockFamilyRegistry)) <END> .create(); }</code><technical_language>This is throwing a big red flag for -- is a limit subtypes of a class? I guess bad if limited block family definitions</technical_language>

Target:
public BlockFamilyDefinitionFormat(AssetManager assetManager, BlockFamilyRegistry blockFamilyRegistry) { super("block"); this.assetManager = assetManager; gson = new GsonBuilder() .registerTypeAdapterFactory(new CaseInsensitiveEnumTypeAdapterFactory()) .registerTypeAdapterFactory(new AssetTypeAdapterFactory(assetManager)) .registerTypeAdapter(BlockFamilyDefinitionData.class, new BlockFamilyDefinitionDataHandler()) .registerTypeAdapter(Vector3f.class, new Vector3fTypeAdapter()) .registerTypeAdapter(Vector4f.class, new Vector4fTypeAdapter()) .registerTypeAdapter(Class.class, new BlockFamilyHandler(blockFamilyRegistry)) .create(); }
Source:
<code>private CacheBuilder<CacheKey, TypeCodec<?>> defaultCacheBuilder() { CacheBuilder<CacheKey, TypeCodec<?>> builder = CacheBuilder.newBuilder() .initialCapacity(100) .weigher(new TypeCodecWeigher()) .maximumWeight(1000); if (logger.isTraceEnabled()) <START> builder = builder.removalListener(new TypeCodecRemovalListener()); <END> return builder; }</code><technical_language>log levels manipulated dynamically, a thin case need worry it</technical_language>

Target:
private CacheBuilder<CacheKey, TypeCodec<?>> defaultCacheBuilder() { CacheBuilder<CacheKey, TypeCodec<?>> builder = CacheBuilder.newBuilder() .initialCapacity(100) .maximumWeight(1000) .weigher(new TypeCodecWeigher()); if (logger.isTraceEnabled()) builder = builder.removalListener(new TypeCodecRemovalListener()); return builder; }
Source:
<code>public Object read(Object request, Map kvp, Map rawKvp) throws Exception { GetFeatureType gf = (GetFeatureType) super.read(request, kvp, rawKvp); Filter filter = getFullFilter(kvp); querySet(gf, "filter", Collections.singletonList(filter)); if (!kvp.containsKey("outputFormat")) { gf.setOutputFormat(null); } if (kvp.containsKey("resolution")) { <START> gf.setResolution((String) kvp.get("resolution")); <END> } return gf; }</code><technical_language>GS architecture parsing of resolution string double done a KVPParser, declare a DoubleKvpParser instance in app-context parse it, assign a double</technical_language>

Target:
public Object read(Object request, Map kvp, Map rawKvp) throws Exception { GetFeatureType gf = (GetFeatureType) super.read(request, kvp, rawKvp); Filter filter = getFullFilter(kvp); querySet(gf, "filter", Collections.singletonList(filter)); if (!kvp.containsKey("outputFormat")) { gf.setOutputFormat(null); } if (kvp.containsKey("resolution")) { gf.setResolution((Integer) kvp.get("resolution")); } return gf; }
Source:
<code><START> public void echoTest() <END> throws ExecutionException, InterruptedException, JSONException { String inputText = "loremIpsum"; String uri = AdminBlobStorageService.ECHO + "?" + EchoHandler.TEXT_KEY + "=" + inputText; FullHttpRequest request = buildRequest(HttpMethod.GET, uri, null, null); Queue<HttpObject> responseParts = nettyClient.sendRequest(request, null, null).get(); HttpResponse response = (HttpResponse) responseParts.poll(); assertEquals("Unexpected status", HttpResponseStatus.OK, response.getStatus()); assertEquals("Unexpected Content-Type", "application/json", HttpHeaders.getHeader(response, HttpHeaders.Names.CONTENT_TYPE)); ByteBuffer buffer = getContent(response, responseParts); String echoedText = new JSONObject(new String(buffer.array())).getString(EchoHandler.TEXT_KEY); assertEquals("Did not get expected response", inputText, echoedText); }</code><technical_language>Do a test for RestServiceErrorCode.MissingArgs case</technical_language>

Target:
public void echoTest() throws ExecutionException, InterruptedException, JSONException { String inputText = "loremIpsum"; String uri = AdminBlobStorageService.ECHO + "?" + EchoHandler.TEXT_KEY + "=" + inputText; FullHttpRequest httpRequest = buildRequest(HttpMethod.GET, uri, null, null); Queue<HttpObject> responseParts = nettyClient.sendRequest(httpRequest, null, null).get(); HttpResponse response = (HttpResponse) responseParts.poll(); assertEquals("Unexpected status", HttpResponseStatus.OK, response.getStatus()); assertEquals("Unexpected Content-Type", "application/json", HttpHeaders.getHeader(response, HttpHeaders.Names.CONTENT_TYPE)); ByteBuffer buffer = getContent(response, responseParts); String echoedText = new JSONObject(new String(buffer.array())).getString(EchoHandler.TEXT_KEY); assertEquals("Did not get expected response", inputText, echoedText); }