auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private String buildUpdateExistingPaymentWorksVendorInStagingTableSql(String pmwVendorRequestId, String pmwRequestStatus, String kfsVendorProcessingStatus, String kfsAchProcessingStatus, String kfsVendorDocumentNumber, Timestamp processingTimeStamp) { StringBuilder sql = new StringBuilder(); sql.append("update kfs.cu_pmw_vendor_t "); sql.append("set pmw_req_stat = '" + pmwRequestStatus); sql.append("', kfs_vnd_proc_stat = '" + kfsVendorProcessingStatus); sql.append("', proc_ts = '" + PaymentWorksDataTransformationService.PROCESSING_TIMESTAMP_SQL_FORMATTER.format(processingTimeStamp)); if (StringUtils.isNotBlank(kfsAchProcessingStatus)) { sql.append("', kfs_ach_proc_stat = '" + kfsAchProcessingStatus); } if (StringUtils.isNotBlank(kfsAchProcessingStatus)) { sql.append("', pven_fdoc_nbr = '" + kfsVendorDocumentNumber); } sql.append("' where pmw_vnd_req_id = '" + pmwVendorRequestId + "'"); return sql.toString(); }

Target:
private String buildUpdateExistingPaymentWorksVendorInStagingTableSql(String pmwVendorRequestId, String pmwRequestStatus, String kfsVendorProcessingStatus, String kfsAchProcessingStatus, String kfsVendorDocumentNumber, Timestamp processingTimeStamp) { StringBuilder sql = new StringBuilder(); sql.append("update kfs.cu_pmw_vendor_t "); sql.append("set pmw_req_stat = '" + pmwRequestStatus); sql.append("', kfs_vnd_proc_stat = '" + kfsVendorProcessingStatus); sql.append("', proc_ts = '" + PROCESSING_TIMESTAMP_SQL_FORMATTER.format(processingTimeStamp)); if (StringUtils.isNotBlank(kfsAchProcessingStatus)) { sql.append("', kfs_ach_proc_stat = '" + kfsAchProcessingStatus); } if (StringUtils.isNotBlank(kfsVendorDocumentNumber)) { sql.append("', pven_fdoc_nbr = '" + kfsVendorDocumentNumber); } sql.append("' where pmw_vnd_req_id = '" + pmwVendorRequestId + "'"); return sql.toString(); }
Source:
public static <T extends Annotation> Object invokeStaticMethodWithAnnotation(Class<?> clazzWithMethod, Class<T> annotationClass, Class<?>... methodReturnTypes) { List<Method> annotatedMethods = Arrays.stream(clazzWithMethod.getDeclaredMethods()).filter( method -> method.isAnnotationPresent(annotationClass)).collect(Collectors.toList()); if(annotatedMethods.size() > 1){ throw new RedDeerException("More than one method is annotated with "+annotationClass); } if(annotatedMethods.size() == 1){ try { boolean methodFound = false; for(Class<?> methodReturnType: methodReturnTypes){ Class<?> mrt = annotatedMethods.get(0).getReturnType(); if (annotatedMethods.get(0).getReturnType().isAssignableFrom(methodReturnType)) { methodFound = true; } } if(!methodFound){ throw new RedDeerException("Method annotated with annotation " + annotationClass + " does not have specified return type " + methodReturnTypes); } return annotatedMethods.get(0).invoke(null, (Object[]) null); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RedDeerException("Something were wrong when executing a method annotated with " + " annotation " + annotationClass, e); } } return null; }

