auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean renderFileFromAttachment(String filename, XWikiDocument doc, XWikiContext context) throws IOException, XWikiException { _Logger.debug("... as attachment"); try { <START> IAttFileNameMatcherRole matcher = Utils.getComponent(IAttFileNameMatcherRole.class); <END> matcher.setFileNamePattern(filename); XWikiAttachment attachment = getAttachmentService().getAttachmentFirstNameMatch(doc, matcher); XWiki xwiki = context.getWiki(); XWikiResponse response = context.getResponse(); String mimetype = xwiki.getEngineContext().getMimeType(filename.toLowerCase()); if (isCssMimeType(mimetype) || isJavascriptMimeType(mimetype)) { byte[] data = attachment.getContent(context); response.setCharacterEncoding(ENCODING); setupHeaders(response, mimetype, attachment.getDate(), data.length); response.getOutputStream().write(data); } else { setupHeaders(response, mimetype, attachment.getDate(), attachment.getContentSize( context)); IOUtils.copy(attachment.getContentInputStream(context), response.getOutputStream() ); } return true; } catch (AttachmentNotExistsException anee) { _Logger.debug("Attachment not found", anee); } return false; }</code><technical_language>this result in ComponentLookup Exception, is "default" implementation</technical_language>

Target:
public boolean renderFileFromAttachment(String filename, XWikiDocument doc, XWikiContext context) throws IOException, XWikiException { _Logger.debug("... as attachment"); try { IAttFileNameMatcherRole matcher = Utils.getComponent(IAttFileNameMatcherRole.class, AttNameWithoutExtMatcher.ATT_NAME_WITHOUT_EXT_MATCHER); matcher.setFileNamePattern(filename); XWikiAttachment attachment = getAttachmentService().getAttachmentFirstNameMatch(doc, matcher); XWiki xwiki = context.getWiki(); XWikiResponse response = context.getResponse(); String mimetype = xwiki.getEngineContext().getMimeType(filename.toLowerCase()); if (isCssMimeType(mimetype) || isJavascriptMimeType(mimetype)) { byte[] data = attachment.getContent(context); response.setCharacterEncoding(ENCODING); setupHeaders(response, mimetype, attachment.getDate(), data.length); response.getOutputStream().write(data); } else { setupHeaders(response, mimetype, attachment.getDate(), attachment.getContentSize( context)); IOUtils.copy(attachment.getContentInputStream(context), response.getOutputStream() ); } return true; } catch (AttachmentNotExistsException anee) { _Logger.debug("Attachment not found", anee); } return false; }
Source:
<code>public Container( final CompressionHeader compressionHeader, final List<Slice> containerSlices, final long containerByteOffset, final long globalRecordCounter) { this.compressionHeader = compressionHeader; this.slices = containerSlices; this.containerByteOffset = containerByteOffset; final ReferenceContext commonRefContext = getDerivedReferenceContextFromSlices(slices); final AlignmentContext alignmentContext = getDerivedAlignmentContext(commonRefContext); int baseCount = 0; int blockCount = 0; int recordCount = 0; for (final Slice slice : slices) { recordCount += slice.getNumberOfRecords(); blockCount += slice.getNumberOfBlocks(); baseCount += slice.getBaseCount(); } this.containerHeader = new ContainerHeader( alignmentContext, globalRecordCounter, blockCount, recordCount, baseCount); <START> validateContainerReferenceContext(); <END> checkReferenceContexts(commonRefContext.getReferenceContextID()); }</code><technical_language>this validation is checking set is equal set to. redundant</technical_language>

Target:
public Container( final CompressionHeader compressionHeader, final List<Slice> containerSlices, final long containerByteOffset, final long globalRecordCounter) { this.compressionHeader = compressionHeader; this.slices = containerSlices; this.containerByteOffset = containerByteOffset; final ReferenceContext commonRefContext = getDerivedReferenceContextFromSlices(slices); final AlignmentContext alignmentContext = getDerivedAlignmentContext(commonRefContext); int baseCount = 0; int blockCount = 0; int recordCount = 0; for (final Slice slice : slices) { recordCount += slice.getNumberOfRecords(); blockCount += slice.getNumberOfBlocks(); baseCount += slice.getBaseCount(); } this.containerHeader = new ContainerHeader( alignmentContext, blockCount, recordCount, globalRecordCounter, baseCount); checkSliceReferenceContexts(commonRefContext.getReferenceContextID()); }
Source:
<code>private Guid GetVdsRunOnDestination() { if (getDestinationVdsId() != null) { VDS target_vds = getVdsDAO().get(getDestinationVdsId()); log.infoFormat("Checking for a specific VDS only - id:{0}, name:{1}, host_name(ip):{2}", getDestinationVdsId(), target_vds.getvds_name(), target_vds.gethost_name()); VmHandler.UpdateVmGuestAgentVersion(getVm()); if (target_vds.getvds_type() == VDSType.PowerClient && !Config.<Boolean> GetValue(ConfigValues.PowerClientAllowRunningGuestsWithoutTools) && getVm() != null && getVm().getHasAgent()) { log.infoFormat( "VdcBLL.RunVmCommandBase.getVdsToRunOn - VM {0} has no tools - skipping power client check", getVm().getId()); } else { if (!target_vds.getvds_group_id().equals(getVm().getvds_group_id()) || target_vds.getstatus() != VDSStatus.Up || (target_vds.getcpu_cores() != null && getVm().getnum_of_cpus() > target_vds.getcpu_cores())) { return Guid.Empty; } <START> <END> return getVdsToRunOn(Arrays.asList(new VDS[] { target_vds })); } } return Guid.Empty; }</code><technical_language>need new VDS[]</technical_language>

