auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Item getBasicFilmWithoutBroadcast(ProgData progData, DateTimeZone zone, Timestamp updatedAt) { String rtFilmAlias = PaHelper.getFilmRtAlias(progData.getRtFilmnumber()); String filmUri = PaHelper.getFilmUri(identifierFor(progData)); <START> ResolvedContent possiblePreviousData = contentResolver.findByCanonicalUris(ImmutableList.of(rtFilmAlias, filmUri)); <END> Film film; Maybe<Identified> oldFilm = possiblePreviousData.get(rtFilmAlias); Maybe<Identified> newFilm = possiblePreviousData.get(filmUri); if (oldFilm.hasValue()) { Identified previous = oldFilm.requireValue(); if (previous instanceof Film) { film = (Film) previous; } else { film = new Film(); Item.copyTo((Episode) previous, film); } film.addAlias(PaHelper.getProgIdAlias(progData.getProgId())); film.addAliasUrl(filmUri); } else if (newFilm.hasValue()) { Identified previous = newFilm.requireValue(); if (previous instanceof Film) { film = (Film) previous; } else { film = new Film(); Item.copyTo((Episode) previous, film); } film.addAlias(PaHelper.getProgIdAlias(progData.getProgId())); film.addAliasUrl(rtFilmAlias); } else { film = getBasicFilm(progData); } if (progData.getFilmYear() != null && MoreStrings.containsOnlyAsciiDigits(progData.getFilmYear())) { film.setYear(Integer.parseInt(progData.getFilmYear())); } return film; }</code><technical_language>findByCanonicalUris need aliases, no</technical_language>

Target:
private Item getBasicFilmWithoutBroadcast(ProgData progData, DateTimeZone zone, Timestamp updatedAt) { String filmAlias = PaHelper.getAlias(progData.getProgId()); String filmUri = PaHelper.getFilmUri(identifierFor(progData)); Maybe<Identified> possiblePreviousData = contentResolver.findByUris(ImmutableList.of( filmAlias, filmUri )).getFirstValue(); Film film; if (possiblePreviousData.hasValue()) { Identified previous = possiblePreviousData.requireValue(); if (previous instanceof Film) { film = (Film) previous; } else { film = new Film(); Item.copyTo((Episode) previous, film); } } else { film = getBasicFilm(progData); } if (progData.getFilmYear() != null && MoreStrings.containsOnlyAsciiDigits(progData.getFilmYear())) { film.setYear(Integer.parseInt(progData.getFilmYear())); } return film; }
Source:
<code>private boolean invalidParam(String url) { <START> return url == null || url.length() == 0; <END> }</code><technical_language><LINK_0></technical_language>

Target:
private boolean invalidParam(String url) { return TextUtils.isEmpty(url); }
Source:
<code>public void testShowStatsWithMultipleFromFails() <START> { <END> assertQueryFails("SHOW STATS FOR (SELECT * FROM orders, nation_partitioned)", ".*There must be exactly one table in query passed to SHOW STATS SELECT clause"); }</code><technical_language>this change</technical_language>

Target:
public void testShowStatsWithMultipleFromFails() { assertQueryFails("SHOW STATS FOR (SELECT * FROM nation_partitioned, region)", ".*There must be exactly one table in query passed to SHOW STATS SELECT clause"); }
Source:
<code>public static List<StorageServerConnections> updateIfaces(List<StorageServerConnections> conns, Guid vdsId) { List<StorageServerConnections> res = new ArrayList<>(conns); for (StorageServerConnections conn : conns) { List<VdsNetworkInterface> ifaces = DbFacade.getInstance().getInterfaceDao() <START> .getIscsiIfacesByHostIdAndStorageTargetId(vdsId, conn.getid()); <END> if (!ifaces.isEmpty()) { VdsNetworkInterface vdsNetworkInterface = ifaces.remove(0); conn.setIface(vdsNetworkInterface.getName()); conn.setNetIfacename(vdsNetworkInterface.isBridged() ? vdsNetworkInterface.getNetworkName() : vdsNetworkInterface.getName()); for (VdsNetworkInterface iface : ifaces) { StorageServerConnections newConn = StorageServerConnections.copyOf(conn); newConn.setid(Guid.newGuid().toString()); newConn.setIface(iface.getName()); newConn.setNetIfacename(iface.isBridged() ? iface.getNetworkName() : iface.getName()); res.add(newConn); } } } return res; }</code><technical_language>I assume this fetches VLAN devices properly, i.e. if iSCSI bond eth0.101, this return eth0 right</technical_language>

Target:
public static List<StorageServerConnections> updateIfaces(List<StorageServerConnections> conns, Guid vdsId) { List<StorageServerConnections> res = new ArrayList<>(conns); for (StorageServerConnections conn : conns) { List<VdsNetworkInterface> ifaces = DbFacade.getInstance().getInterfaceDao() .getIscsiIfacesByHostIdAndStorageTargetId(vdsId, conn.getid()); if (!ifaces.isEmpty()) { VdsNetworkInterface removedInterface = ifaces.remove(0); setInterfaceProperties(conn, removedInterface); for (VdsNetworkInterface iface : ifaces) { StorageServerConnections newConn = StorageServerConnections.copyOf(conn); newConn.setid(Guid.newGuid().toString()); setInterfaceProperties(newConn, iface); res.add(newConn); } } } return res; }
Source:
<code>public void toLastCommitted() { log.debug("toLastCommitted tailer: " + id); String msg = consumer.assignment().stream().map(tp -> String.format("%s-%02d:+%d", getNameForTopic(tp.topic()), tp.partition(), toLastCommitted(tp))) <START> .collect(Collectors.joining("|")); <END> if (msg.length() > 0) { log.info("toLastCommitted offsets: " + group + ":" + msg); } lastCommittedOffsets.clear(); lastOffsets.clear(); records.clear(); }</code><technical_language>Enclose in if (log.isInfoEnabled())</technical_language>