Target:
public static <T extends Annotation> Object invokeStaticMethodWithAnnotation(Class<?> clazzWithMethod, Class<T> annotationClass, Class<?>... methodReturnTypes) { List<Method> annotatedMethods = Arrays.stream(clazzWithMethod.getDeclaredMethods()).filter( method -> method.isAnnotationPresent(annotationClass)).collect(Collectors.toList()); if(annotatedMethods.size() > 1){ throw new RedDeerException("More than one method is annotated with "+annotationClass); } if(annotatedMethods.size() == 1){ try { for(Class<?> methodReturnType: methodReturnTypes){ if (annotatedMethods.get(0).getReturnType().isAssignableFrom(methodReturnType)) { return annotatedMethods.get(0).invoke(null, (Object[]) null); } } throw new RedDeerException("Method annotated with annotation " + annotationClass + " does not have specified return type " + methodReturnTypes); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { throw new RedDeerException("Something were wrong when executing a method annotated with " + " annotation " + annotationClass, e); } } return null; }
Source:
public void setup(Context.OperatorContext context) { operatorId = context.getId(); logger.info("OperatorID from Base class: {}", operatorId); spinMillis = context.getValue(com.datatorrent.api.Context.OperatorContext.SPIN_MILLIS); factory = JCSMPFactory.onlyInstance(); JCSMPChannelProperties channelProperties = (JCSMPChannelProperties)this.properties.getProperty(JCSMPProperties.CLIENT_CHANNEL_PROPERTIES); channelProperties.setConnectRetries(Integer.parseInt(this.connectRetries)); channelProperties.setReconnectRetries(Integer.parseInt(this.reconnectRetries)); reconnectRetryMillis = channelProperties.getReconnectRetryWaitInMillis(); try { session = factory.createSession(this.properties, null, new PrintingSessionEventHandler()); } catch (JCSMPException e) { DTThrowable.rethrow(e); } logger.debug("Properties:\n" + properties.toString()); idempotentStorageManager.setup(context); lastCompletedWId = idempotentStorageManager.getLargestRecoveryWindow(); }

Target:
public void setup(Context.OperatorContext context) { operatorId = context.getId(); logger.debug("OperatorID: {}", operatorId); rcHandler = new ReconnectCallbackHandler(); cbHandler = new MessageHandler(arrivedTopicMessagesToProcess); factory = JCSMPFactory.onlyInstance(); JCSMPChannelProperties channelProperties = (JCSMPChannelProperties)this.properties.getProperty(JCSMPProperties.CLIENT_CHANNEL_PROPERTIES); channelProperties.setConnectRetries(this.connectRetries); channelProperties.setReconnectRetries(this.reconnectRetries); reconnectRetryMillis = channelProperties.getReconnectRetryWaitInMillis(); try { session = factory.createSession(this.properties, null, new SessionHandler()); } catch (JCSMPException e) { DTThrowable.rethrow(e); } logger.debug("Properties:\n" + properties.toString()); idempotentStorageManager.setup(context); lastCompletedWId = idempotentStorageManager.getLargestRecoveryWindow(); }
Source:
public RecipeHandler(IRecipeMachine machineInstance) { this.machineInstance = machineInstance; shapedTrie = new RecipeNode(null); shapelessTrie = new RecipeNode(null); shapedReverseLookupTable = new HashMap<Item, ArrayList<Pair<AbstractIngredient[], Float>>>(); shapelessReverseLookupTable = new HashMap<Item, ArrayList<Pair<AbstractIngredient[], Float>>>(); }

Target:
public RecipeHandler(IRecipeMachine machineInstance) { this.machineInstance = machineInstance; String uniqueName = machineInstance.getUniqueMachineName(); if (machineLookupTable.containsKey(uniqueName)) { throw new RuntimeException("Another machine named " + uniqueName + " has already been registered."); } machineLookupTable.put(uniqueName, machineInstance); shapedTrie = new RecipeNode(null); shapelessTrie = new RecipeNode(null); shapedReverseLookupTable = new IdentityHashMap<Item, List<Pair<AbstractIngredient[], Float>>>(); shapelessReverseLookupTable = new IdentityHashMap<Item, List<Pair<AbstractIngredient[], Float>>>(); }
Source:
public boolean equals(Object o) { return (o == this) || ((o instanceof java.util.Map) && areEqual(delegate.toJavaSet(), ((java.util.Map<?, ?>) o).entrySet())); }

Target:
public boolean equals(Object o) { return TODO(); }
Source:
public void run() { try { Thread.currentThread().setName("LeaderConnector-" + address); Socket sock = connectToLeader(); if(sock != null && sock.isConnected() && !socket.compareAndSet(null, sock)) sock.close(); } catch (Exception e) { LOG.error("Failed to connect to " + address, e); } finally { latch.countDown(); } }

Target:
public void run() { try { Thread.currentThread().setName("LeaderConnector-" + address); Socket sock = connectToLeader(); if (sock != null && sock.isConnected() && !socket.compareAndSet(null, sock)) { LOG.info("Connection to the leader is already established, close the redundant connection"); sock.close(); } } catch (Exception e) { LOG.error("Failed connect to {}", address, e); } finally { latch.countDown(); } }
Source:
private void openPopupPlayer(final boolean append) { if (!PermissionHelper.isPopupEnabled(activity)) { PermissionHelper.showPopupEnablementToast(activity); return; } if (!bounded) startService(false); if (player != null && player.isInFullscreen()) player.toggleFullscreen(); PlayQueue queue = setupPlayQueueForIntent(append); if (append) { NavigationHelper.enqueueOnPopupPlayer(activity, queue, false); } else { Runnable onAllow = () -> NavigationHelper.playOnPopupPlayer(activity, queue, true); if (shouldAskBeforeClearingQueue()) showClearingQueueConfirmation(onAllow); else onAllow.run(); } }

Target:
private void openPopupPlayer(final boolean append) { if (!PermissionHelper.isPopupEnabled(activity)) { PermissionHelper.showPopupEnablementToast(activity); return; } if (!bound) { startService(requireContext(), false); } if (player != null && player.isFullscreen()) { player.toggleFullscreen(); } final PlayQueue queue = setupPlayQueueForIntent(append); if (append) { NavigationHelper.enqueueOnPopupPlayer(activity, queue, false); } else { replaceQueueIfUserConfirms(() -> NavigationHelper .playOnPopupPlayer(activity, queue, true)); } }
Source:
protected void onUpdated() { if (entity==null || !Entities.isManaged(entity)) { if (log.isDebugEnabled()) log.debug("Ignoring onUpdated when entity is not in valid state ({})", this, entity); return; } if (getConfig(DERIVE_SERVICE_PROBLEMS)) { Object newval = computeServiceProblems(); updateMapSensor(SERVICE_PROBLEMS, newval); } if (getConfig(DERIVE_SERVICE_NOT_UP)) { Object newval = computeServiceNotUp(); updateMapSensor(SERVICE_NOT_UP_INDICATORS, newval); } }

Target:
protected void onUpdated() { if (entity==null || !Entities.isManaged(entity)) { if (log.isDebugEnabled()) log.debug("Ignoring onUpdated when entity is not in valid state ({})", this, entity); return; } if (getConfig(DERIVE_SERVICE_PROBLEMS)) { updateMapSensor(SERVICE_PROBLEMS, computeServiceProblems()); } if (getConfig(DERIVE_SERVICE_NOT_UP)) { updateMapSensor(SERVICE_NOT_UP_INDICATORS, computeServiceNotUp()); } }
Source:
private JSONObject _request(Method m, String url, String json, boolean build, boolean search) throws AlgoliaException { HttpRequestBase req; switch (m) { case DELETE: req = new HttpDelete(); break; case GET: req = new HttpGet(); break; case POST: req = new HttpPost(); break; case PUT: req = new HttpPut(); break; default: throw new IllegalArgumentException("Method " + m + " is not supported"); } List<AlgoliaInnerException> errors = new ArrayList<AlgoliaInnerException>(); List<String> hosts = build ? buildHostsThatAreUp() : queryHostsThatAreUp(); for (String host : hosts) { JSONObject res = _requestByHost(req, host, url, json, errors, search); if (res != null) { hostStatuses.put(host, new HostStatus()); return res; } else { hostStatuses.put(host, new HostStatus().setUp(false)); } } throw AlgoliaException.from("Hosts unreachable", errors); }

Target:
private JSONObject _request(Method m, String url, String json, boolean build, boolean search) throws AlgoliaException { HttpRequestBase req; switch (m) { case DELETE: req = new HttpDelete(); break; case GET: req = new HttpGet(); break; case POST: req = new HttpPost(); break; case PUT: req = new HttpPut(); break; default: throw new IllegalArgumentException("Method " + m + " is not supported"); } List<AlgoliaInnerException> errors = new ArrayList<AlgoliaInnerException>(); List<String> hosts = build ? buildHostsThatAreUp() : queryHostsThatAreUp(); for (String host : hosts) { JSONObject res = _requestByHost(req, host, url, json, errors, search); if (res != null) { hostStatuses.put(host, HostStatus.up()); return res; } else { hostStatuses.put(host, HostStatus.down()); } } throw AlgoliaException.from("Hosts unreachable", errors); }
Source:
protected boolean doValidate() { GeoLocation currentValue = getCurrentValue(); if (currentValue == null) { return false; } double latitude = currentValue.getLatitude(); double longitude = currentValue.getLongitude(); if (latitude > 90.0 || latitude < -90.0) { return false; } if (longitude > 180.0 || longitude < -180.0) { return false; } return true; }

Target:
protected boolean doValidate() { GeoLocation currentValue = getCurrentValue(); if (currentValue != null) { double latitude = currentValue.getLatitude(); double longitude = currentValue.getLongitude(); if (latitude > 90.0 || latitude < -90.0) { return false; } if (longitude > 180.0 || longitude < -180.0) { return false; } return true; } else { return !isRequired(); } }
Source:
public void deleteMembersGroup(PerunSession sess, Vo vo) throws InternalErrorException, GroupAlreadyRemovedException, GroupAlreadyRemovedFromResourceException { Group group; try { group = getGroupByName(sess, vo, VosManager.MEMBERS_GROUP); } catch (GroupNotExistsException e) { throw new ConsistencyErrorException("Built-in members group must exist.",e); } try { this.deleteAnyGroup(sess, group, true); } catch (RelationExistsException e) { throw new ConsistencyErrorException("Built-in members group cannot have any relation in this stage.", e); } catch (NotGroupMemberException | WrongAttributeValueException | WrongReferenceAttributeValueException | GroupNotExistsException | AlreadyMemberException e) { throw new ConsistencyErrorException("This exception is caused by something going wrong while deleting groups operations. " + "Members group cannot have any operations defined on it.", e); } }

Target:
public void deleteMembersGroup(PerunSession sess, Vo vo) throws InternalErrorException, GroupAlreadyRemovedException, GroupAlreadyRemovedFromResourceException, GroupOperationsException, GroupNotExistsException { Group group; try { group = getGroupByName(sess, vo, VosManager.MEMBERS_GROUP); } catch (GroupNotExistsException e) { throw new ConsistencyErrorException("Built-in members group must exist.",e); } try { this.deleteAnyGroup(sess, group, true); } catch (RelationExistsException e) { throw new ConsistencyErrorException("Built-in members group cannot have any relation in this stage.", e); } }
Source:
public void validateCollectionElementsNotNull(Supplier<? extends Collection<?>> getter1, Supplier<? extends Collection<?>> getter2) { Collection<?> collection1 = getter1.get(); Collection<?> collection2 = getter2.get(); if (isCollectionInvalid(collection1) || isCollectionInvalid(collection2)) { throw new IllegalArgumentException("collection contains null elements"); } }

Target:
public void validateCollectionElementsNotNull(Supplier<? extends Collection<?>> getter1, Supplier<? extends Collection<?>> getter2) { validateCollectionElementsNotNull(getter1); validateCollectionElementsNotNull(getter2); }
Source:
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (holder instanceof ReaderPostViewHolder) { renderPost(position, (ReaderPostViewHolder) holder); } else if (holder instanceof ReaderXPostViewHolder) { renderXPost(position, (ReaderXPostViewHolder) holder); } else if (holder instanceof SiteHeaderViewHolder) { SiteHeaderViewHolder blogHolder = (SiteHeaderViewHolder) holder; blogHolder.mSiteHeaderView.setOnBlogInfoLoadedListener(mBlogInfoLoadedListener); if (isDiscover()) { blogHolder.mSiteHeaderView.loadBlogInfo(ReaderConstants.DISCOVER_SITE_ID, 0); } else { blogHolder.mSiteHeaderView.loadBlogInfo(mCurrentBlogId, mCurrentFeedId); } } else if (holder instanceof TagHeaderViewHolder) { TagHeaderViewHolder tagHolder = (TagHeaderViewHolder) holder; tagHolder.mTagHeaderView.setCurrentTag(mCurrentTag); } else if (holder instanceof GapMarkerViewHolder) { GapMarkerViewHolder gapHolder = (GapMarkerViewHolder) holder; gapHolder.mGapMarkerView.setCurrentTag(mCurrentTag); } }