Target:
private Guid GetVdsRunOnDestination() { if (getDestinationVdsId() == null) { return Guid.Empty; } final VDS target_vds = getVdsDAO().get(getDestinationVdsId()); log.infoFormat("Checking for a specific VDS only - id:{0}, name:{1}, host_name(ip):{2}", getDestinationVdsId(), target_vds.getvds_name(), target_vds.gethost_name()); VmHandler.UpdateVmGuestAgentVersion(getVm()); if (target_vds.getvds_type() == VDSType.PowerClient && !Config.<Boolean> GetValue(ConfigValues.PowerClientAllowRunningGuestsWithoutTools) && getVm() != null && getVm().getHasAgent()) { log.infoFormat( "VdcBLL.RunVmCommandBase.getVdsToRunOn - VM {0} has no tools - skipping power client check", getVm().getId()); return Guid.Empty; } else if (target_vds.getvds_group_id().equals(getVm().getvds_group_id()) && target_vds.getstatus() != VDSStatus.Up && target_vds.getcpu_cores() != null && target_vds.getcpu_cores() >= getVm().getnum_of_cpus()) { return getVdsToRunOn(Arrays.asList(target_vds)); } return Guid.Empty; }
Source:
<code>public void testProcessScheduledMessageRetry() { final ResponseMessageResultType result = ResponseMessageResultType.NOT_OK; final Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, 1); final Date scheduledRetryTime = calendar.getTime(); final RetryHeader retryHeader = new RetryHeader(0, this.getMaxRetryCount, scheduledRetryTime); final ProtocolResponseMessage message = new ProtocolResponseMessage.Builder() .deviceMessageMetadata(DEVICE_MESSAGE_DATA).domain(DOMAIN).domainVersion(DOMAIN_VERSION).result(result) .dataObject(DATA_OBJECT).scheduled(true).retryHeader(retryHeader).build(); final ScheduledTask scheduledTask = new ScheduledTask(DEVICE_MESSAGE_DATA, DOMAIN, DOMAIN, DATA_OBJECT, SCHEDULED_TIME); <START> when(this.scheduledTaskRepository.findByCorrelationUid(anyString())).thenReturn(scheduledTask); <END> this.deviceResponseMessageService.processMessage(message); verify(this.domainResponseMessageSender, never()).send(message); verify(this.scheduledTaskRepository, never()).delete(scheduledTask); assertEquals(new Timestamp(scheduledRetryTime.getTime()), scheduledTask.getscheduledTime()); }</code><technical_language>for findByCorrelationUid specific possible. string, exact string "correlationId" is meant here</technical_language>

Target:
public void testProcessScheduledMessageRetry() { final ResponseMessageResultType result = ResponseMessageResultType.NOT_OK; final Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.DATE, 1); final Date scheduledRetryTime = calendar.getTime(); final RetryHeader retryHeader = new RetryHeader(0, 1, scheduledRetryTime); final String exceptionMessage = "message"; final OsgpException exception = new OsgpException(ComponentType.OSGP_CORE, exceptionMessage); final ProtocolResponseMessage message = new ProtocolResponseMessage.Builder() .deviceMessageMetadata(DEVICE_MESSAGE_DATA).domain(DOMAIN).domainVersion(DOMAIN_VERSION).result(result) .dataObject(DATA_OBJECT).scheduled(true).retryHeader(retryHeader).osgpException(exception).build(); final ScheduledTask scheduledTask = new ScheduledTask(DEVICE_MESSAGE_DATA, DOMAIN, DOMAIN, DATA_OBJECT, SCHEDULED_TIME); when(this.scheduledTaskRepository.findByCorrelationUid(anyString())).thenReturn(scheduledTask); this.deviceResponseMessageService.processMessage(message); verify(this.domainResponseMessageSender, never()).send(message); verify(this.scheduledTaskRepository, never()).delete(scheduledTask); verify(this.scheduledTaskRepository).save(scheduledTask); assertEquals(new Timestamp(scheduledRetryTime.getTime()), scheduledTask.getscheduledTime()); assertTrue(scheduledTask.getErrorLog().contains(exceptionMessage)); }
Source:
<code>public LongInputStream getLongInputStream() { checkState(closed); FixedLengthSliceInput sliceInput = new ChunkedSliceInput(new ChainedSliceLoader(buffer.getCompressedSlices()), 32 * 1024); OrcDataSourceId orcDataSourceId = new OrcDataSourceId("LongOutputStream"); try { return new LongInputStreamV1( new OrcInputStream( orcDataSourceId, sliceInput, <START> createOrcDecompressor(orcDataSourceId, compression, 1024 * 1024), <END> newSimpleAggregatedMemoryContext(), sliceInput.getRetainedSize()), signed); } catch (OrcCorruptionException e) { throw new UncheckedIOException("Unable to create LongInputStream from LongOutputStream", e); } }</code><technical_language>pretty this bufferSize is passed constructor</technical_language>

Target:
public LongInputStream getLongInputStream() { checkState(closed); FixedLengthSliceInput sliceInput = new ChunkedSliceInput(new ChainedSliceLoader(buffer.getCompressedSlices()), 32 * 1024); OrcDataSourceId orcDataSourceId = new OrcDataSourceId("LongOutputStream"); try { return new LongInputStreamV1( new OrcInputStream( orcDataSourceId, sliceInput, createOrcDecompressor(orcDataSourceId, compression, bufferSize), newSimpleAggregatedMemoryContext(), sliceInput.getRetainedSize()), signed); } catch (OrcCorruptionException e) { throw new UncheckedIOException("Unable to create LongInputStream from LongOutputStream", e); } }
Source:
<code>static HashMap<LocalDate, List<TripPatternForDate>> mapTripPatternsByStopDate( Multimap<Integer, TripPattern> patternsByServiceCode, Multimap<LocalDate, Integer> serviceCodesByLocalDates ) { HashMap<LocalDate, List<TripPatternForDate>> tripPatternsByStopByDate = new HashMap<>(); for (LocalDate localDate : serviceCodesByLocalDates.keySet()) { Set<Integer> services = new HashSet<>(serviceCodesByLocalDates.get(localDate)); List<TripPattern> filteredPatterns = services .stream() .map(patternsByServiceCode::get) .flatMap(Collection::stream) <START> .collect(Collectors.toList()); <END> List<TripPatternForDate> tripPatternsForDate = new ArrayList<>(); for (TripPattern tripPattern : filteredPatterns) { List<TripSchedule> tripSchedules = new ArrayList<>(tripPattern.getTripSchedules()); tripSchedules = tripSchedules.stream() .filter(t -> services.contains(t.getServiceCode())) .collect(Collectors.toList()); TripPatternForDate tripPatternForDate = new TripPatternForDate( tripPattern, tripSchedules ); tripPatternsForDate.add(tripPatternForDate); } tripPatternsByStopByDate.put(localDate, tripPatternsForDate); } for (List<TripPatternForDate> list : tripPatternsByStopByDate.values()) { list.sort(Comparator.comparingInt(p -> p.getTripPattern().getId())); } return tripPatternsByStopByDate; }</code><technical_language>This a distinct(), a TripPattern occur multiple times. This is a TripPattern contains TripSchedules for multiple servicesCodes, present multiple serviceCodes in patternsByServiceCode. List<TripPattern> filteredPatterns = services .stream() .map(patternsByServiceCode::get) .flatMap(Collection::stream) .distinct() .collect(Collectors.toList()); This problems line attempting put uniquely a map: <LINK_0></technical_language>