Target:
public void toLastCommitted() { if (log.isDebugEnabled()) { log.debug("toLastCommitted tailer: " + id); } String msg = consumer.assignment() .stream() .map(tp -> String.format("%s-%02d:+%d", getNameForTopic(tp.topic()), tp.partition(), toLastCommitted(tp))) .collect(Collectors.joining("|")); if (msg.length() > 0) { if (log.isInfoEnabled()) { log.info("toLastCommitted offsets: " + group + ":" + msg); } } lastCommittedOffsets.clear(); lastOffsets.clear(); records.clear(); }
Source:
<code>private DetectorTask restoreRedundancyAndMergeSegments(Layout layout) { String localEndpoint = serverContext.getLocalEndpoint(); if (RedundancyCalculator.requiresMerge(layout, localEndpoint) && !layout.getUnresponsiveServers().contains(localEndpoint)) { log.info("Layout requires restoration: {}. Spawning task to merge segments on {}.", layout, localEndpoint); Supplier<Boolean> redundancyAction = () -> handleMergeSegments( localEndpoint, runtimeSingletonResource, layout, MERGE_SEGMENTS_RETRY_QUERY_TIMEOUT ); mergeSegmentsTask = CompletableFuture.supplyAsync(redundancyAction, failureDetectorWorker); <START> return DetectorTask.COMPLETED; <END> } else if (!mergeSegmentsTask.isDone()) { log.debug("Merge segments task already in progress. Skipping spawning another task."); return DetectorTask.SKIPPED; } log.debug("No segments to merge. Skipping step."); return DetectorTask.SKIPPED; }</code><technical_language>worried if affects failure detector</technical_language>

Target:
private void restoreRedundancyAndMergeSegments(Layout layout) { String localEndpoint = serverContext.getLocalEndpoint(); if (!mergeSegmentsTask.isDone()){ log.trace("Merge segments task already in progress. Skipping spawning another task."); return; } if (RedundancyCalculator.canRestoreRedundancyOrMergeSegments(layout, localEndpoint) && !layout.getUnresponsiveServers().contains(localEndpoint)) { log.info("Layout requires restoration: {}. Spawning task to merge segments on {}.", layout, localEndpoint); Supplier<Boolean> redundancyAction = () -> handleMergeSegments( localEndpoint, runtimeSingletonResource, layout ); mergeSegmentsTask = CompletableFuture.supplyAsync(redundancyAction, failureDetectorWorker); return; } log.trace("No segments to merge. Skipping step."); }
Source:
<code><START> public void shouldPreferClientDestPortWhenInitialized() { <END> HttpRequestMessageImpl message = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", new HttpQueryParams(), new Headers(), "192.168.0.2", "https", 7002, "localhost", new InetSocketAddress("api.netflix.com", 443)); assertEquals(message.getClientDestinationPort(), 443); }</code><technical_language>Line wrapping is odd here. fill lines way, put arg line. This is for consistency</technical_language>

Target:
public void shouldPreferClientDestPortWhenInitialized() { HttpRequestMessageImpl message = new HttpRequestMessageImpl(new SessionContext(), "HTTP/1.1", "POST", "/some/where", new HttpQueryParams(), new Headers(), "192.168.0.2", "https", 7002, "localhost", new InetSocketAddress("api.netflix.com", 443)); assertEquals(message.getClientDestinationPort(), Optional.of(443)); }
Source:
<code>public void storePrefs() { <START> <END> List<String> externalStyles = styles.stream().filter(style -> !style.internalStyleProperty().get()).map(this::toOOBibStyle).map(OOBibStyle::getPath).collect(Collectors.toList()); preferences.setExternalStyles(externalStyles); preferences.setCurrentStyle(selectedItem.getValue().getStylePath()); preferencesService.setOpenOfficePreferences(preferences); }</code><technical_language>delete empty line</technical_language>

Target:
public void storePrefs() { List<String> externalStyles = styles.stream().map(this::toOOBibStyle).filter(style->!style.isInternalStyle()).map(OOBibStyle::getPath).collect(Collectors.toList()); preferences.setExternalStyles(externalStyles); preferences.setCurrentStyle(selectedItem.getValue().getStylePath()); preferencesService.setOpenOfficePreferences(preferences); }
Source:
<code>protected void configureMetaStore(HiveConf conf) { try { Class.forName(JDBCDriver.class.getName()); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } metaStorageUrl = "jdbc:hsqldb:mem:" + UUID.randomUUID().toString(); <START> hiveConf.set("datanucleus.connectiondrivername", "org.hsqldb.jdbc.JDBCDriver"); <END> hiveConf.set("javax.jdo.option.ConnectionDriverName", "org.hsqldb.jdbc.JDBCDriver"); hiveConf.set("datanucleus.connectionPoolingType", "None"); conf.setBoolVar(METASTORE_VALIDATE_CONSTRAINTS, true); conf.setBoolVar(METASTORE_VALIDATE_COLUMNS, true); conf.setBoolVar(METASTORE_VALIDATE_TABLES, true); }</code><technical_language>JDBCDriver.class.getName() in place a string constant in places. Stick way. I prefer class.getName() myself</technical_language>

Target:
protected void configureMetaStore(HiveConf conf) { String jdbcDriver = JDBCDriver.class.getName(); try { Class.forName(jdbcDriver); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } metaStorageUrl = "jdbc:hsqldb:mem:" + UUID.randomUUID().toString(); hiveConf.set("datanucleus.connectiondrivername", jdbcDriver); hiveConf.set("javax.jdo.option.ConnectionDriverName", jdbcDriver); hiveConf.set("datanucleus.connectionPoolingType", "None"); conf.setBoolVar(METASTORE_VALIDATE_CONSTRAINTS, true); conf.setBoolVar(METASTORE_VALIDATE_COLUMNS, true); conf.setBoolVar(METASTORE_VALIDATE_TABLES, true); }
Source:
<code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View v = inflater.inflate(R.layout.dialog_addshow, container, false); ButterKnife.inject(this, v); mButtonNegative.setText(R.string.dont_add_show); mButtonNegative.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); mButtonPositive.setText(R.string.action_shows_add); mButtonPositive.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if(mAdapterCallback != null) { mShow.isAdded = true; <START> mAdapterCallback.notifyDataSetChanged(); <END> } mListener.onAddShow(mShow); dismiss(); } }); ButterKnife.apply(labelViews, VISIBLE, false); return v; }</code><technical_language>post event relevant TraktAddFragment reacts to. need hang adapter</technical_language>