Target:
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { if (holder instanceof ReaderPostViewHolder) { renderPost(position, (ReaderPostViewHolder) holder); } else if (holder instanceof ReaderXPostViewHolder) { renderXPost(position, (ReaderXPostViewHolder) holder); } else if (holder instanceof SiteHeaderViewHolder) { SiteHeaderViewHolder siteHolder = (SiteHeaderViewHolder) holder; siteHolder.mSiteHeaderView.setOnBlogInfoLoadedListener(mBlogInfoLoadedListener); if (isDiscover()) { siteHolder.mSiteHeaderView.loadBlogInfo(ReaderConstants.DISCOVER_SITE_ID, 0); } else { siteHolder.mSiteHeaderView.loadBlogInfo(mCurrentBlogId, mCurrentFeedId); } } else if (holder instanceof TagHeaderViewHolder) { TagHeaderViewHolder tagHolder = (TagHeaderViewHolder) holder; tagHolder.mTagHeaderView.setCurrentTag(mCurrentTag); } else if (holder instanceof GapMarkerViewHolder) { GapMarkerViewHolder gapHolder = (GapMarkerViewHolder) holder; gapHolder.mGapMarkerView.setCurrentTag(mCurrentTag); } }
Source:
protected void AddVmTemplateImages() { Guid srcStorageDomain = mImages.get(0).getstorage_id().getValue(); Guid vmSnapshotId = Guid.NewGuid(); for (DiskImage diskImage : mImages) { CreateImageTemplateParameters createParams = new CreateImageTemplateParameters(diskImage.getId(), getVmTemplateId(), getVmTemplateName(), getVmId()); if(diskImage.getstorage_id() != null && !diskImage.getstorage_id().equals(Guid.Empty)) { createParams.setStorageDomainId(diskImage.getstorage_id().getValue()); } else { createParams.setStorageDomainId(srcStorageDomain); } createParams.setVmSnapshotId(vmSnapshotId); createParams.setEntityId(getParameters().getEntityId()); createParams.setDestinationStorageDomainId(getStorageDomainId().getValue()); createParams.setParentParemeters(getParameters()); getParameters().getImagesParameters().add(createParams); VdcReturnValueBase retValue = Backend.getInstance().runInternalAction( VdcActionType.CreateImageTemplate, createParams); getReturnValue().getTaskIdList().addAll(retValue.getInternalTaskIdList()); } }