Target:
static HashMap<LocalDate, List<TripPatternForDate>> mapTripPatternsByStopDate( Multimap<Integer, TripPattern> patternsByServiceCode, Multimap<LocalDate, Integer> serviceCodesByLocalDates ) { HashMap<LocalDate, List<TripPatternForDate>> tripPatternsByStopByDate = new HashMap<>(); for (LocalDate localDate : serviceCodesByLocalDates.keySet()) { Set<Integer> services = new HashSet<>(serviceCodesByLocalDates.get(localDate)); List<TripPattern> filteredPatterns = services .stream() .map(patternsByServiceCode::get) .flatMap(Collection::stream) .distinct() .collect(Collectors.toList()); List<TripPatternForDate> tripPatternsForDate = new ArrayList<>(); for (TripPattern tripPattern : filteredPatterns) { List<TripSchedule> tripSchedules = new ArrayList<>(tripPattern.getTripSchedules()); tripSchedules = tripSchedules.stream() .filter(t -> services.contains(t.getServiceCode())) .collect(Collectors.toList()); TripPatternForDate tripPatternForDate = new TripPatternForDate( tripPattern, tripSchedules, localDate ); tripPatternsForDate.add(tripPatternForDate); } tripPatternsByStopByDate.put(localDate, tripPatternsForDate); } return tripPatternsByStopByDate; }
Source:
<code>protected void reloadSlave() throws Exception { ModelNode op = new ModelNode(); op.get(OP).set("reload"); op.get(OP_ADDR).add(HOST, "slave"); op.get(ADMIN_ONLY).set(false); try { getDomainSlaveClient().execute(new OperationBuilder(op).build()); } catch(IOException e) { final Throwable cause = e.getCause(); if (!(cause instanceof ExecutionException) && !(cause instanceof CancellationException)) { throw e; } } <START> readHostControllerStatus(getDomainSlaveClient(), TIMEOUT); <END> }</code><technical_language>reuse DomainLifecycleUtil#*</technical_language>

Target:
protected void reloadSlave() throws Exception { ModelNode op = new ModelNode(); op.get(OP).set("reload"); op.get(OP_ADDR).add(HOST, "slave"); op.get(ADMIN_ONLY).set(false); try { getDomainSlaveClient().execute(new OperationBuilder(op).build()); } catch(IOException e) { final Throwable cause = e.getCause(); if (!(cause instanceof ExecutionException) && !(cause instanceof CancellationException)) { throw e; } } }
Source:
<code>public void createAuxiliaryConnections(boolean isRejoin) { Set<Integer> hostsToConnect = Sets.newHashSet(); if (isRejoin) { hostsToConnect.addAll(m_peers); } else { for (Integer host : m_peers) { if (host > m_localHostId) { hostsToConnect.add(host); } } } if (hostsToConnect.isEmpty()) return; for (int hostId : hostsToConnect) { Iterator<ForeignHost> it = m_foreignHosts.get(hostId).iterator(); if (it.hasNext()) { InetSocketAddress listeningAddress = it.next().m_listeningAddress; for (int ii = 0; ii < m_secondaryConnections; ii++) { try { <START> SocketChannel socket = m_joiner.requestForConnection(listeningAddress); <END> ForeignHost fhost = new ForeignHost(this, hostId, socket, Integer.MAX_VALUE, listeningAddress, new PicoNetwork(socket, true)); putForeignHost(hostId, fhost); fhost.enableRead(VERBOTEN_THREADS); } catch (IOException | JSONException e) { hostLog.error("Failed to connect to peer nodes.", e); throw new RuntimeException("Failed to establish socket connection with " + listeningAddress.getAddress().getHostAddress(), e); } } } } boolean ready = true; for (int hostId : m_peers) { ready = ready && m_foreignHosts.get(hostId).size() == (m_secondaryConnections + 1); if (!ready) return; } if (ready) { m_hasAllSecondaryConnectionCreated = true; } }</code><technical_language>need "listeningAddress" changed number of secondary connections. pull iterator out side of for loop</technical_language>

Target:
public void createAuxiliaryConnections(boolean isRejoin) { Set<Integer> hostsToConnect = Sets.newHashSet(); if (isRejoin) { hostsToConnect.addAll(m_peers); } else { for (Integer host : m_peers) { if (host > m_localHostId) { hostsToConnect.add(host); } } } if (hostsToConnect.isEmpty()) return; for (int hostId : hostsToConnect) { Iterator<ForeignHost> it = m_foreignHosts.get(hostId).iterator(); if (it.hasNext()) { InetSocketAddress listeningAddress = it.next().m_listeningAddress; for (int ii = 0; ii < m_secondaryConnections; ii++) { try { SocketChannel socket = m_joiner.requestForConnection(listeningAddress); ForeignHost fhost = new ForeignHost(this, hostId, socket, Integer.MAX_VALUE, listeningAddress, new PicoNetwork(socket, true)); putForeignHost(hostId, fhost); fhost.enableRead(VERBOTEN_THREADS); } catch (IOException | JSONException e) { hostLog.error("Failed to connect to peer nodes.", e); throw new RuntimeException("Failed to establish socket connection with " + listeningAddress.getAddress().getHostAddress(), e); } } } } for (int hostId : m_peers) { if (m_foreignHosts.get(hostId).size() != (m_secondaryConnections + 1)) { return; } } m_hasAllSecondaryConnectionCreated = true; }
Source:
<code>public String toString() { <START> String str = "push " + uri + " " + getRefs().toString(); <END> if (retryCount == 0) { return str; } return "(retry " + retryCount + ") " + str; }</code><technical_language>This information leak. Task toString output is filtered for users based able project named getProjectNameKey(), administrators tasks. addition of reference information a user able a project reference (e.g. "master") learn of another replication ask working a hidden name (e.g. "sekret"). This bad. is easy find out if caller is Administrator allowed anything, a normal user need references filtered them. alternative is add a new SSH command in this plugin is restricted administrator @RequiresCapability("administrateServer") shows contents of replication queue in a more detailed formatting</technical_language>