Target:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final View v = inflater.inflate(R.layout.dialog_addshow, container, false); ButterKnife.inject(this, v); mButtonNegative.setText(R.string.dont_add_show); mButtonNegative.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); mButtonPositive.setText(R.string.action_shows_add); mButtonPositive.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mShow.isAdded = true; EventBus.getDefault().post(new AddShowEvent()); mListener.onAddShow(mShow); dismiss(); } }); ButterKnife.apply(labelViews, VISIBLE, false); return v; }
Source:
<code>public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("CodeSystem [oid="); builder.append(oid); builder.append(", name="); builder.append(name); builder.append(", shortName="); builder.append(shortName); builder.append(", organizationLink="); builder.append(organizationLink); builder.append(", primaryLanguage="); builder.append(primaryLanguage); builder.append(", citation="); builder.append(citation); builder.append("]"); builder.append(", branchPath="); builder.append(branchPath); builder.append("]"); builder.append(", iconPath="); builder.append(iconPath); builder.append("]"); builder.append(", repositoryUuid="); builder.append(repositoryUuid); <START> builder.append("]"); <END> return builder.toString(); }</code><technical_language>Add extensionMap toString()</technical_language>

Target:
public String toString() { final StringBuilder builder = new StringBuilder(); builder.append("CodeSystem [oid="); builder.append(oid); builder.append(", name="); builder.append(name); builder.append(", shortName="); builder.append(shortName); builder.append(", organizationLink="); builder.append(organizationLink); builder.append(", primaryLanguage="); builder.append(primaryLanguage); builder.append(", citation="); builder.append(citation); builder.append(", branchPath="); builder.append(branchPath); builder.append(", iconPath="); builder.append(iconPath); builder.append(", repositoryUuid="); builder.append(repositoryUuid); builder.append(", additionalProperties="); builder.append(additionalProperties); builder.append("]"); return builder.toString(); }
Source:
<code>public void onPerfectMatchSearchedEvent(String search, boolean notEqualsSearch) { clearLists(); dataObjectFieldsMap .entrySet() .stream() .filter(entry -> filterTerm(entry.getKey(), search, notEqualsSearch)) .forEach(filteredEntry -> addDataObjectListGroupItemView(filteredEntry.getKey(), filteredEntry.getValue())); simpleJavaTypeFieldsMap .entrySet() .stream() .filter(entry -> filterTerm(entry.getKey(), search, notEqualsSearch)) .forEach(filteredEntry -> addSimpleJavaTypeListGroupItemView(filteredEntry.getKey(), filteredEntry.getValue())); instanceFieldsMap .entrySet() .stream() .filter(entry -> filterTerm(entry.getKey(), search, notEqualsSearch)) .forEach(filteredEntry -> addInstanceListGroupItemView(filteredEntry.getKey(), filteredEntry.getValue())); simpleJavaInstanceFieldsMap .entrySet() .stream() .filter(entry -> filterTerm(entry.getKey(), search, notEqualsSearch)) .forEach(filteredEntry -> addSimpleJavaInstanceListGroupItemView(filteredEntry.getKey(), filteredEntry.getValue())); updateSeparators(); if (!notEqualsSearch) { <START> checkInstanceIsAssigned(search); <END> } }</code><technical_language>update method name checking action inside? return boolean current do action result this place? do think? Do mix not? I wrong</technical_language>

Target:
public void onPerfectMatchSearchedEvent(String search, boolean notEqualsSearch) { clearLists(); dataObjectFieldsMap .entrySet() .stream() .filter(entry -> filterTerm(entry.getKey(), search, notEqualsSearch)) .forEach(filteredEntry -> addDataObjectListGroupItemView(filteredEntry.getKey(), filteredEntry.getValue())); simpleJavaTypeFieldsMap .entrySet() .stream() .filter(entry -> filterTerm(entry.getKey(), search, notEqualsSearch)) .forEach(filteredEntry -> addSimpleJavaTypeListGroupItemView(filteredEntry.getKey(), filteredEntry.getValue())); instanceFieldsMap .entrySet() .stream() .filter(entry -> filterTerm(entry.getKey(), search, notEqualsSearch)) .forEach(filteredEntry -> addInstanceListGroupItemView(filteredEntry.getKey(), filteredEntry.getValue())); simpleJavaInstanceFieldsMap .entrySet() .stream() .filter(entry -> filterTerm(entry.getKey(), search, notEqualsSearch)) .forEach(filteredEntry -> addSimpleJavaInstanceListGroupItemView(filteredEntry.getKey(), filteredEntry.getValue())); updateSeparators(); }
Source:
<code>private ValueContext<?, Object> buildNewLocalExecutionContext(CascadingMetaData cascadingMetaData, ValueContext<?, ?> valueContext, Object value) { ValueContext<?, Object> newValueContext; Contracts.assertNotNull( value, "value cannot be null" ); newValueContext = ValueContext.getLocalExecutionContext( validatorScopedContext.getParameterNameProvider(), value, <START> cascadingMetaData.getBeanMetaDataForCascadable( beanMetaDataManager, value ), <END> valueContext.getPropertyPath() ); newValueContext.setCurrentValidatedValue( value ); return newValueContext; }</code><technical_language>Do expect metadata for free form case in beanMetaDataManager? If not, I suspect push beanMetaDataManager constructor (and 2 implementations of CascadingMetaData in end). in mind for that</technical_language>

Target:
private ValueContext<?, Object> buildNewLocalExecutionContext(CascadingMetaData cascadingMetaData, ValueContext<?, ?> valueContext, Object value) { ValueContext<?, Object> newValueContext; Contracts.assertNotNull( value, "value cannot be null" ); newValueContext = ValueContext.getLocalExecutionContext( validatorScopedContext.getParameterNameProvider(), value, cascadingMetaData.getBeanMetaDataForCascadable( constraintMetaDataManager, value ), valueContext.getPropertyPath() ); newValueContext.setCurrentValidatedValue( value ); return newValueContext; }
Source:
<code>private static void closeIterator(Iterator<?> iter) { <START> if (iter != null && iter instanceof CloseableIterator) { <END> ((CloseableIterator) iter).close(); } }</code><technical_language>unnecessary null check</technical_language>