Target:
protected void AddVmTemplateImages() { Guid srcStorageDomain = mImages.get(0).getstorage_id().getValue(); Guid vmSnapshotId = Guid.NewGuid(); for (DiskImage diskImage : mImages) { CreateImageTemplateParameters createParams = new CreateImageTemplateParameters(diskImage.getId(), getVmTemplateId(), getVmTemplateName(), getVmId()); if(!diskImage.getstorage_id().equals(Guid.Empty)) { createParams.setStorageDomainId(diskImage.getstorage_id().getValue()); } else { createParams.setStorageDomainId(srcStorageDomain); } createParams.setVmSnapshotId(vmSnapshotId); createParams.setEntityId(getParameters().getEntityId()); createParams.setDestinationStorageDomainId(getStorageDomainId().getValue()); createParams.setParentParemeters(getParameters()); getParameters().getImagesParameters().add(createParams); VdcReturnValueBase retValue = Backend.getInstance().runInternalAction( VdcActionType.CreateImageTemplate, createParams); getReturnValue().getTaskIdList().addAll(retValue.getInternalTaskIdList()); } }
Source:
public PatternPathRouter.RoutableDestination<Object> getRoutableEndpoint( CarbonMessage carbonMessage) throws WebSocketEndpointAnnotationException { String uri = (String) carbonMessage.getProperty(Constants.TO); LOGGER.info("path : " + uri); List<PatternPathRouter.RoutableDestination<Object>> routableDestinations = endpointPatternPathRouter.getDestinations(uri); return getBestEndpoint(routableDestinations, uri); }

Target:
public PatternPathRouter.RoutableDestination<Object> getRoutableEndpoint( CarbonMessage carbonMessage) throws WebSocketEndpointAnnotationException { String uri = (String) carbonMessage.getProperty(Constants.TO); List<PatternPathRouter.RoutableDestination<Object>> routableDestinations = endpointPatternPathRouter.getDestinations(uri); return getBestEndpoint(routableDestinations, uri); }
Source:
public void enqueuePendingFile(final File file) { pendingFileExecutor.submit(new Runnable() { @Override public void run() { try { BufferedReader in = null; try { in = new BufferedReader(new InputStreamReader(new SnappyInputStream(new FileInputStream(file)), Charsets.UTF_8)); Event event = codec.fromJson(in.readLine()); EventPartition partition = partitioner.getPartition(event); enqueueUpload(partition, file); } catch (IOException e) { log.error(e, "Error while uploading file %s", file.getName()); } finally { Closeables.closeQuietly(in); } } catch (Exception e) { log.error(e, "Unable to schedule pending file %s for upload", file.getName()); } } }); }

Target:
public void enqueuePendingFile(final File file) { pendingFileExecutor.submit(new Runnable() { @Override public void run() { BufferedReader in = null; FileInputStream filein = null; try { filein = new FileInputStream(file); in = new BufferedReader(new InputStreamReader(new SnappyInputStream(filein), Charsets.UTF_8)); Event event = codec.fromJson(in.readLine()); EventPartition partition = partitioner.getPartition(event); enqueueUpload(partition, file); } catch (Exception e) { log.error(e, "Error while uploading file %s", file.getName()); file.renameTo(new File(failedFileDir, file.getName())); } finally { try { Closeables.close(filein, true); Closeables.close(in, true); } catch (IOException e) { log.error(e, "Error closing event file"); } } } }); }
Source:
private void addToZipOutput(final String path, final RepositoryFolder folder, final ZipOutputStream zipOutput) throws IOException { int itemsCount = 0; final List<RepositoryFile> files = folder.getFiles(); for (RepositoryFile file : files) { System.out.println("File: " + path + file.getName()); zipOutput.putNextEntry(new ZipEntry(path + file.getName())); file.readFile(new Action<InputStream>() { @Override public void run(InputStream fileInput) throws Exception { FileHelper.copy(fileInput, zipOutput); } }); zipOutput.closeEntry(); itemsCount++; } final List<RepositoryFolder> folders = folder.getFolders(); for (RepositoryFolder subFolder : folders) { String name = subFolder.getName(); System.out.println("Directory: " + path + name + "/"); addToZipOutput(path + name + "/", subFolder, zipOutput); itemsCount++; } if (itemsCount == 0 && ! path.equals("")) { String relativePath = path; System.out.println("Empty: " + relativePath); ZipEntry entry = new ZipEntry(relativePath); zipOutput.putNextEntry(entry); } }

Target:
private void addToZipOutput(final String path, final RepositoryFolder folder, final ZipOutputStream zipOutput) throws IOException { int itemsCount = 0; final List<RepositoryFile> files = folder.getFiles(); for (RepositoryFile file : files) { logger.info("File: " + path + file.getName()); zipOutput.putNextEntry(new ZipEntry(path + file.getName())); file.readFile(new Action<InputStream>() { @Override public void run(InputStream fileInput) throws Exception { FileHelper.copy(fileInput, zipOutput); } }); zipOutput.closeEntry(); itemsCount++; } final List<RepositoryFolder> folders = folder.getFolders(); for (RepositoryFolder subFolder : folders) { String name = subFolder.getName(); logger.info("Directory: " + path + name + "/"); addToZipOutput(path + name + "/", subFolder, zipOutput); itemsCount++; } if (itemsCount == 0 && ! path.equals("")) { String relativePath = path; logger.info("Empty: " + relativePath); ZipEntry entry = new ZipEntry(relativePath); zipOutput.putNextEntry(entry); } }
Source:
public void terminated() throws ViatraBaseException { Notification n = new Notification(TERMINATED, this, sequenceNumber++); sendNotification(n); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name; try { name = new ObjectName(MBEANNAME+"_"+CURRENTVERSION+"_"+ID); mbs.unregisterMBean(name); } catch (MalformedObjectNameException | MBeanRegistrationException | InstanceNotFoundException e) { throw new ViatraBaseException(e.getMessage()); } }

Target:
public void terminated() throws ViatraDebuggerException { Notification n = new Notification(TERMINATED, this, sequenceNumber++); sendNotification(n); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName name; try { name = new ObjectName(MBEANNAME+"_"+CURRENTVERSION+"_"+ID); mbs.unregisterMBean(name); } catch (MalformedObjectNameException | MBeanRegistrationException | InstanceNotFoundException e) { throw new ViatraDebuggerException(e.getMessage()); } }
Source:
public void shouldCreateRepartitionTopicWithSpecifiedNumberOfPartitions() throws ExecutionException, InterruptedException { final String repartitionName = "new-partitions"; final long timestamp = System.currentTimeMillis(); sendEvents( timestamp, Arrays.asList( new KeyValue<>(1, "A"), new KeyValue<>(2, "B") ) ); final StreamsBuilder builder = new StreamsBuilder(); builder.stream(inputTopic, Consumed.with(Serdes.Integer(), Serdes.String())) .repartition(Repartitioned.<Integer, String>as(repartitionName).withNumberOfPartitions(2)) .groupByKey() .count() .toStream() .to(outputTopic); startStreams(builder); validateReceivedMessages( new IntegerDeserializer(), new LongDeserializer(), Arrays.asList( new KeyValue<>(1, 1L), new KeyValue<>(2, 1L) ) ); final String repartitionTopicName = toRepartitionTopicName(repartitionName); assertTrue(topicExists(repartitionTopicName)); assertEquals(2, getNumberOfPartitionsForTopic(repartitionTopicName)); }