Target:
public String toString() { String print = "[" + HexFormat.fromInt(id) + "] push " + uri + " " + getRefs().toString(); if (retryCount > 0) { print = "(retry " + retryCount + ") " + print; } return print; }
Source:
<code>public List<Sample> getLastWeek( @Scope({OAuthScope.SENSORS_BASIC}) final AccessToken accessToken, @PathParam("sensor") final String sensor, @QueryParam("from") Long clientUtcTimestamp) { <START> final int slotDurationInMinutes = 5; <END> final int queryDurationInHours = 24; validateQueryRange(clientUtcTimestamp, DateTime.now(), accessToken.accountId, allowedRangeInSeconds); return deviceDataDAO.generateTimeSerie(clientUtcTimestamp, accessToken.accountId, slotDurationInMinutes, queryDurationInHours, sensor); }</code><technical_language>5 minutes for 7 \* 24 hrs' data? 60 more</technical_language>

Target:
public List<Sample> getLastWeek( @Scope({OAuthScope.SENSORS_BASIC}) final AccessToken accessToken, @PathParam("sensor") final String sensor, @QueryParam("from") Long clientUtcTimestamp) { final int slotDurationInMinutes = 60; final int queryDurationInHours = 24 * 7; validateQueryRange(clientUtcTimestamp, DateTime.now(), accessToken.accountId, allowedRangeInSeconds); return deviceDataDAO.generateTimeSerie(clientUtcTimestamp, accessToken.accountId, slotDurationInMinutes, queryDurationInHours, sensor); }
Source:
<code>public void setUp() throws Exception { <START> assumeTrue(0 == Utils.getGlobalConnectionCount()); <END> boolean ascii; if (protocol.equals("ascii")) { ascii = true; } else if (protocol.equals("binary")) { ascii = false; } else { throw new IllegalArgumentException(protocol); } HostAndPort integrationServer = getServerAddress(); int embeddedPort = ascii ? asciiEmbeddedServer.getPort() : binaryEmbeddedServer.getPort(); String address = isEmbedded() ? "127.0.0.1" : integrationServer.getHostText(); int port = isEmbedded() ? embeddedPort : integrationServer.getPort(); MemcacheClientBuilder<String> builder = MemcacheClientBuilder.newStringClient() .withAddress(HostAndPort.fromParts(address, port)) .withConnections(1) .withMaxOutstandingRequests(1000) .withMetrics(NoopMetrics.INSTANCE) .withRetry(false) .withReplyExecutor(Utils.SAME_THREAD_EXECUTOR) .withRequestTimeoutMillis(100); if (ascii) { asciiClient = builder.connectAscii(); binaryClient = null; client = asciiClient; } else { binaryClient = builder.connectBinary(); asciiClient = null; client = binaryClient; } ConnectFuture.connectFuture(client).get(); System.out.printf("Using client: %s protocol: %s and port: %d\n", client, protocol, port); cleanup(); }</code><technical_language>this assumption (i.e ignoring test if true), want test fail in case highlight broken</technical_language>

Target:
public void setUp() throws Exception { assertEquals(0, Utils.getGlobalConnectionCount()); boolean ascii; if (protocol.equals("ascii")) { ascii = true; } else if (protocol.equals("binary")) { ascii = false; } else { throw new IllegalArgumentException(protocol); } HostAndPort integrationServer = getServerAddress(); int embeddedPort = ascii ? asciiEmbeddedServer.getPort() : binaryEmbeddedServer.getPort(); String address = isEmbedded() ? "127.0.0.1" : integrationServer.getHostText(); int port = isEmbedded() ? embeddedPort : integrationServer.getPort(); MemcacheClientBuilder<String> builder = MemcacheClientBuilder.newStringClient() .withAddress(HostAndPort.fromParts(address, port)) .withConnections(1) .withMaxOutstandingRequests(1000) .withMetrics(NoopMetrics.INSTANCE) .withRetry(false) .withReplyExecutor(Utils.SAME_THREAD_EXECUTOR) .withRequestTimeoutMillis(100); if (ascii) { asciiClient = builder.connectAscii(); binaryClient = null; client = asciiClient; } else { binaryClient = builder.connectBinary(); asciiClient = null; client = binaryClient; } ConnectFuture.connectFuture(client).get(); System.out.printf("Using client: %s protocol: %s and port: %d\n", client, protocol, port); cleanup(); }
Source:
<code>public String login(String login, String pass, File cred, String ssh) throws RestServerException, ServiceException { HttpPost httpPost = new HttpPost(RMConfig.get().getRestUrl() + "/rm/login"); try { MultipartEntity entity; if (cred == null) { entity = createLoginPasswordSSHKeyMultipart(login, pass, ssh); } else { entity = new MultipartEntity(); entity.addPart("credential", new FileBody(cred, "application/octet-stream")); } httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost); String responseAsString = convertToString(response.getEntity().getContent()); switch (response.getStatusLine().getStatusCode()) { case 200: break; default: <START> String message = responseAsString; <END> if (message.trim().length() == 0) { message = "{ \"httpErrorCode\": " + response.getStatusLine().getStatusCode() + "," + "\"errorMessage\": \"" + response.getStatusLine().getReasonPhrase() + "\" }"; } throw new RestServerException(response.getStatusLine().getStatusCode(), message); } return responseAsString; } catch (IOException e) { throw new ServiceException(e.getMessage()); } finally { httpPost.releaseConnection(); if (cred != null) { cred.delete(); } } }</code><technical_language>need a new String message. responseAsString variable</technical_language>