Target:
private static void closeIterator(Iterator<?> iter) { if (iter instanceof CloseableIterator) { ((CloseableIterator) iter).close(); } }
Source:
<code>public void testAWSConfigurationWithJSONObject() { JSONObject jsonObject; try { jsonObject = new JSONObject("{\n" + " \"UserAgent\": \"aws-amplify-cli/0.1.0\",\n" + " \"Version\": \"1.0\",\n" + " \"IdentityManager\": {\n" + " \"Default\": {}\n" + " },\n" + " \"AppSync\": {\n" + " \"Default\": {\n" + " \"ApiUrl\": \"redacted\",\n" + " \"Region\": \"redacted\",\n" + " \"AuthMode\": \"API_KEY\",\n" + " \"ApiKey\": \"da2-xyz\",\n" + " \"ClientDatabasePrefix\": \"redacted\"\n" + " }\n" + " },\n" + " \"CredentialsProvider\": {\n" + " \"CognitoIdentity\": {\n" + " \"Default\": {\n" + " \"PoolId\": \"redacted\",\n" + " \"Region\": \"redacted\"\n" + " }\n" + " }\n" + " }\n" + "}"); <START> AWSConfiguration awsConfiguration = new AWSConfiguration(jsonObject); <END> assertNotNull(awsConfiguration); assertNotNull(awsConfiguration.optJsonObject("AppSync")); assertEquals("API_KEY", awsConfiguration.optJsonObject("AppSync").getString("AuthMode")); } catch (JSONException e) { fail("Error in constructing AWSConfiguration." + e.getLocalizedMessage()); } }</code><technical_language>Nitpick: a test try construct a CognitoCachingCredentialsProvider client reads expected</technical_language>

Target:
public void testAWSConfigurationWithJSONObject() { try { JSONObject jsonObject = new JSONObject(jsonString); AWSConfiguration awsConfiguration = new AWSConfiguration(jsonObject); assertNotNull(awsConfiguration); assertNotNull(awsConfiguration.optJsonObject("AppSync")); assertEquals("API_KEY", awsConfiguration.optJsonObject("AppSync").getString("AuthMode")); } catch (JSONException e) { fail("Error in constructing AWSConfiguration." + e.getLocalizedMessage()); } }
Source:
<code>public Map<String, Boolean> getParameters() { <START> Map<String, Boolean> headers = new HashMap<>(); <END> headers.put(ARTIFACT_FILE_NAME, true); headers.put(ARTIFACT_FOLDER_NAME, false); headers.put(UID, true); return headers; }</code><technical_language>avoid creating a new HashMap call here</technical_language>

Target:
public Map<String, Boolean> getParameters() { return params; }
Source:
<code>protected MessageHandler newRequestHandler() { return message -> { String reply = message.getReplyTo(); if (reply == null || reply.isEmpty()) { LOGGER.warn("Discarding invalid NATS request (no reply)"); return; } String correlationId; try { correlationId = HeaderUtils.decodeFromFrame(message.getData()).get(FContext.CID_HEADER); } catch (TException e) { LOGGER.warn("Discarding invalid NATS request, could not get FContext headers", e); return; } <START> eventHandler.onNewRequest(correlationId); <END> executorService.execute( new Request(message.getData(), System.currentTimeMillis(), message.getReplyTo(), highWatermark, inputProtoFactory, outputProtoFactory, processor, conn, correlationId)); }; }</code><technical_language>unfortunate unconditionally deserialize headers here, especially default handler correlation ID. thought deeply, propagate this FContext this watermark/logging logic done a standard middleware (and optionally disabled in library altogether). For example, propagate timestamp (in some form) inbound FProtocol readRequestHeader propagate some kind of non-serialized attributes FContext. for timestamps themselves, System.currentTimeMillis() monotonic time issue resolved in time.Time, granularity issues solved in Instant in Java 9. Instant monotonic time stored non-serialized attribute (or some kind of opaque FTimestamp unifies time.Time does)</technical_language>

Target:
protected MessageHandler newRequestHandler() { return message -> { String reply = message.getReplyTo(); if (reply == null || reply.isEmpty()) { LOGGER.warn("Discarding invalid NATS request (no reply)"); return; } Map<Object, Object> ephemeralProperties = new HashMap<>(); this.eventHandler.onRequestReceived(ephemeralProperties); executorService.execute( new Request(message.getData(), message.getReplyTo(), inputProtoFactory, outputProtoFactory, processor, conn, eventHandler, ephemeralProperties)); }; }
Source:
<code>private void validateTag(String xmlTag) { Conditions.checkNotNullOrEmpty(xmlTag, "xmlTag"); <START> boolean valid = false; <END> if (xmlTag.compareTo("resourceDoc") == 0) { valid = true; } else if (xmlTag.compareTo("applicationDocs") == 0) { valid = true; } else if (xmlTag.compareTo("grammars") == 0) { valid = true; } if (!valid) { throw new OseeArgumentException("Invalid resource document tag"); } }</code><technical_language>This a C style equality check. Also, account for case mismatches. Conside if("resourceDoc".equalsIgnoreCase(xmlTag))... instead</technical_language>

Target:
private void validateTag(String xmlTag) { Conditions.checkNotNullOrEmpty(xmlTag, "xmlTag"); boolean valid = false; if (xmlTag.equals("resourceDoc")) { valid = true; } else if (xmlTag.equals("applicationDocs")) { valid = true; } else if (xmlTag.equals("grammars")) { valid = true; } if (!valid) { throw new OseeArgumentException("Invalid resource document tag"); } }
Source:
<code>public void nextTuple() { BufferedReader br = null; try { String line; br = new BufferedReader(Files.newBufferedReader(Paths.get(path), StandardCharsets.UTF_8)); while ((line = br.readLine()) != null) { String[] result = line.split(delimiter); if (result.length != 2) { LOG.error("Format of input file not as expected. Expecting separated first name and last name", delimiter); } else { Map<String, Object> event = new HashMap<>(); event.put(FIRST_NAME, result[0].trim()); event.put(LAST_NAME, result[1].trim()); List<Object> values = new ArrayList<>(); <START> values.add(new MyStreamlineEvent(event, outputStream)); <END> spoutOutputCollector.emit(outputStream, values, UUID.randomUUID()); } } } catch (IOException e) { LOG.error("Got exception while reading file at {}", path); throw new RuntimeException(e); } finally { if (br != null) try { br.close(); } catch (IOException e) { LOG.error("Got exception while closing buffered reader"); throw new RuntimeException(e); } } }</code><technical_language>do require user construct a MyStreamlineEvent class?. able default implementation internally</technical_language>