Target:
public void shouldCreateRepartitionTopicWithSpecifiedNumberOfPartitions() throws Exception { final String repartitionName = "new-partitions"; final long timestamp = System.currentTimeMillis(); sendEvents( timestamp, Arrays.asList( new KeyValue<>(1, "A"), new KeyValue<>(2, "B") ) ); final StreamsBuilder builder = new StreamsBuilder(); builder.stream(inputTopic, Consumed.with(Serdes.Integer(), Serdes.String())) .repartition(Repartitioned.<Integer, String>as(repartitionName).withNumberOfPartitions(2)) .groupByKey() .count() .toStream() .to(outputTopic); startStreams(builder); validateReceivedMessages( new IntegerDeserializer(), new LongDeserializer(), Arrays.asList( new KeyValue<>(1, 1L), new KeyValue<>(2, 1L) ) ); final String repartitionTopicName = toRepartitionTopicName(repartitionName); assertTrue(topicExists(repartitionTopicName)); assertEquals(2, getNumberOfPartitionsForTopic(repartitionTopicName)); }
Source:
public void testGroupByWithLiteralInSubqueryGrouping() throws Exception { testQuery( "SELECT \n" + " t1, t2\n" + " FROM\n" + " ( SELECT\n" + " 'dummy' as t1,\n" + " CASE\n" + " WHEN \n" + " dim4 = 'b'\n" + " THEN dim4\n" + " ELSE NULL\n" + " END AS t2\n" + " FROM\n" + " numfoo\n" + " GROUP BY\n" + " dim4\n" + " )\n" + " GROUP BY\n" + " t1,t2\n", ImmutableList.of( GroupByQuery.builder() .setDataSource( GroupByQuery.builder() .setDataSource(CalciteTests.DATASOURCE3) .setInterval(querySegmentSpec(Filtration.eternity())) .setGranularity(Granularities.ALL) .setDimensions(new DefaultDimensionSpec("dim4", "_d0", ValueType.STRING)) .setContext(QUERY_CONTEXT_DEFAULT) .build() ) .setVirtualColumns( expressionVirtualColumn( "v0", "\'dummy\'", ValueType.STRING ), expressionVirtualColumn( "v1", "case_searched((\"_d0\" == 'b'),\"_d0\",null)", ValueType.STRING ) ) .setInterval(querySegmentSpec(Filtration.eternity())) .setDimensions( dimensions( new DefaultDimensionSpec("v0", "d0", ValueType.STRING), new DefaultDimensionSpec("v1", "d1", ValueType.STRING) ) ) .setGranularity(Granularities.ALL) .setContext(QUERY_CONTEXT_DEFAULT) .build() ), NullHandling.replaceWithDefault() ? ImmutableList.of( new Object[]{"dummy", ""}, new Object[]{"dummy", "b"} ) : ImmutableList.of( new Object[]{"dummy", null}, new Object[]{"dummy", "b"} ) ); }

Target:
public void testGroupByWithLiteralInSubqueryGrouping() throws Exception { testQuery( "SELECT \n" + " t1, t2\n" + " FROM\n" + " ( SELECT\n" + " 'dummy' as t1,\n" + " CASE\n" + " WHEN \n" + " dim4 = 'b'\n" + " THEN dim4\n" + " ELSE NULL\n" + " END AS t2\n" + " FROM\n" + " numfoo\n" + " GROUP BY\n" + " dim4\n" + " )\n" + " GROUP BY\n" + " t1,t2\n", ImmutableList.of( GroupByQuery.builder() .setDataSource( GroupByQuery.builder() .setDataSource(CalciteTests.DATASOURCE3) .setInterval(querySegmentSpec(Filtration.eternity())) .setGranularity(Granularities.ALL) .setDimensions(new DefaultDimensionSpec("dim4", "_d0", ValueType.STRING)) .setContext(QUERY_CONTEXT_DEFAULT) .build() ) .setVirtualColumns( expressionVirtualColumn( "v0", "\'dummy\'", ValueType.STRING ), expressionVirtualColumn( "v1", "case_searched((\"_d0\" == 'b'),\"_d0\",null)", ValueType.STRING ) ) .setInterval(querySegmentSpec(Filtration.eternity())) .setDimensions( dimensions( new DefaultDimensionSpec("v0", "d0", ValueType.STRING), new DefaultDimensionSpec("v1", "d1", ValueType.STRING) ) ) .setGranularity(Granularities.ALL) .setContext(QUERY_CONTEXT_DEFAULT) .build() ), ImmutableList.of( new Object[]{"dummy", NULL_STRING}, new Object[]{"dummy", "b"} ) ); }
Source:
public CSMMetrics() { int numEnumEntries = ContainerProtos.Type.values().length; this.opsLatency = new MutableRate[numEnumEntries]; this.registry = new MetricsRegistry("CSMMetrics"); for (int i = 0; i < numEnumEntries; i++) { opsLatency[i] = registry.newRate( ContainerProtos.Type.forNumber(i + 1).toString(), ContainerProtos.Type.forNumber(i + 1) + " op"); } }

Target:
public CSMMetrics() { int numCmdTypes = ContainerProtos.Type.values().length; this.opsLatency = new MutableRate[numCmdTypes]; this.registry = new MetricsRegistry(CSMMetrics.class.getName()); for (int i = 0; i < numCmdTypes; i++) { opsLatency[i] = registry.newRate( ContainerProtos.Type.forNumber(i + 1).toString(), ContainerProtos.Type.forNumber(i + 1) + " op"); } }
Source:
private void assertEmptyPropertiesView(boolean emptyPropertiesView) { List<Tree> findedTrees = propertyViewBot.getFinder().findControls(IsInstanceOf.instanceOf(Tree.class)); assertEquals("The properties view is expected to be " + (emptyPropertiesView ? "" : "not") + " empty", emptyPropertiesView, findedTrees.isEmpty() || (!findedTrees.isEmpty() && !propertyViewBot.tree().hasItems())); }