Target:
public String login(String login, String pass, File cred, String ssh) throws RestServerException, ServiceException { HttpPost httpPost = new HttpPost(RMConfig.get().getRestUrl() + "/rm/login"); try { MultipartEntity entity; if (cred == null) { entity = createLoginPasswordSSHKeyMultipart(login, pass, ssh); } else { entity = new MultipartEntity(); entity.addPart("credential", new FileBody(cred, "application/octet-stream")); } httpPost.setEntity(entity); HttpResponse response = httpClient.execute(httpPost); String responseAsString = convertToString(response.getEntity().getContent()); switch (response.getStatusLine().getStatusCode()) { case 200: break; default: if (responseAsString.trim().length() == 0) { responseAsString = "{ \"httpErrorCode\": " + response.getStatusLine().getStatusCode() + "," + "\"errorMessage\": \"" + response.getStatusLine().getReasonPhrase() + "\" }"; } throw new RestServerException(response.getStatusLine().getStatusCode(), responseAsString); } return responseAsString; } catch (IOException e) { throw new ServiceException(e.getMessage()); } finally { httpPost.releaseConnection(); if (cred != null) { cred.delete(); } } }
Source:
<code>private boolean isMavenProject() { <START> return model.getLocation().append("pom.xml").toFile().exists(); <END> }</code><technical_language>extract "pom.xml" a constant for improved visibility</technical_language>

Target:
private boolean isMavenProject() { return model.getLocation().append(MAVEN_POM_XML_FILE).toFile().exists(); }
Source:
<code>public static boolean isMatchingItem(@Nonnull final ItemStack base, @Nonnull final ItemStack comparison, final boolean matchDamage, final boolean matchNBT) { if (base.isEmpty() || comparison.isEmpty()) { return false; } if (base.getItem() != comparison.getItem()) { return false; } Set<String> matchingNBT = matchingNBTRegistry.get(base.getItem()); if (matchingNBT != null && !isNbtSubsetEquals(base, comparison, matchingNBT)) { return false; } <START> <END> if (matchDamage && base.getHasSubtypes()) { if (!isWildcard(base) && !isWildcard(comparison)) { if (base.getItemDamage() != comparison.getItemDamage()) { return false; } } } if (matchNBT) { NBTTagCompound baseTag = base.getTagCompound(); if (baseTag != null && !baseTag.equals(comparison.getTagCompound())) { return false; } } return true; }</code><technical_language>move this else statement if (matchNBT) perform strict comparison first</technical_language>

Target:
public static boolean isMatchingItem(@Nonnull final ItemStack base, @Nonnull final ItemStack comparison, final boolean matchDamage, final boolean matchNBT) { if (base.isEmpty() || comparison.isEmpty()) { return false; } if (base.getItem() != comparison.getItem()) { return false; } if (matchDamage && base.getHasSubtypes()) { if (!isWildcard(base) && !isWildcard(comparison)) { if (base.getItemDamage() != comparison.getItemDamage()) { return false; } } } if (matchNBT) { NBTTagCompound baseTag = base.getTagCompound(); if (baseTag != null && !baseTag.equals(comparison.getTagCompound())) { return false; } } else { List<StackMatchingPredicate> predicates = matchingPredicates.getOrDefault(base.getItem(), Collections.emptyList()); for (StackMatchingPredicate predicate : predicates) { if (!predicate.isMatching(base, comparison)) { return false; } } } return true; }
Source:
<code>public static Set<InternetAddress> convertRecipientString(String recipientList, EnvVars envVars, int type) throws AddressException, UnsupportedEncodingException { final Set<InternetAddress> internetAddresses = new LinkedHashSet<>(); if (!StringUtils.isBlank(recipientList)) { final String expandedRecipientList = fixupDelimiters(envVars.expand(recipientList)); InternetAddress[] all = InternetAddress.parse(expandedRecipientList.replace("bcc:", "").replace("cc:", "")); String[] recipients = StringUtils.stripAll(expandedRecipientList.split(",")); if (recipients.length != all.length) { throw new IllegalArgumentException("Unsupported format in expanded recipient list string: " + expandedRecipientList); <START> } <END> final Set<InternetAddress> to = new LinkedHashSet<>(); final Set<InternetAddress> cc = new LinkedHashSet<>(); final Set<InternetAddress> bcc = new LinkedHashSet<>(); final String defaultSuffix = ExtendedEmailPublisher.descriptor().getDefaultSuffix(); for (int i = 0; i < recipients.length; i++) { String recipient = recipients[i]; InternetAddress address = all[i]; if (recipient.startsWith("bcc:")) { bcc.add(address); } else if (recipient.startsWith("cc:")) { cc.add(address); } else { to.add(address); } } if(type == BCC) { internetAddresses.addAll(bcc); } else if(type == CC) { internetAddresses.addAll(cc); } else { internetAddresses.addAll(to); } for(InternetAddress address : internetAddresses) { if(!address.getAddress().contains("@")) { User u = User.get(address.getAddress(), false, null); String userEmail; if(u != null) { userEmail = getUserConfiguredEmail(u); if(userEmail != null){ address.setAddress(userEmail); } } } if(!address.getAddress().contains("@") && defaultSuffix != null && defaultSuffix.contains("@")) { address.setAddress(address.getAddress() + defaultSuffix); } if(address.getPersonal() != null) { address.setPersonal(address.getPersonal(), ExtendedEmailPublisher.descriptor().getCharset()); } } } return internetAddresses; }</code><technical_language>thanks for time try fix</technical_language>