Target:
public void nextTuple() { try (BufferedReader br = new BufferedReader(Files.newBufferedReader(Paths.get(path), StandardCharsets.UTF_8))) { String line; while ((line = br.readLine()) != null) { String[] result = line.split(delimiter); if (result.length != 2) { LOG.error("Format of input file not as expected. Expecting separated first name and last name", delimiter); } else { List<Object> values = new ArrayList<>(); values.add(StreamlineEventImpl.builder().sourceStream(outputStream).put(FIRST_NAME, result[0].trim()).put(LAST_NAME, result[1].trim()) .build()); spoutOutputCollector.emit(outputStream, values, UUID.randomUUID()); } } } catch (IOException e) { LOG.error("Got exception while reading file at {}", path); throw new RuntimeException(e); } }
Source:
<code>protected CommandStack getCommandStack(IWorkbenchPart part, Object input) { <START> Object helper <END> = getInputType(input); if (null != helper) { return SystemManager.INSTANCE.getCommandStack(((Device) helper).getAutomationSystem()); } return null; }</code><technical_language>This Device, cast away</technical_language>

Target:
protected CommandStack getCommandStack(IWorkbenchPart part, Object input) { Device helper = getInputType(input); if (null != helper) { return SystemManager.INSTANCE.getCommandStack(helper.getAutomationSystem()); } return null; }
Source:
<code><START> public ArrayList<CategoryPill.Data> getCategoriesFromSite(final String siteId, User user) { <END> return new Categories(user).execute(CreateCategoryContext.defaultContextUsing(siteId, "")); }</code><technical_language>Interface for return signature</technical_language>

Target:
public List<CategoryPill.Data> getCategoriesFromSite(final String siteId, User user) { return new Categories(user).execute(CreateCategoryContext.defaultContextUsing(siteId, "")); }
Source:
<code>public void goToLastEvent() throws CTFException { <START> seek(getEndTime()); <END> while (fPrio.size() > 1) { advance(); } }</code><technical_language>Is seek requires a timestamp in cycles</technical_language>

Target:
public void goToLastEvent() throws CTFException { seek(fTrace.timestampNanoToCycles(getEndTime())); while (fPrio.size() > 1) { advance(); } }
Source:
<code>public boolean isFulltextSearchDisabled() { <START> return (isFulltextDisabled() || fulltextConfiguration.fulltextSearchDisabled); <END> }</code><technical_language>Remove extra parentheses</technical_language>

Target:
public boolean isFulltextSearchDisabled() { return isFulltextDisabled() || fulltextConfiguration.fulltextSearchDisabled; }
Source:
<code>public final void indexingProgress(IndexingProgressStats stats) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { <START> WorkbenchWindow workbenchWindow = (WorkbenchWindow)PlatformUI.getWorkbench().getActiveWorkbenchWindow(); <END> StatusLineManager statusLineManager = workbenchWindow.getStatusLineManager(); if(stats.getStatsSum()==0) { statusLineManager.setMessage("CQuery : Idle"); } else { statusLineManager.setMessage("CQuery : Busy | "+stats.getStatsSum()+" Jobs"); } } }); }</code><technical_language>sufficient display status in active window. this patch, if I open a window Window -> New Window, window is currently active (focused) status line updated, other stuck a stale message time focused. Instead, IWorkbench.getWorkbenchWindows() show status in windows</technical_language>

Target:
public final void indexingProgress(IndexingProgressStats stats) { Display.getDefault().asyncExec(new Runnable() { @Override public void run() { final String cqueryStatusFieldId = "org.eclipse.lsp4e.cpp.status"; final int width = 28; IWorkbenchWindow[] Workbenchwindows = PlatformUI.getWorkbench().getWorkbenchWindows(); for (IWorkbenchWindow window : Workbenchwindows) { StatusLineManager statusLine = ((WorkbenchWindow) window).getStatusLineManager(); if (statusLine.find(cqueryStatusFieldId) != null) { statusLine.remove(cqueryStatusFieldId); } StatusLineContributionItem cqueryStatusField = new StatusLineContributionItem(cqueryStatusFieldId, width); statusLine.add(cqueryStatusField); String msg = stats.getTotalJobs() > 0 ? NLS.bind(Messages.CqueryStateBusy, stats.getTotalJobs()) : Messages.CqueryStateIdle; cqueryStatusField.setText(msg); } } }); }
Source:
<code>public void setProperties(Properties props) throws StandardException{ properties=props; Enumeration e=properties.keys(); while(e.hasMoreElements()){ String key=(String)e.nextElement(); String value=(String)properties.get(key); switch(key){ case "joinOrder": if(StringUtil.SQLEqualsIgnoreCase(value,"fixed")){ fixedJoinOrder=true; }else if(StringUtil.SQLEqualsIgnoreCase(value,"unfixed")){ fixedJoinOrder=false; }else{ throw StandardException.newException(SQLState.LANG_INVALID_JOIN_ORDER_SPEC,value); } break; case "useStatistics": if(StringUtil.SQLEqualsIgnoreCase(value,"true")){ useStatistics=true; }else if(StringUtil.SQLEqualsIgnoreCase(value,"false")){ useStatistics=false; }else{ throw StandardException.newException(SQLState.LANG_INVALID_STATISTICS_SPEC,value); } break; case "tableLimitForExhaustiveSearch": try { tableLimitForExhaustiveSearch = Integer.parseUnsignedInt(value); } catch (NumberFormatException nfe) { throw StandardException.newException(SQLState.LANG_INVALID_TABLE_LIMIT_FOR_EXHAUSTIVE_SEARCH, value); } <START> if (tableLimitForExhaustiveSearch == 0) <END> throw StandardException.newException(SQLState.LANG_INVALID_TABLE_LIMIT_FOR_EXHAUSTIVE_SEARCH, value); break; default: throw StandardException.newException(SQLState.LANG_INVALID_FROM_LIST_PROPERTY,key,value); } } }</code><technical_language>I change <=0</technical_language>