Target:
private void assertEmptyPropertiesView(boolean emptyPropertiesView) { List<Tree> findedTrees = propertyViewBot.getFinder().findControls(IsInstanceOf.instanceOf(Tree.class)); boolean result = findedTrees.isEmpty() || (!findedTrees.isEmpty() && !propertyViewBot.tree().hasItems()); if (emptyPropertiesView) { assertTrue("The properties view is expected to be empty.", result); } else { assertFalse("The properties view is not expected to be empty.", result); } }
Source:
private void processResponse(final String command, final HttpURLConnection hconn) throws IOException { final int httpResponseCode = hconn.getResponseCode(); if (httpResponseCode >= 400 && httpResponseCode < 500) { throw new IllegalStateException( "Unable to connect to Tomcat manager. " + "The server command (" + command + ") failed with responseCode (" + httpResponseCode + ") and responseMessage (" + hconn.getResponseMessage()+ ").\n\n" + "Please make sure that you provided correct credentials for a user which is allowed to access Tomcat manager application.\n" + "The user must have 'manager-script' role specified in tomcat-users.xml file.\n"); } else if (httpResponseCode >= 300) { throw new IllegalStateException("The server command (" + command + ") failed with responseCode (" + httpResponseCode + ") and responseMessage (" + hconn.getResponseMessage() + ")."); } BufferedReader reader = null; try { reader = new BufferedReader(new InputStreamReader(hconn.getInputStream(), MANAGER_CHARSET)); String line = reader.readLine(); String contentError = null; if (line != null && !line.startsWith("OK -")) { contentError = line; } while (line != null) { line = reader.readLine(); } if (contentError != null) { throw new IllegalStateException("The server command (" + command + ") failed with content (" + contentError + ")."); } } finally { closeQuietly(reader); } }

Target:
private void processResponse(final String command, final HttpURLConnection hconn) throws IOException { final int httpResponseCode = hconn.getResponseCode(); if (httpResponseCode >= 400 && httpResponseCode < 500) { throw new IllegalStateException( "Unable to connect to Tomcat manager. " + "The server command (" + command + ") failed with responseCode (" + httpResponseCode + ") and responseMessage (" + hconn.getResponseMessage()+ ").\n\n" + "Please make sure that you provided correct credentials for a user which is allowed to access Tomcat manager application.\n" + "The user must have 'manager-script' role specified in tomcat-users.xml file.\n"); } else if (httpResponseCode >= 300) { throw new IllegalStateException("The server command (" + command + ") failed with responseCode (" + httpResponseCode + ") and responseMessage (" + hconn.getResponseMessage() + ")."); } try (BufferedReader reader = new BufferedReader(new InputStreamReader(hconn.getInputStream(), MANAGER_CHARSET))) { String line = reader.readLine(); String contentError = null; if (line != null && !line.startsWith("OK -")) { contentError = line; } while (line != null) { line = reader.readLine(); } if (contentError != null) { throw new IllegalStateException("The server command (" + command + ") failed with content (" + contentError + ")."); } } }
Source:
private <T> T decode(ByteBuf input, Class<T> clazz) throws Exception { ChannelHandlerContext ctx = mock(ChannelHandlerContext.class); when(ctx.alloc()).thenReturn(ByteBufAllocator.DEFAULT); List<Object> decoded = new ArrayList<Object>(); new WebSocket13FrameDecoder(true, false, 65536, true).decode(ctx, input, decoded); assertEquals(1, decoded.size()); return clazz.cast(decoded.get(0)); }

Target:
private <T> T decode(ByteBuf input, Class<T> clazz) { EmbeddedChannel ch = new EmbeddedChannel(new WebSocket13FrameDecoder(true, false, 65536, true)); assertTrue(ch.writeInbound(input)); Object decoded = ch.readInbound(); assertNotNull(decoded); assertFalse(ch.finish()); return clazz.cast(decoded); }
Source:
public static void getAudioDownloadFolder(Context context) { getFolder(context, R.string.download_path_audio_key, Environment.DIRECTORY_MUSIC); }

Target:
public static File getAudioDownloadFolder(Context context) { return getFolder(context, R.string.download_path_audio_key, Environment.DIRECTORY_MUSIC); }
Source:
public void testResolveKnownVariable() { final String message = "This is my ${Variable}"; final String expectedResolved = "This is my value"; Map<String, String> values = new HashMap<String, String>(); values.put("variable", "value"); String resolvedMessage = AuditLogDirector.resolveMessage(message, values); Assert.assertEquals(expectedResolved, resolvedMessage); }

Target:
public void testResolveKnownVariable() { final String message = "This is my ${Variable}"; final String expectedResolved = "This is my value"; Map<String, String> values = Collections.singletonMap("variable", "value"); String resolvedMessage = AuditLogDirector.resolveMessage(message, values); Assert.assertEquals(expectedResolved, resolvedMessage); }
Source:
public boolean kill() { if (status.isKilled()) { return false; } status = SchedulerStatus.KILLED; pinger.interrupt(); schedulingThread.interrupt(); logger.info("Killing all running task processes..."); for (RunningTaskData taskData : jobs.getRunningTasks()) { NodeSet nodes = taskData.getTask().getExecuterInformation().getNodes(); try { taskData.getLauncher().kill(); } catch (Throwable t) { logger.error("Failed to terminate launcher", t); } try { infrastructure.getRMProxiesManager() .getUserRMProxy(taskData.getUser(), taskData.getCredentials()) .releaseNodes(nodes, taskData.getTask().getCleaningScript(), addThirdPartyCredentials(taskData.getCredentials())); } catch (Throwable t) { logger.error("Failed to release nodes", t); } } listenJobLogsSupport.shutdown(); infrastructure.shutdown(); listener.schedulerStateUpdated(SchedulerEvent.KILLED); new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(SCHEDULER_EXIT_DELAY); } catch (InterruptedException e) { e.printStackTrace(); } System.exit(0); } }).start(); return true; }