Target:
public static Set<InternetAddress> convertRecipientString(String recipientList, EnvVars envVars, int type) throws AddressException, UnsupportedEncodingException { return convertRecipientString(recipientList, envVars, type, null); }
Source:
<code>public FieldInjector(ContainerImpl container, Field field, String name) throws MissingDependencyException { this.field = field; <START> if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers())) && !field.isAccessible()) { <END> SecurityManager sm = System.getSecurityManager(); try { if (sm != null) { sm.checkPermission(new ReflectPermission("suppressAccessChecks")); } field.setAccessible(true); } catch (AccessControlException e) { throw new DependencyException("Security manager in use, could not access field: " + field.getDeclaringClass().getName() + "(" + field.getName() + ")", e); } } Key<?> key = Key.newInstance(field.getType(), name); factory = container.getFactory(key); if (factory == null) { throw new MissingDependencyException("No mapping found for dependency " + key + " in " + field + "."); } this.externalContext = ExternalContext.newInstance(field, key, container); }</code><technical_language>a good idea extract this a method eg.: isAccessible(field) instead of repeating code times</technical_language>

Target:
public FieldInjector(ContainerImpl container, Field field, String name) throws MissingDependencyException { this.field = field; if (isNotPublic(field) && !field.isAccessible()) { SecurityManager sm = System.getSecurityManager(); try { if (sm != null) { sm.checkPermission(new ReflectPermission("suppressAccessChecks")); } field.setAccessible(true); } catch (AccessControlException e) { throw new DependencyException("Security manager in use, could not access field: " + field.getDeclaringClass().getName() + "(" + field.getName() + ")", e); } } Key<?> key = Key.newInstance(field.getType(), name); factory = container.getFactory(key); if (factory == null) { throw new MissingDependencyException("No mapping found for dependency " + key + " in " + field + "."); } this.externalContext = ExternalContext.newInstance(field, key, container); }
Source:
<code>private UserDTO getUserDtoFromJson(String json, Long dtoId) { UserDTO userDTO = null; try { if (json != null && json != "") { <START> jsonMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); <END> userDTO = jsonMapper.readValue(json, UserDTO.class); } } catch (final Exception ex) { LOGGER.error("Could not parse activity ID " + dtoId + " original data. " + "JSON was: " + json, ex); } return userDTO; }</code><technical_language>I handled this issue in a a @JsonIgnoreProperties annotation DTO objects themselves, wanting check tested this user activity beginning of CHPL works. handle this issue in for activity types... this is fine if better. If want do remove annotation I modify other builders do this way? Alternatively switch I done originally. Fine either, want consistent</technical_language>

Target:
private UserDTO getUserDtoFromJson(String json, Long dtoId) { UserDTO userDTO = null; try { if (json != null && json != "") { userDTO = jsonMapper.readValue(json, UserDTO.class); } } catch (final Exception ex) { LOGGER.error("Could not parse activity ID " + dtoId + " original data. " + "JSON was: " + json, ex); } return userDTO; }
Source:
<code>public void setup() throws Exception { queryExecutor = MoreExecutors.newDirectExecutorService(); when(preQueryPlugin.process(any(), any())) .thenAnswer(invocation -> invocation.getArguments()[1]); strategy = new SortedFederationStrategy( queryExecutor, Arrays.asList(preQueryPlugin), new ArrayList<>()); <START> federateStrategy = <END> new SortedFederationStrategy( queryExecutor, Arrays.asList(preQueryPlugin), new ArrayList<>()); responseArgumentCaptor = ArgumentCaptor.forClass(QueryResponseImpl.class); requestArgumentCaptor = ArgumentCaptor.forClass(QueryRequestImpl.class); when(mockSortedQueryMonitorFactory.createMonitor( any(CompletionService.class), any(Map.class), responseArgumentCaptor.capture(), requestArgumentCaptor.capture(), any(List.class))) .thenReturn(mockSortedQueryMonitor); strategy.setSortedQueryMonitorFactory(mockSortedQueryMonitorFactory); when(mockQuery.getTimeoutMillis()).thenReturn(LONG_TIMEOUT); when(mockQuery.getPageSize()).thenReturn(-1); metacard = new MetacardImpl(); metacard.setId("mock metacard"); Result mockResult = new ResultImpl(metacard); List<Result> results = Collections.singletonList(mockResult); when(mockResponse.getResults()).thenReturn(results); properties = new HashMap<>(); }</code><technical_language>this federateStrategy strategy necessary? dupes. stateful comparing state? for tests clear difference is</technical_language>

Target:
public void setup() throws Exception { queryExecutor = MoreExecutors.newDirectExecutorService(); when(preQueryPlugin.process(any(), any())) .thenAnswer(invocation -> invocation.getArguments()[1]); strategy = new SortedFederationStrategy( queryExecutor, Arrays.asList(preQueryPlugin), new ArrayList<>()); responseArgumentCaptor = ArgumentCaptor.forClass(QueryResponseImpl.class); requestArgumentCaptor = ArgumentCaptor.forClass(QueryRequestImpl.class); when(mockQuery.getTimeoutMillis()).thenReturn(LONG_TIMEOUT); when(mockQuery.getPageSize()).thenReturn(-1); metacard = new MetacardImpl(); metacard.setId("mock metacard"); Result mockResult = new ResultImpl(metacard); List<Result> results = Collections.singletonList(mockResult); when(mockResponse.getResults()).thenReturn(results); properties = new HashMap<>(); }
Source:
<code>public ListenableFuture<Void> write(ByteBuffer buffer, Map<String, String> headers) throws IllegalArgumentException { if (buffer != null) { <START> byte[] bytes = new byte[buffer.remaining()]; <END> buffer.get(bytes); return write(new ByteArrayEntity(bytes), headers); } else { throw new IllegalArgumentException("ByteBuffer parameter is empty."); } }</code><technical_language>creates a new array if ByteBuffer is array. java HttpEntity content; if (buffer.hasArray()) { content = new ByteArrayEntity(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); } else { // existing logic. }</technical_language>

Target:
public ListenableFuture<Void> write(ByteBuffer buffer, Map<String, String> headers) throws IllegalArgumentException { Preconditions.checkArgument(buffer != null, "ByteBuffer parameter is empty."); HttpEntity content; if (buffer.hasArray()) { content = new ByteArrayEntity(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining()); } else { byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); content = new ByteArrayEntity(bytes); } return write(content, headers); }
Source:
<code>public static Optional<Cookie> getCookie(final Collection<Cookie> cookies, final String name) { <START> if (cookies != null) { <END> for (final Cookie cookie : cookies) { if (cookie != null && CommonHelper.areEquals(name, cookie.getName())) { return Optional.of(cookie); } } } return Optional.empty(); }</code><technical_language>Surely this done streaming cookies.stream.filter(cookie != null && CommonHelper.equals...).findFirst() This return Optional directly, empty</technical_language>