Target:
public void setProperties(Properties props) throws StandardException{ properties=props; Enumeration e=properties.keys(); while(e.hasMoreElements()){ String key=(String)e.nextElement(); String value=(String)properties.get(key); switch(key){ case "joinOrder": if(StringUtil.SQLEqualsIgnoreCase(value,"fixed")){ fixedJoinOrder=true; }else if(StringUtil.SQLEqualsIgnoreCase(value,"unfixed")){ fixedJoinOrder=false; }else{ throw StandardException.newException(SQLState.LANG_INVALID_JOIN_ORDER_SPEC,value); } break; case "useStatistics": if(StringUtil.SQLEqualsIgnoreCase(value,"true")){ useStatistics=true; }else if(StringUtil.SQLEqualsIgnoreCase(value,"false")){ useStatistics=false; }else{ throw StandardException.newException(SQLState.LANG_INVALID_STATISTICS_SPEC,value); } break; case "tableLimitForExhaustiveSearch": try { tableLimitForExhaustiveSearch = Integer.parseInt(value); } catch (NumberFormatException nfe) { throw StandardException.newException(SQLState.LANG_INVALID_TABLE_LIMIT_FOR_EXHAUSTIVE_SEARCH, value); } if (tableLimitForExhaustiveSearch <= 0) throw StandardException.newException(SQLState.LANG_INVALID_TABLE_LIMIT_FOR_EXHAUSTIVE_SEARCH, value); break; default: throw StandardException.newException(SQLState.LANG_INVALID_FROM_LIST_PROPERTY,key,value); } } }
Source:
<code>public void testGetBikeStationsTampa() { Application.get().setCurrentRegion(MockRegion.getTampa(getContext()), false); OtpBikeStationRequest request = OtpBikeStationRequest.newRequest(getContext(), null, null); OtpBikeStationResponse response = request.call(); assertNotNull(response); assertNotNull(response.stations); assertEquals(133, response.stations.size()); <START> for(BikeRentalStation station: response.stations) { <END> assertNotNull(station.name); } }</code><technical_language>This test is a good start - get a reference element in list assert of fields in raw JSON match pull out of station object. ~~~ "id": "bike_3566", "name": "B-1165", "x": -82.40730666666667, "y": 28.066505, "bikesAvailable": 1, "spacesAvailable": 0, "allowDropoff": false, "isFloatingBike": true, "networks": [ "default" ], "realTimeData": true }, ~~~ Jackson is deserializing fields correctly, missing (like new isFloatingBike</technical_language>

Target:
public void testGetBikeStationsTampa() { Application.get().setCurrentRegion(MockRegion.getTampa(getContext()), false); OtpBikeStationRequest request = OtpBikeStationRequest.newRequest(getContext(), null, null); OtpBikeStationResponse response = request.call(); assertNotNull(response); assertNotNull(response.stations); assertEquals(133, response.stations.size()); for (BikeRentalStation station: response.stations) { assertNotNull(station.name); } assertFirstStationIsCorrect(response.stations.get(0)); }
Source:
<code><START> private static byte[] hexStringToByteArray(String s) { <END> int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i < len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character.digit(s.charAt(i+1), 16)); } return data; }</code><technical_language>This is 'only' test code decide do this Apache Codec</technical_language>

Target:
private static byte[] hexStringToByteArray(String s) { try { return Hex.decodeHex(s.toCharArray()); } catch (DecoderException ex) { throw new RuntimeException("Error decoding hex data: " + s); } }
Source:
<code>void propagateDraw (long container, long cairo) { if (container == fixedHandle) { long list = GTK.gtk_container_get_children (container); long temp = list; while (temp != 0) { long child = OS.g_list_data (temp); if (child != 0) { Widget widget = display.getWidget (child); if (widget != this) { if <START> (noChildDrawing != <END> null) { Boolean childLowered = childrenLowered.get(widget); if (childLowered == null) { childrenLowered.put(widget, false); childLowered = false; } GtkAllocation allocation = new GtkAllocation (); GTK.gtk_widget_get_allocation(child, allocation); if (allocation.y < 0) { if (!childLowered) { if (GTK.GTK4) { long surface = gtk_widget_get_surface(child); GDK.gdk_surface_lower(surface); } else { long window = gtk_widget_get_window(child); GDK.gdk_window_lower(window); } childrenLowered.put(widget, true); } } else { if (childLowered) { if (GTK.GTK4) { long surface = gtk_widget_get_surface(child); GDK.gdk_surface_raise(surface); } else { long window = gtk_widget_get_window(child); GDK.gdk_window_raise(window); } childrenLowered.put(widget, false); } GTK.gtk_container_propagate_draw(container, child, cairo); } } else { GTK.gtk_container_propagate_draw(container, child, cairo); } } } temp = OS.g_list_next (temp); } OS.g_list_free (list); } }</code><technical_language>proposed change content of noChildDrawing change boolean remove extra code retrieve dimension in tree/table, this place dimensions</technical_language>

Target:
void propagateDraw (long container, long cairo) { if (container == fixedHandle) { long list = GTK.gtk_container_get_children (container); long temp = list; while (temp != 0) { long child = OS.g_list_data (temp); if (child != 0) { Widget widget = display.getWidget (child); if (widget != this) { if (noChildDrawing) { Boolean childLowered = childrenLowered.get(widget); if (childLowered == null) { childrenLowered.put(widget, false); childLowered = false; } GtkAllocation allocation = new GtkAllocation (); GTK.gtk_widget_get_allocation(child, allocation); if (allocation.y < 0) { if (!childLowered) { if (GTK.GTK4) { long surface = gtk_widget_get_surface(child); GDK.gdk_surface_lower(surface); } else { long window = gtk_widget_get_window(child); GDK.gdk_window_lower(window); } childrenLowered.put(widget, true); } } else { if (childLowered) { if (GTK.GTK4) { long surface = gtk_widget_get_surface(child); GDK.gdk_surface_raise(surface); } else { long window = gtk_widget_get_window(child); GDK.gdk_window_raise(window); } childrenLowered.put(widget, false); } GTK.gtk_container_propagate_draw(container, child, cairo); } } else { GTK.gtk_container_propagate_draw(container, child, cairo); } } } temp = OS.g_list_next (temp); } OS.g_list_free (list); } }
Source:
<code>public String notFound( HttpServletRequest request, @CurrentUser Integer currentUserId, @RequestAttribute(name = RequestDispatcher.ERROR_REQUEST_URI, required = false) String page, @RequestHeader(name = "referer", required = false) String referer, @RequestHeader(name = "user-agent", required = false) String agent) { String ip = request.getRemoteAddr(); String method = request.getMethod(); siteService.logAboutAbsentPage(page, method, currentUserId, ip, referer, agent); <START> return SiteUrl.COMMON_ERROR_PAGE; <END> }</code><technical_language>This is a URL accessed a path a file. So: 1) a path a file belong a class URLs 2) need a constant for a file path in this case. duplicate /error/status-code string 3 times :)</technical_language>