Target:
public boolean kill() { if (status.isKilled()) { return false; } status = SchedulerStatus.KILLED; pinger.interrupt(); schedulingThread.interrupt(); logger.info("Killing all running task processes..."); for (RunningTaskData taskData : jobs.getRunningTasks()) { NodeSet nodes = taskData.getTask().getExecuterInformation().getNodes(); try { taskData.getLauncher().kill(); } catch (Throwable t) { logger.error("Failed to terminate launcher", t); } try { infrastructure.getRMProxiesManager() .getUserRMProxy(taskData.getUser(), taskData.getCredentials()) .releaseNodes(nodes, taskData.getTask().getCleaningScript(), addThirdPartyCredentials(taskData.getCredentials())); } catch (Throwable t) { logger.error("Failed to release nodes", t); } } listenJobLogsSupport.shutdown(); infrastructure.shutdown(); listener.schedulerStateUpdated(SchedulerEvent.KILLED); new Thread(() -> { try { Thread.sleep(SCHEDULER_KILL_DELAY); } catch (InterruptedException e) { logger.warn("Scheduler.kill() was interrupted while waiting for its configured delay, now terminating the process", e); } System.exit(0); }).start(); return true; }
Source:
public static int mapECLtype2SQLtype(String ecltype) { if (mapECLTypeNameToSQLType.containsKey(ecltype)) { return mapECLTypeNameToSQLType.get(ecltype); } else { int ftype = java.sql.Types.OTHER; String postfixUpper = ecltype.substring(ecltype.lastIndexOf(':') + 1).toUpperCase(); if (mapECLTypeNameToSQLType.containsKey(postfixUpper)) return mapECLTypeNameToSQLType.get(postfixUpper); else { Matcher m = TRAILINGNUMERICPATTERN.matcher(postfixUpper); if (m.matches() && mapECLTypeNameToSQLType.containsKey(m.group(2))) ftype = mapECLTypeNameToSQLType.get(m.group(2)); return ftype; } } }

Target:
public static int mapECLtype2SQLtype(String ecltype) { if (mapECLTypeNameToSQLType.containsKey(ecltype)) { return mapECLTypeNameToSQLType.get(ecltype); } else { String postfixUpper = ecltype.substring(ecltype.lastIndexOf(':') + 1).toUpperCase(); if (mapECLTypeNameToSQLType.containsKey(postfixUpper)) return mapECLTypeNameToSQLType.get(postfixUpper); else { Matcher m = TRAILINGNUMERICPATTERN.matcher(postfixUpper); if (m.matches() && mapECLTypeNameToSQLType.containsKey(m.group(2))) return mapECLTypeNameToSQLType.get(m.group(2)); else return java.sql.Types.OTHER; } } }
Source:
public void setup() { if (mListFragments == null) { mListFragments = new ArrayList<Fragment>(); mListFragments.add(fragmentOverview = (ProfileOverviewFragment) Fragment.instantiate(this, ProfileOverviewFragment.class.getName())); mListFragments.add(fragmentStats = (ProfileStatsFragment) Fragment.instantiate(this, ProfileStatsFragment.class.getName())); mListFragments.add(fragmentFeed = (FeedFragment) Fragment.instantiate(this, FeedFragment.class.getName())); fragmentFeed.setTitle(selectedPersona().getPersonaName()); fragmentFeed.setType(FeedClient.TYPE_PROFILE); fragmentFeed.setId(selectedPersona().getPersonaId()); fragmentFeed.setCanWrite(false); mViewPager = (ViewPager) findViewById(R.id.viewpager); mTabs = (SwipeyTabs) findViewById(R.id.swipeytabs); mPagerAdapter = new SwipeyTabsPagerAdapter( mFragmentManager, new String[] { "OVERVIEW", "STATS", "FEED" }, mListFragments, mViewPager, mLayoutInflater ); mViewPager.setAdapter(mPagerAdapter); mTabs.setAdapter(mPagerAdapter); mViewPager.setOnPageChangeListener(mTabs); mViewPager.setCurrentItem(0); mViewPager.setOffscreenPageLimit(2); } }

Target:
public void setup() { if (mListFragments == null) { mListFragments = new ArrayList<Fragment>(); mListFragments.add(fragmentOverview = (ProfileOverviewFragment) Fragment.instantiate(this, ProfileOverviewFragment.class.getName())); mListFragments.add(fragmentStats = (ProfileStatsFragment) Fragment.instantiate(this, ProfileStatsFragment.class.getName())); mListFragments.add(fragmentFeed = (FeedFragment) Fragment.instantiate(this, FeedFragment.class.getName())); fragmentFeed.setTitle(BF3Droid.getUser()); fragmentFeed.setType(FeedClient.TYPE_PROFILE); fragmentFeed.setId(BF3Droid.getUserId()); fragmentFeed.setCanWrite(false); mViewPager = (ViewPager) findViewById(R.id.viewpager); mTabs = (SwipeyTabs) findViewById(R.id.swipeytabs); mPagerAdapter = new SwipeyTabsPagerAdapter( mFragmentManager, new String[] { "OVERVIEW", "STATS", "FEED" }, mListFragments, mViewPager, mLayoutInflater ); mViewPager.setAdapter(mPagerAdapter); mTabs.setAdapter(mPagerAdapter); mViewPager.setOnPageChangeListener(mTabs); mViewPager.setCurrentItem(0); mViewPager.setOffscreenPageLimit(2); } }
Source:
private void getQuarks(Builder<@NonNull Integer> builder, int quark, List<String> pattern) { try { String element = pattern.get(0); List<String> remainder = pattern.subList(1, pattern.size()); if (remainder.isEmpty()) { if (element.equals(WILDCARD)) { builder.addAll(getSubAttributes(quark, false)); } else if (element.equals(PARENT)){ builder.add(getParentAttributeQuark(quark)); } else { builder.add(getQuarkRelative(quark, element)); } } else { if (element.equals(WILDCARD)) { for (@NonNull Integer subquark : getSubAttributes(quark, false)) { getQuarks(builder, subquark, remainder); } } else if (element.equals(PARENT)){ getQuarks(builder, getParentAttributeQuark(quark), remainder); } else { getQuarks(builder, getQuarkRelative(quark, element), remainder); } } } catch (AttributeNotFoundException e) { } }

Target:
private void getQuarks(Builder<@NonNull Integer> builder, int quark, List<String> pattern) { try { String element = pattern.get(0); if (element == null) { return; } List<String> remainder = pattern.subList(1, pattern.size()); if (remainder.isEmpty()) { if (element.equals(WILDCARD)) { builder.addAll(getSubAttributes(quark, false)); } else if (element.equals(PARENT)){ builder.add(getParentAttributeQuark(quark)); } else { int subQuark = optQuarkRelative(quark, element); if (subQuark != INVALID_ATTRIBUTE) { builder.add(subQuark); } } } else { if (element.equals(WILDCARD)) { for (@NonNull Integer subquark : getSubAttributes(quark, false)) { getQuarks(builder, subquark, remainder); } } else if (element.equals(PARENT)){ getQuarks(builder, getParentAttributeQuark(quark), remainder); } else { int subQuark = optQuarkRelative(quark, element); if (subQuark != INVALID_ATTRIBUTE) { getQuarks(builder, subQuark, remainder); } } } } catch (AttributeNotFoundException e) { throw new IndexOutOfBoundsException(String.format("Index: %d, Size: %d", quark, getNbAttributes())); } }
Source:
public EnvironmentConfig getEnvironmentConfig(String environmentName) throws NoSuchEnvironmentException { if(environments.hasEnvironmentNamed(new CaseInsensitiveString(environmentName))) return environments.named(new CaseInsensitiveString(environmentName)); return null; }