Target:
public static Optional<Cookie> getCookie(final Collection<Cookie> cookies, final String name) { if (cookies != null) { return cookies.stream().filter( cookie -> cookie != null && CommonHelper.areEquals(name, cookie.getName()) ).findFirst(); } return Optional.empty(); }
Source:
<code>public int[] transformToIntValuesSV(ProjectionBlock projectionBlock) { if (_results == null) { _results = new int[DocIdSetPlanNode.MAX_DOC_PER_CALL]; } byte[][] firstValues = _firstArgument.transformToBytesValuesSV(projectionBlock); byte[][] secondValues = _secondArgument.transformToBytesValuesSV(projectionBlock); for (int i = 0; i < projectionBlock.getNumDocs(); i++) { Geometry firstGeometry = GeometrySerializer.deserialize(firstValues[i]); Geometry secondGeometry = GeometrySerializer.deserialize(secondValues[i]); <START> if (GeometryUtils.isGeography(firstGeometry) || GeometryUtils.isGeography(secondGeometry)) { <END> throw new RuntimeException( String.format("%s is available for Geometry objects only", FUNCTION_NAME)); } _results[i] = firstGeometry.equals(secondGeometry) ? 1 : 0; } return _results; }</code><technical_language>Equals work geography well</technical_language>

Target:
public int[] transformToIntValuesSV(ProjectionBlock projectionBlock) { if (_results == null) { _results = new int[DocIdSetPlanNode.MAX_DOC_PER_CALL]; } byte[][] firstValues = _firstArgument.transformToBytesValuesSV(projectionBlock); byte[][] secondValues = _secondArgument.transformToBytesValuesSV(projectionBlock); for (int i = 0; i < projectionBlock.getNumDocs(); i++) { Geometry firstGeometry = GeometrySerializer.deserialize(firstValues[i]); Geometry secondGeometry = GeometrySerializer.deserialize(secondValues[i]); _results[i] = firstGeometry.equals(secondGeometry) ? 1 : 0; } return _results; }
Source:
<code>private void recreateStudentWithNewEmail( CourseStudent newCourseStudent, String lastName, CourseStudent courseStudent, boolean hasDocument, boolean keepUpdateTimestamp, String courseId, String email) throws InvalidParametersException, EntityDoesNotExistException { newCourseStudent.setLastName(lastName); newCourseStudent.setCreatedAt(courseStudent.getCreatedAt()); if (keepUpdateTimestamp) { newCourseStudent.setLastUpdate(courseStudent.getUpdatedAt()); } try { createStudent(new StudentAttributes(newCourseStudent), hasDocument); } catch (EntityAlreadyExistsException e) { <START> CourseStudent existingStudent = (CourseStudent) getEntity(new StudentAttributes(newCourseStudent)); <END> String error = ERROR_UPDATE_EMAIL_ALREADY_USED + existingStudent.getName() + "/" + existingStudent.getEmail(); throw new InvalidParametersException(error); } deleteStudent(courseId, email); }</code><technical_language>refactor new StudentAttributes(newCourseStudent) out, needed in try block. clearer</technical_language>

Target:
private void recreateStudentWithNewEmail( CourseStudent newCourseStudent, String lastName, CourseStudent courseStudent, boolean hasDocument, boolean keepUpdateTimestamp, String courseId, String email) throws InvalidParametersException { newCourseStudent.setLastName(lastName); newCourseStudent.setCreatedAt(courseStudent.getCreatedAt()); if (keepUpdateTimestamp) { newCourseStudent.setLastUpdate(courseStudent.getUpdatedAt()); } StudentAttributes newCourseStudentAttributes = new StudentAttributes(newCourseStudent); try { createStudent(newCourseStudentAttributes, hasDocument); } catch (EntityAlreadyExistsException e) { CourseStudent existingStudent = (CourseStudent) getEntity(newCourseStudentAttributes); String error = ERROR_UPDATE_EMAIL_ALREADY_USED + existingStudent.getName() + "/" + existingStudent.getEmail(); throw new InvalidParametersException(error); } deleteStudent(courseId, email); }
Source:
<code>public void setUp() { <START> GwtMockito.initMocks(this); <END> view = GWT.create(TimeZonePickerViewImpl.class); doCallRealMethod().when(view).setLocalTimeZone(); doCallRealMethod().when(view).setValue(anyString()); doCallRealMethod().when(view).populateTzSelector(); doCallRealMethod().when(tzSelect).setValue(anyString()); doCallRealMethod().when(tzSelect).setValue(anyString(), anyBoolean()); view.tzSelect = tzSelect; tested = spy(new TimeZonePicker(view)); }</code><technical_language>if this is necessary, I remember I declaring some Runner class (on class declaration) implies initializing mocks class itself</technical_language>

Target:
public void setUp() { view = GWT.create(TimeZonePickerViewImpl.class); doCallRealMethod().when(view).setValue(anyString()); doCallRealMethod().when(view).populateTzSelector(); doCallRealMethod().when(tzSelect).setValue(anyString()); doCallRealMethod().when(tzSelect).setValue(anyString(), anyBoolean()); view.tzSelect = tzSelect; tested = spy(new TimeZonePicker(view)); }
Source:
<code>@Override public <Resp> void response(HttpAdapter<?, Resp> adapter, Resp res, Throwable error, SpanCustomizer customizer) { HttpResponse response; if (res instanceof HttpClientResponse) { response = new HttpClientResponse.FromHttpAdapter((HttpClientAdapter) adapter, res); } else if (adapter instanceof HttpClientResponse.ToHttpAdapter) { response = ((HttpClientResponse.ToHttpAdapter) adapter).delegate; } else { throw new AssertionError("programming bug"); } <START> errorParser.error(error, customizer); <END> responseParser.parse(response, error, currentTraceContext.get(), customizer); }</code><technical_language>wondering is ordering requirement lines</technical_language>