Target:
public String notFound( HttpServletRequest request, @CurrentUser Integer currentUserId, @RequestAttribute(name = RequestDispatcher.ERROR_REQUEST_URI, required = false) String page, @RequestHeader(name = "referer", required = false) String referer, @RequestHeader(name = "user-agent", required = false) String agent) { String ip = request.getRemoteAddr(); String method = request.getMethod(); siteService.logAboutAbsentPage(page, method, currentUserId, ip, referer, agent); return "error/status-code"; }
Source:
<code>private void addPool(InetSocketAddress server) { <START> int currentPoolNumber = currentPools.size() + 1; <END> addPool(server, new CassandraClientPoolingContainer(server, config, currentPoolNumber)); }</code><technical_language>I a problems this approach I misunderstanding something. 1) currentPools modified while looping adding Pools. This metrics re-registered (causing exceptions). maintain a separate counter is increased ( AtomicInteger.incrementAndGet ) avoid duplicate metrics. 2) product node is registering pool1.metric, pool2.metric is ordering guarantee (or config start up) product node1's pool1 metrics for a C* host node2's pool1 metrics. do this, sorting host names registering help. 3) a product node is bounced register pools in a order graphs jump, this is ok long aware of it. Sorting helps try order same</technical_language>

Target:
void addPool(InetSocketAddress server) { int currentPoolNumber = cassandraHosts.indexOf(server) + 1; addPool(server, new CassandraClientPoolingContainer(server, config, currentPoolNumber)); }
Source:
<code>public List<String> getFieldNames() { <START> return ImmutableList.copyOf(fieldNames); <END> }</code><technical_language>Collections.unmodifiableList similar other places</technical_language>

Target:
public List<String> getFieldNames() { return Collections.unmodifiableList(fieldNames); }
Source:
<code>private static boolean shouldEnforceHardTabs(FileSystemItem item) { if (item == null) return false; if ("Makefile".equals(item.getName()) || "Makevars".equals(item.getName()) || <START> ".tsv".equals(item.getExtension())) <END> { return true; } return false; }</code><technical_language>Do need limit this .in/.win for Makefile before</technical_language>

Target:
private static boolean shouldEnforceHardTabs(FileSystemItem item) { if (item == null) return false; String[] requiresHardTabs = new String[] { "Makefile", "Makefile.in", "Makefile.win", "Makevars", "Makevars.in", "Makevars.win" }; for (String file : requiresHardTabs) if (file.equals(item.getName())) return true; if (".tsv".equals(item.getExtension())) return true; return false; }
Source:
<code>private void addExitMenu() { final boolean isMac = SystemProperties.isMac(); final JMenuItem leaveGameMenuExit = new JMenuItem(SwingAction.of("Leave Game", e -> frame.leaveGame())); leaveGameMenuExit.setMnemonic(KeyEvent.VK_L); if (isMac) { leaveGameMenuExit.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_L, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); } else { leaveGameMenuExit.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_Q, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); } add(leaveGameMenuExit); if (isMac) { <START> MacOsIntegration.setQuitHandler(() -> frame.shutdown()); <END> } else { final JMenuItem menuFileExit = new JMenuItem(SwingAction.of("Exit Program", e -> frame.shutdown())); menuFileExit.setMnemonic(KeyEvent.VK_E); add(menuFileExit); } }</code><technical_language>shutdown returns a boolean, this change unecessary</technical_language>

Target:
private void addExitMenu() { final boolean isMac = SystemProperties.isMac(); final JMenuItem leaveGameMenuExit = new JMenuItem(SwingAction.of("Leave Game", e -> frame.leaveGame())); leaveGameMenuExit.setMnemonic(KeyEvent.VK_L); if (isMac) { leaveGameMenuExit.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_L, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); } else { leaveGameMenuExit.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_Q, Toolkit.getDefaultToolkit().getMenuShortcutKeyMaskEx())); } add(leaveGameMenuExit); if (isMac) { MacOsIntegration.setQuitHandler(frame); } else { final JMenuItem menuFileExit = new JMenuItem(SwingAction.of("Exit Program", e -> frame.shutdown())); menuFileExit.setMnemonic(KeyEvent.VK_E); add(menuFileExit); } }
Source:
<code>protected VDSExceptionBase createDefaultConcreteException(String errorMessage) { VDSExceptionBase outEx = new IrsOperationFailedNoFailoverException(errorMessage); <START> return outEx; <END> }</code><technical_language>inline return statement</technical_language>

Target:
protected VDSExceptionBase createDefaultConcreteException(String errorMessage) { return new IrsOperationFailedNoFailoverException(errorMessage); }
Source:
<code>public boolean runAllParagraphs(String noteId, List<Map<String, Object>> paragraphs, ServiceContext context, ServiceCallback<Paragraph> callback) throws IOException { if (!checkPermission(noteId, Permission.RUNNER, Message.OP.RUN_ALL_PARAGRAPHS, context, callback)) { return false; } Note note = notebook.getNote(noteId); if (note == null) { callback.onFailure(new NoteNotFoundException(noteId), context); return false; } note.setRunning(true); try { if (paragraphs != null) { for (Map<String, Object> raw : paragraphs) { String paragraphId = (String) raw.get("id"); if (paragraphId == null) { <START> continue; <END> } String text = (String) raw.get("paragraph"); String title = (String) raw.get("title"); Map<String, Object> params = (Map<String, Object>) raw.get("params"); Map<String, Object> config = (Map<String, Object>) raw.get("config"); if (!runParagraph(noteId, paragraphId, title, text, params, config, false, true, context, callback)) { return false; } } } else { try { note.runAll(context.getAutheInfo(), true); return true; } catch (Exception e) { LOGGER.warn("Fail to run note: " + note.getName(), e); return false; } } } finally { note.setRunning(false); } return true; }</code><technical_language>add a debug message here</technical_language>