Target:
public EnvironmentConfig getEnvironmentConfig(String environmentName) throws NoSuchEnvironmentException { return environments.named(new CaseInsensitiveString(environmentName)); }
Source:
public void releaseCursor(Cursor cursor) { try { cursor.release(); if (cursors.remove(cursor)) { if (provider.isClosed() && cursors.isEmpty()) { releaseResources(); } } } catch (Exception e) { LOGGER.warn("Exception was found trying to release cursor resources. Execution will continue", e); } finally { statistics.decrementOpenCursors(); } }

Target:
public void releaseCursor(Cursor cursor) { try { cursor.release(); if (cursors.remove(cursor) && provider.isClosed() && cursors.isEmpty()) { releaseResources(); } } catch (Exception e) { LOGGER.warn("Exception was found trying to release cursor resources. Execution will continue", e); } finally { statistics.decrementOpenCursors(); } }
Source:
public void insertRow(RowWithMetaData metaData, Object[] values) throws InterruptedException { while (true) { try { PartitionSingleExecuteProcedureCallback cbmt = new PartitionSingleExecuteProcedureCallback(metaData); if (!m_client.callProcedure(cbmt, m_insertProcedure, values)) { m_log.fatal("Failed to send CSV insert to VoltDB cluster."); ClientResponse response = new ClientResponseImpl(ClientResponseImpl.SERVER_UNAVAILABLE, new VoltTable[0], "Failed to call procedure.", 0); m_errHandler.handleError(metaData, response, "Failed to call procedure."); } break; } catch (NoConnectionsException ex) { Thread.sleep(1000); } catch (IOException ex) { Thread.sleep(1000); } catch (Exception ex) { m_errHandler.handleError(metaData, null, ex.toString()); } } }

Target:
public void insertRow(RowWithMetaData metaData, Object[] values) throws InterruptedException { m_totalRowCount.incrementAndGet(); insert(metaData, values); }
Source:
public List<Map<String, String>> linkify(HttpServletRequest req, String message) { String baseGerritUrl = urls.getBaseGerritUrl(req); CommentLinkInfo changeIds = new CommentLinkInfo("ChangeIdLinks", changeId, baseGerritUrl + "#/q/$2,n,z", ""); mCommentLinks.add(changeIds); List<Map<String, String>> parsed = Lists.newArrayList(); parsed.add(ImmutableMap.of("text", message)); for (CommentLinkInfo clp : mCommentLinks) { for (int index = 0; index < parsed.size(); index++) { Map<String, String> piece = parsed.get(index); if (piece.get("url") == null) { List<Map<String, String>> resultingReplacement = clp.replace(piece.get("text")); if (resultingReplacement != null) { parsed.remove(index); for (Map<String, String> it : resultingReplacement) { parsed.add(index, it); index++; } } } } } mCommentLinks.remove(mCommentLinks.size() - 1); return parsed; }

Target:
public List<Map<String, String>> linkify(HttpServletRequest req, String message) { String baseGerritUrl = urls.getBaseGerritUrl(req); CommentLinkInfo changeIds = new CommentLinkInfo("ChangeIdLinks", CHANGE_ID_PATTERN, baseGerritUrl + "#/q/$2,n,z", ""); List<CommentLinkInfo> operationalCommentLinks = new ArrayList<CommentLinkInfo>(commentLinks); operationalCommentLinks.add(changeIds); List<Map<String, String>> parsed = Lists.newArrayList(); parsed.add(ImmutableMap.of("text", message)); for (int index = 0; index < parsed.size(); index++) { Map<String, String> piece = parsed.get(index); if (piece.get("url") == null) { String text = piece.get("text"); Matcher m = allPattern.matcher(text); if (m.find()) { for (CommentLinkInfo clp : operationalCommentLinks) { List<Map<String, String>> resultingReplacement = clp.replace(piece.get("text")); if (resultingReplacement != null) { parsed.remove(index); for (Map<String, String> it : resultingReplacement) { parsed.add(index, it); index++; } } } } } } return parsed; }
Source:
public final void disconnect(Optional<? extends ConnectionAnchor> anchor) { disconnect(anchor.orElse(null)); }

Target:
public final void disconnect(Optional<? extends ConnectionAnchor> anchor) { anchor.ifPresent(this::disconnect); }
Source:
public void returnsCorrectLengthWithUrl() throws Exception { final Path file = BodyUrlTest.createTempFile(); try { final byte[] bytes = new Utf8String("URL returnsCorrectLength!").asBytes(); try (InputStream input = new InputOf(bytes).stream()) { Files.copy(input, file, StandardCopyOption.REPLACE_EXISTING); } MatcherAssert.assertThat( "Body content of Body.Url doesn't have the correct length", new LengthOf(new Body.Url(file.toUri().toURL())).intValue(), new IsEqual<>(bytes.length) ); } finally { Files.deleteIfExists(file); } }

Target:
public void returnsCorrectLengthWithUrl() throws Exception { try (TempFile file = new TempFile()) { final Bytes body = new Utf8String("URL returnsCorrectLength!"); try (OutputStream outStream = new OutputTo(file.value()).stream()) { new LengthOf( new TeeInput(body, new OutputTo(outStream)) ).intValue(); } MatcherAssert.assertThat( "Body content of Body.Url doesn't have the correct length", new LengthOf( new Body.Url(file.value().toUri().toURL()) ).intValue(), new IsEqual<>(body.asBytes().length) ); } }
Source:
public void disconnect() throws IOException { if (forwarders != null) { for (LocalPortForwarder forwarder : forwarders) { try { forwarder.close(); } catch (IOException e) { log.warn("Error closing forwarder", e); } } } trans.disconnect(); super.disconnect(); }

Target:
public void disconnect() throws IOException { for (LocalPortForwarder forwarder : forwarders) { try { forwarder.close(); } catch (IOException e) { log.warn("Error closing forwarder", e); } } forwarders.clear(); trans.disconnect(); super.disconnect(); }