Target:
@Override public <Resp> void response(HttpAdapter<?, Resp> adapter, Resp res, Throwable error, SpanCustomizer customizer) { HttpResponse response; if (res instanceof HttpClientResponse) { response = new HttpClientAdapters.FromResponseAdapter<>((HttpClientAdapter) adapter, res); } else if (adapter instanceof HttpClientAdapters.ToResponseAdapter) { response = ((HttpClientAdapters.ToResponseAdapter) adapter).delegate; } else { throw new AssertionError("programming bug"); } responseParser.parse(response, currentTraceContext.get(), customizer); }
Source:
<code>public Host update(Host incoming) { validateEnums(Host.class, incoming); QueryIdResolver<Guid> hostResolver = new QueryIdResolver<Guid>(VdcQueryType.GetVdsByVdsId, GetVdsByVdsIdParameters.class); VDS entity = getEntity(hostResolver, true); <START> if (incoming.isSetCluster() && (incoming.getCluster().isSetId() || incoming.getCluster().isSetName())) { <END> Guid clusterId = lookupClusterId(incoming); performAction(VdcActionType.ChangeVDSCluster, new ChangeVDSClusterParameters(clusterId, guid)); } return performUpdate(incoming, entity, map(entity), hostResolver, VdcActionType.UpdateVds, new UpdateParametersProvider()); }</code><technical_language>breaking use-case here, checking old_cluster != new_cluster</technical_language>

Target:
public Host update(Host incoming) { validateEnums(Host.class, incoming); QueryIdResolver<Guid> hostResolver = new QueryIdResolver<Guid>(VdcQueryType.GetVdsByVdsId, GetVdsByVdsIdParameters.class); VDS entity = getEntity(hostResolver, true); if (incoming.isSetCluster() && (incoming.getCluster().isSetId() || incoming.getCluster().isSetName())) { Guid clusterId = lookupClusterId(incoming); if (!clusterId.equals(entity.getvds_group_id())) { performAction(VdcActionType.ChangeVDSCluster, new ChangeVDSClusterParameters(clusterId, guid)); } } return performUpdate(incoming, entity, map(entity), hostResolver, VdcActionType.UpdateVds, new UpdateParametersProvider()); }
Source:
<code>public MappingCodec( @NonNull TypeCodec<InnerT> innerCodec, @NonNull GenericType<OuterT> outerJavaType) { <START> this.innerCodec = Objects.requireNonNull(innerCodec, "innerCodec cannot be null"); <END> this.outerJavaType = Objects.requireNonNull(outerJavaType, "outerJavaType cannot be null"); }</code><technical_language>nit: this constructor protected (although I real issue public)</technical_language>

Target:
protected MappingCodec( @NonNull TypeCodec<InnerT> innerCodec, @NonNull GenericType<OuterT> outerJavaType) { this.innerCodec = Objects.requireNonNull(innerCodec, "innerCodec cannot be null"); this.outerJavaType = Objects.requireNonNull(outerJavaType, "outerJavaType cannot be null"); }
Source:
<code>public void invitesAndKicks() throws Exception { final MkBase base = new MkBase(); final Bout bout = base.randomBout(); final Friends friends = bout.friends(); final String friend = base.randomBout().friends().iterate().iterator() .next().alias(); friends.invite(friend); <START> final String someone = base.randomBout().friends().iterate().iterator() <END> .next().alias(); friends.invite(someone); friends.kick(friend); MatcherAssert.assertThat( friends.iterate(), Matchers.not( Matchers.hasItem(new Friend.HasAlias(Matchers.is(friend))) ) ); }</code><technical_language>@erimerturk this bout other one? Do need change this test</technical_language>

Target:
public void invitesAndKicks() throws Exception { final MkBase base = new MkBase(); final Bout bout = base.randomBout(); final Friends friends = bout.friends(); final String friend = base.randomAlias().name(); friends.invite(friend); final String someone = base.randomAlias().name(); friends.invite(someone); friends.kick(friend); MatcherAssert.assertThat( friends.iterate(), Matchers.not( Matchers.hasItem(new Friend.HasAlias(Matchers.is(friend))) ) ); }
Source:
<code>public ArtifactInputStream getInputStream(String storageId, String repositoryId, String path) throws IOException, NoSuchAlgorithmException, <START> ArtifactTransportException <END> { Storage storage = getConfiguration().getStorage(storageId); logger.debug("Checking in " + storage.getId() + ":" + repositoryId + "..."); Repository repository = storage.getRepository(repositoryId); StorageProvider storageProvider = storageProviderRegistry.getProvider(repository.getImplementation()); final File repoPath = storageProvider.getFileImplementation(storage.getRepository(repositoryId).getBasedir()); final File artifactFile = storageProvider.getFileImplementation(repoPath.getPath(), path).getCanonicalFile(); logger.debug(" -> Checking for " + artifactFile.getCanonicalPath() + "..."); if (artifactFile.exists()) { logger.debug("Resolved " + artifactFile.getCanonicalPath() + "!"); ArtifactInputStream ais = storageProvider.getInputStreamImplementation(artifactFile.getAbsolutePath()); ais.setLength(artifactFile.length()); return ais; } return null; }</code><technical_language>code style for this project is: @Override public ArtifactInputStream getInputStream(String storageId, String repositoryId, String path) throws IOException, NoSuchAlgorithmException, ArtifactTransportException</technical_language>

Target:
public ArtifactInputStream getInputStream(String storageId, String repositoryId, String path) throws IOException, NoSuchAlgorithmException, ArtifactTransportException { Storage storage = getConfiguration().getStorage(storageId); logger.debug("Checking in " + storage.getId() + ":" + repositoryId + "..."); Repository repository = storage.getRepository(repositoryId); StorageProvider storageProvider = storageProviderRegistry.getProvider(repository.getImplementation()); String storagePath = storage.getRepository(repositoryId).getBasedir() + '/' + path; ArtifactInputStream ais = storageProvider.getInputStreamImplementation(storagePath); return ais; }