Target:
public boolean runAllParagraphs(String noteId, List<Map<String, Object>> paragraphs, ServiceContext context, ServiceCallback<Paragraph> callback) throws IOException { if (!checkPermission(noteId, Permission.RUNNER, Message.OP.RUN_ALL_PARAGRAPHS, context, callback)) { return false; } Note note = notebook.getNote(noteId); if (note == null) { callback.onFailure(new NoteNotFoundException(noteId), context); return false; } note.setRunning(true); try { if (paragraphs != null) { for (Map<String, Object> raw : paragraphs) { String paragraphId = (String) raw.get("id"); if (paragraphId == null) { LOGGER.warn("No id found in paragraph json: " + raw); continue; } try { String text = (String) raw.get("paragraph"); String title = (String) raw.get("title"); Map<String, Object> params = (Map<String, Object>) raw.get("params"); Map<String, Object> config = (Map<String, Object>) raw.get("config"); if (!runParagraph(noteId, paragraphId, title, text, params, config, false, true, context, callback)) { return false; } } catch (Exception e) { throw new IOException("Fail to run paragraph json: " + raw); } } } else { try { note.runAll(context.getAutheInfo(), true); return true; } catch (Exception e) { LOGGER.warn("Fail to run note: " + note.getName(), e); return false; } } } finally { note.setRunning(false); } return true; }
Source:
<code>private Composite createTabSkeleton(TabFolder tabFolder, String tabLabel, String introText) { TabItem tbtmMain = new TabItem(tabFolder, SWT.NONE); tbtmMain.setText(tabLabel); Composite tabComposite = new Composite(tabFolder, SWT.NONE); tbtmMain.setControl(tabComposite); GridLayout layout = new GridLayout(1, true); layout.verticalSpacing = VERTICAL_SPACING_GRID; tabComposite.setLayout(layout); GridData layoutData = new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1); tabComposite.setLayoutData(layoutData); Label introductionText = new Label(tabComposite, SWT.WRAP); layoutData = <START> new GridData(SWT.FILL, SWT.FILL, true, false); <END> layoutData.widthHint = INTRO_TEXT_WIDTH_HINT; introductionText.setLayoutData(layoutData); introductionText.setText(introText); return tabComposite; }</code><technical_language>want consider GridDataFactory. If yes, sense in pages create a bit more complex grid data objects</technical_language>

Target:
private Composite createTabSkeleton(TabFolder tabFolder, String tabLabel, String introText) { TabItem tbtmMain = new TabItem(tabFolder, SWT.NONE); tbtmMain.setText(tabLabel); Composite tabComposite = new Composite(tabFolder, SWT.NONE); tbtmMain.setControl(tabComposite); GridLayout layout = new GridLayout(1, true); tabComposite.setLayout(layout); GridData layoutData = new GridData(SWT.FILL, SWT.FILL, false, false, 1, 1); tabComposite.setLayoutData(layoutData); Label introductionText = new Label(tabComposite, SWT.WRAP); GridDataFactory.fillDefaults().grab(true, false).hint(INTRO_TEXT_WIDTH_HINT, SWT.DEFAULT) .applyTo(introductionText); introductionText.setText(introText); return tabComposite; }
Source:
<code>public PagarMeResponse execute() throws PagarMeException { final StringBuilder builder = new StringBuilder(); int responseCode = -1; try { if (method.equalsIgnoreCase(HttpMethod.POST) || method.equalsIgnoreCase(HttpMethod.PUT) || method.equalsIgnoreCase(HttpMethod.DELETE)) { httpClient.setDoOutput(true); if (parameters.size() > 0) { <START> String json = JSONUtils.getInterpreter().toJson(parameters); <END> final byte[] payload = JSONUtils.getInterpreter().toJson(parameters).getBytes(); httpClient.addRequestProperty("Content-Type", "application/json"); httpClient.addRequestProperty("Content-Length", String.valueOf(payload.length)); final OutputStream os = httpClient.getOutputStream(); os.write(payload); os.flush(); } } try { is = httpClient.getInputStream(); responseCode = httpClient.getResponseCode(); } catch (IOException e) { is = httpClient.getErrorStream(); responseCode = httpClient.getResponseCode(); } final BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line; while ((line = reader.readLine()) != null) { builder.append(line); builder.append('\r'); } reader.close(); httpClient.disconnect(); return new PagarMeResponse(responseCode, JSONUtils.getInterpreter().fromJson(builder.toString(), JsonElement.class)); } catch (Exception e) { if (e instanceof JsonSyntaxException) { throw new PagarMeException(responseCode, url, method, builder.toString()); } throw PagarMeException.buildWithError(e); } }</code><technical_language>Is necessary</technical_language>

Target:
public PagarMeResponse execute() throws PagarMeException { final StringBuilder builder = new StringBuilder(); int responseCode = -1; try { if (method.equalsIgnoreCase(HttpMethod.POST) || method.equalsIgnoreCase(HttpMethod.PUT) || method.equalsIgnoreCase(HttpMethod.DELETE)) { httpClient.setDoOutput(true); if (parameters.size() > 0) { final byte[] payload = JSONUtils.getInterpreter().toJson(parameters).getBytes(); httpClient.addRequestProperty("Content-Type", "application/json"); httpClient.addRequestProperty("Content-Length", String.valueOf(payload.length)); final OutputStream os = httpClient.getOutputStream(); os.write(payload); os.flush(); } } try { is = httpClient.getInputStream(); responseCode = httpClient.getResponseCode(); } catch (IOException e) { is = httpClient.getErrorStream(); responseCode = httpClient.getResponseCode(); } final BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8")); String line; while ((line = reader.readLine()) != null) { builder.append(line); builder.append('\r'); } reader.close(); httpClient.disconnect(); return new PagarMeResponse(responseCode, JSONUtils.getInterpreter().fromJson(builder.toString(), JsonElement.class)); } catch (Exception e) { if (e instanceof JsonSyntaxException) { throw new PagarMeException(responseCode, url, method, builder.toString()); } throw PagarMeException.buildWithError(e); } }