auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public static void runRebaseJob(final Repository repository, String jobname, Ref ref) { final RebaseOperation rebase = new RebaseOperation(repository, ref); Job job = new Job(jobname) { @Override protected IStatus run(IProgressMonitor monitor) { if (!repository.getRepositoryState().equals( RepositoryState.SAFE)) throw new IllegalStateException("Can't nest rebase"); try { rebase.execute(monitor); } catch (final CoreException e) { if (!repository.getRepositoryState().equals( RepositoryState.SAFE)) { try { new RebaseOperation(repository, Operation.ABORT) .execute(monitor); } catch (CoreException e1) { return createMultiStatus(e, e1); } } return e.getStatus(); } return Status.OK_STATUS; } }; job.setUser(true); job.setRule(rebase.getSchedulingRule()); job.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent cevent) { IStatus result = cevent.getJob().getResult(); if (result.getSeverity() == IStatus.CANCEL) { Display.getDefault().asyncExec(new Runnable() { public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); MessageDialog .openInformation( shell, UIText.RebaseCurrentRefCommand_RebaseCanceledTitle, UIText.RebaseCurrentRefCommand_RebaseCanceledMessage); } }); } else if (result.isOK()) { RebaseResultDialog.show(rebase.getResult(), repository); } } }); job.schedule(); }

Target:
public static void runRebaseJob(final Repository repository, String jobname, Ref ref) { final RebaseOperation rebase = new RebaseOperation(repository, ref); Job job = new Job(jobname) { @Override protected IStatus run(IProgressMonitor monitor) { if (!repository.getRepositoryState().equals( RepositoryState.SAFE)) throw new IllegalStateException( "Can't start rebase if repository state isn't SAFE"); try { rebase.execute(monitor); } catch (final CoreException e) { if (!repository.getRepositoryState().equals( RepositoryState.SAFE)) { try { new RebaseOperation(repository, Operation.ABORT) .execute(monitor); } catch (CoreException e1) { return createMultiStatus(e, e1); } } return e.getStatus(); } return Status.OK_STATUS; } }; job.setUser(true); job.setRule(rebase.getSchedulingRule()); job.addJobChangeListener(new JobChangeAdapter() { @Override public void done(IJobChangeEvent cevent) { IStatus result = cevent.getJob().getResult(); if (result.getSeverity() == IStatus.CANCEL) { Display.getDefault().asyncExec(new Runnable() { public void run() { Shell shell = PlatformUI.getWorkbench() .getActiveWorkbenchWindow().getShell(); MessageDialog .openInformation( shell, UIText.RebaseCurrentRefCommand_RebaseCanceledTitle, UIText.RebaseCurrentRefCommand_RebaseCanceledMessage); } }); } else if (result.isOK()) { RebaseResultDialog.show(rebase.getResult(), repository); } } }); job.schedule(); }
Source:
public InputReader(InputStream inputStream, @Nullable final ICommandOutputListener listener, final boolean isStdOut) { fResult = new StringBuilder(); fReader = new InputStreamReader(inputStream); fThread = new Thread() { @Override public void run() { final char[] buffer = new char[BYTES_PER_KB]; int read; try { while (!fDone && (read = fReader.read(buffer)) > 0) { fResult.append(buffer, 0, read); if (listener != null) { if (isStdOut) { listener.outputUpdated(checkNotNull(String.valueOf(buffer, 0, read))); } else { listener.errorOutputUpdated(checkNotNull(String.valueOf(buffer, 0, read))); } } } } catch (IOException e) { } } }; fThread.start(); }

Target:
public InputReader(InputStream inputStream, @Nullable final ICommandOutputListener listener, final boolean isStdOut) { fResult = new StringBuilder(); fReader = new InputStreamReader(inputStream); fThread = new Thread() { @Override public void run() { final char[] buffer = new char[BYTES_PER_KB]; int read; try { while (!fDone && (read = fReader.read(buffer)) > 0) { fResult.append(buffer, 0, read); if (listener != null) { if (isStdOut) { listener.outputUpdated(String.valueOf(buffer, 0, read)); } else { listener.errorOutputUpdated(String.valueOf(buffer, 0, read)); } } } } catch (IOException e) { } } }; fThread.start(); }
Source:
public void getParam(String key){ this.params.get(key); }

Target:
public Param<?> getParam(String key){ return this.params.get(key); }
Source:
private OnHeapValueHolder<V> internalGet(final K key, final boolean updateAccess) throws CacheAccessException { getObserver.begin(); try { OnHeapValueHolder<V> result = map.computeIfPresent(key, new BiFunction<K, OnHeapValueHolder<V>, OnHeapValueHolder<V>>() { @Override public OnHeapValueHolder<V> apply(K mappedKey, OnHeapValueHolder<V> mappedValue) { final long now = timeSource.getTimeMillis(); if (mappedValue.isExpired(now, TimeUnit.MILLISECONDS)) { onExpiration(mappedKey, mappedValue); return null; } if (updateAccess) { if (setAccessTimeAndExpiryThenReturnMapping(key, mappedValue, now) == null) { onExpiration(mappedKey, mappedValue); return null; } } return mappedValue; } }); if (result == null) { getObserver.end(StoreOperationOutcomes.GetOutcome.MISS); } else { getObserver.end(StoreOperationOutcomes.GetOutcome.HIT); } return result; } catch (RuntimeException re) { handleRuntimeException(re); return null; } }

Target:
private OnHeapValueHolder<V> internalGet(final K key, final boolean updateAccess) throws CacheAccessException { getObserver.begin(); try { OnHeapValueHolder<V> result = map.computeIfPresent(key, new BiFunction<K, OnHeapValueHolder<V>, OnHeapValueHolder<V>>() { @Override public OnHeapValueHolder<V> apply(K mappedKey, OnHeapValueHolder<V> mappedValue) { final long now = timeSource.getTimeMillis(); if (mappedValue.isExpired(now, TimeUnit.MILLISECONDS)) { onExpiration(mappedKey, mappedValue); return null; } if (updateAccess) { return setAccessTimeAndExpiryThenReturnMapping(key, mappedValue, now, false); } return mappedValue; } }); if (result == null) { getObserver.end(StoreOperationOutcomes.GetOutcome.MISS); } else { getObserver.end(StoreOperationOutcomes.GetOutcome.HIT); } return result; } catch (RuntimeException re) { handleRuntimeException(re); return null; } }
Source:
private M mergeOldAndNewMetadata(@Nonnull M previousMetadata, @Nullable M userMetadata, boolean isCreate) { M.Builder builder = previousMetadata.toBuilder(); for (Descriptors.FieldDescriptor fieldDescriptor : previousMetadata.getDescriptorForType().getFields()) { if (fieldDescriptor.getOptions().getExtension(CorfuOptions.schema).getVersion()) { builder.setField( fieldDescriptor, Optional.ofNullable(previousMetadata.getField(fieldDescriptor)) .map(previousVersion -> (isCreate ? 0L : ((Long) previousVersion) + 1)) .orElse(0L)); } else if (fieldDescriptor.isRepeated()) { int count = previousMetadata.getRepeatedFieldCount(fieldDescriptor); for (int i = 0; i < count; i++) { builder.setRepeatedField(fieldDescriptor, i, previousMetadata.getRepeatedField(fieldDescriptor, i)); } } else if (userMetadata != null) { if (!userMetadata.hasField(fieldDescriptor)) { builder.setField(fieldDescriptor, previousMetadata.getField(fieldDescriptor)); } else { builder.setField(fieldDescriptor, userMetadata.getField(fieldDescriptor)); } } } return (M) builder.build(); }

Target:
private M mergeOldAndNewMetadata(@Nonnull M previousMetadata, @Nullable M userMetadata, boolean isCreate) { M.Builder builder = previousMetadata.toBuilder(); for (Descriptors.FieldDescriptor fieldDescriptor : previousMetadata.getDescriptorForType().getFields()) { if (fieldDescriptor.getOptions().getExtension(CorfuOptions.schema).getVersion()) { builder.setField( fieldDescriptor, Optional.ofNullable(previousMetadata.getField(fieldDescriptor)) .map(previousVersion -> (isCreate ? 0L : ((Long) previousVersion) + 1)) .orElse(0L)); } else if (fieldDescriptor.isRepeated()) { if (userMetadata != null) { try { int count = userMetadata.getRepeatedFieldCount(fieldDescriptor); for (int i = 0; i < count; i++) { builder.setRepeatedField(fieldDescriptor, i, userMetadata.getRepeatedField(fieldDescriptor, i)); } } catch (IllegalArgumentException iae) { int count = previousMetadata.getRepeatedFieldCount(fieldDescriptor); for (int i = 0; i < count; i++) { builder.setRepeatedField(fieldDescriptor, i, previousMetadata.getRepeatedField(fieldDescriptor, i)); } } } } else if (userMetadata != null) { if (!userMetadata.hasField(fieldDescriptor)) { builder.setField(fieldDescriptor, previousMetadata.getField(fieldDescriptor)); } else { builder.setField(fieldDescriptor, userMetadata.getField(fieldDescriptor)); } } } return (M) builder.build(); }
Source:
protected MergeResult<RawText> contentMerge(CanonicalTreeParser base, CanonicalTreeParser ours, CanonicalTreeParser theirs) throws IOException { RawText baseText = base == null ? RawText.EMPTY_TEXT : getRawText( base.getEntryObjectId(), db); RawText ourText = ours == null ? RawText.EMPTY_TEXT : getRawText( ours.getEntryObjectId(), db); RawText theirsText = theirs == null ? RawText.EMPTY_TEXT : getRawText( theirs.getEntryObjectId(), db); return (mergeAlgorithm.merge(RawTextComparator.DEFAULT, baseText, ourText, theirsText)); }

Target:
private MergeResult<RawText> contentMerge(CanonicalTreeParser base, CanonicalTreeParser ours, CanonicalTreeParser theirs) throws IOException { RawText baseText = base == null ? RawText.EMPTY_TEXT : getRawText( base.getEntryObjectId(), db); RawText ourText = ours == null ? RawText.EMPTY_TEXT : getRawText( ours.getEntryObjectId(), db); RawText theirsText = theirs == null ? RawText.EMPTY_TEXT : getRawText( theirs.getEntryObjectId(), db); return (mergeAlgorithm.merge(RawTextComparator.DEFAULT, baseText, ourText, theirsText)); }
Source:
public void shouldReportNodesThatAreNotIndexed() throws Exception { IndexSamplingConfig samplingConfig = new IndexSamplingConfig( Config.empty() ); Iterator<IndexRule> indexRuleIterator = new SchemaStorage( fixture.directStoreAccess().nativeStores().getSchemaStore() ).indexesGetAll(); while ( indexRuleIterator.hasNext() ) { IndexRule indexRule = indexRuleIterator.next(); IndexAccessor accessor = fixture.directStoreAccess().indexes(). apply( indexRule.getProviderDescriptor() ).getOnlineAccessor( indexRule.getId(), indexRule.getIndexDescriptor(), samplingConfig ); IndexUpdater updater = accessor.newUpdater( IndexUpdateMode.ONLINE ); updater.remove( asPrimitiveLongSet( indexedNodes ) ); updater.close(); accessor.force(); accessor.close(); } ConsistencySummaryStatistics stats = check(); on( stats ).verify( RecordType.NODE, 3 ) .andThatsAllFolks(); }

Target:
public void shouldReportNodesThatAreNotIndexed() throws Exception { IndexSamplingConfig samplingConfig = new IndexSamplingConfig( Config.defaults() ); Iterator<IndexRule> indexRuleIterator = new SchemaStorage( fixture.directStoreAccess().nativeStores().getSchemaStore() ).indexesGetAll(); while ( indexRuleIterator.hasNext() ) { IndexRule indexRule = indexRuleIterator.next(); IndexAccessor accessor = fixture.directStoreAccess().indexes(). apply( indexRule.getProviderDescriptor() ).getOnlineAccessor( indexRule.getId(), indexRule.getIndexDescriptor(), samplingConfig ); IndexUpdater updater = accessor.newUpdater( IndexUpdateMode.ONLINE ); updater.remove( asPrimitiveLongSet( indexedNodes ) ); updater.close(); accessor.force(); accessor.close(); } ConsistencySummaryStatistics stats = check(); on( stats ).verify( RecordType.NODE, 3 ) .andThatsAllFolks(); }
Source:
protected SimpleKeyManagerFactory() { this(""); }

Target:
protected SimpleKeyManagerFactory() { this(StringUtil.EMPTY_STRING); }
Source:
public static Predicate<Element> hasModifiers(Modifier... modifiers) { final Collection<Modifier> modifierCollection = Lists.newArrayList(modifiers); return new Predicate<Element>() { @Override public boolean apply(Element input) { return input.getModifiers().containsAll(modifierCollection); } }; }

Target:
public static Predicate<Element> hasModifiers(Modifier... modifiers) { return hasModifiers(ImmutableSet.copyOf(modifiers)); }
Source:
public static IDeploymentConfig getDeploymentConfig(IServerAttributes attributes) { String dcKey = "deploymentconfig"; IService service = getService(attributes); if (service == null) { return null; } String dcName = service.getPods().stream().filter(p -> p.getLabels().containsKey(dcKey)) .findFirst() .map(p -> p.getLabels().get(dcKey)) .orElse(null); if (dcName == null) { return null; } Connection connection = getConnection(attributes); if (connection == null) { return null; } IDeploymentConfig dc = connection.getResource(ResourceKind.DEPLOYMENT_CONFIG, service.getNamespace(), dcName); return dc; }

Target:
public static IDeploymentConfig getDeploymentConfig(IServerAttributes attributes) { IService service = getService(attributes); if (service == null) { return null; } String dcName = service.getPods().stream().filter(p -> p.getLabels().containsKey(DEPLOYMENT_CONFIG_KEY)) .findFirst() .map(p -> p.getLabels().get(DEPLOYMENT_CONFIG_KEY)) .orElse(null); if (dcName == null) { return null; } Connection connection = getConnection(attributes); if (connection == null) { return null; } IDeploymentConfig dc = connection.getResource(ResourceKind.DEPLOYMENT_CONFIG, service.getNamespace(), dcName); return dc; }
Source:
private void updateGMFFontStyle(View view, BasicLabelStyle basicLabelStyle) { FontStyle fontStyle = (FontStyle) createOrFindStyle(view, NotationPackage.eINSTANCE.getFontStyle()); List<FontFormat> labelFormat = basicLabelStyle.getLabelFormat(); fontStyle.setBold(false); fontStyle.setItalic(false); fontStyle.setUnderline(false); fontStyle.setStrikeThrough(false); for (FontFormat fontFormat : labelFormat) { switch (fontFormat.getValue()) { case FontFormat.BOLD: fontStyle.setBold(true); break; case FontFormat.ITALIC: fontStyle.setItalic(true); break; case FontFormat.UNDERLINE: fontStyle.setUnderline(true); break; case FontFormat.STRIKE_THROUGH: fontStyle.setStrikeThrough(true); break; default: break; } } fontStyle.setFontHeight(basicLabelStyle.getLabelSize()); if (fontStyle.getFontName() == null) { fontStyle.setFontName(DEFAULT_FONT_STYLE); } RGBValues labelColor = basicLabelStyle.getLabelColor(); if (labelColor != null) { fontStyle.setFontColor(FigureUtilities.RGBToInteger(new RGB(labelColor.getRed(), labelColor.getGreen(), labelColor.getBlue()))); } }

Target:
private void updateGMFFontStyle(View view, BasicLabelStyle basicLabelStyle) { FontStyle fontStyle = (FontStyle) createOrFindStyle(view, NotationPackage.eINSTANCE.getFontStyle()); List<FontFormat> labelFormat = basicLabelStyle.getLabelFormat(); if (fontStyle.isBold() != labelFormat.contains(FontFormat.BOLD_LITERAL)) { fontStyle.setBold(labelFormat.contains(FontFormat.BOLD_LITERAL)); } if (fontStyle.isItalic() != labelFormat.contains(FontFormat.ITALIC_LITERAL)) { fontStyle.setItalic(labelFormat.contains(FontFormat.ITALIC_LITERAL)); } if (fontStyle.isUnderline() != labelFormat.contains(FontFormat.UNDERLINE_LITERAL)) { fontStyle.setUnderline(labelFormat.contains(FontFormat.UNDERLINE_LITERAL)); } if (fontStyle.isStrikeThrough() != labelFormat.contains(FontFormat.STRIKE_THROUGH_LITERAL)) { fontStyle.setStrikeThrough(labelFormat.contains(FontFormat.STRIKE_THROUGH_LITERAL)); } fontStyle.setFontHeight(basicLabelStyle.getLabelSize()); if (fontStyle.getFontName() == null) { fontStyle.setFontName(DEFAULT_FONT_STYLE); } RGBValues labelColor = basicLabelStyle.getLabelColor(); if (labelColor != null) { fontStyle.setFontColor(FigureUtilities.RGBToInteger(new RGB(labelColor.getRed(), labelColor.getGreen(), labelColor.getBlue()))); } }
Source:
private Iterator<HiveFileInfo> getLocatedFileStatusRemoteIterator(Path path, PathFilter pathFilter) { try (TimeStat.BlockTimer ignored = namenodeStats.getListLocatedStatus().time()) { return new FileStatusIterator(path, listDirectoryOperation, namenodeStats, pathFilter); } }

Target:
private Iterator<HiveFileInfo> getLocatedFileStatusRemoteIterator(Path path, PathFilter pathFilter) { try (TimeStat.BlockTimer ignored = namenodeStats.getListLocatedStatus().time()) { return Iterators.filter(new FileStatusIterator(path, listDirectoryOperation, namenodeStats), input -> pathFilter.accept(input.getPath())); } }
Source:
public Iterable<String> precompiledHeaderArgs(Path pchOutputPath) { String hFilename = pchOutputPath.getFileName().toString(); String pchFilename = hFilename.substring(0, hFilename.length() - 4) + ".pch"; return ImmutableList.of("/Yu", pchFilename); }

Target:
public Iterable<String> precompiledHeaderArgs(Path pchOutputPath) { String hFilename = pchOutputPath.getFileName().toString(); String pchFilename = Files.getNameWithoutExtension(hFilename) + ".pch"; return ImmutableList.of("/Yu", pchFilename); }
Source:
private String tokenPayload(CardAuthorisationGatewayRequest request) { List<BasicNameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("card[cvc]", request.getAuthCardDetails().getCvc())); params.add(new BasicNameValuePair("card[exp_month]", request.getAuthCardDetails().expiryMonth())); params.add(new BasicNameValuePair("card[exp_year]", request.getAuthCardDetails().expiryYear())); params.add(new BasicNameValuePair("card[number]", request.getAuthCardDetails().getCardNo())); params.add(new BasicNameValuePair("card[name]", request.getAuthCardDetails().getCardHolder())); if (request.getAuthCardDetails().getAddress().isPresent()) { Address address = request.getAuthCardDetails().getAddress().get(); params.add(new BasicNameValuePair("card[address_line1]", address.getLine1())); params.add(new BasicNameValuePair("card[address_line2]", address.getLine2())); params.add(new BasicNameValuePair("card[address_city]", address.getCity())); params.add(new BasicNameValuePair("card[address_country]", address.getCountry())); params.add(new BasicNameValuePair("card[address_zip]", address.getPostcode())); } return URLEncodedUtils.format(params, UTF_8); }

Target:
private String tokenPayload(CardAuthorisationGatewayRequest request) { List<BasicNameValuePair> params = new ArrayList<>(); params.add(new BasicNameValuePair("card[cvc]", request.getAuthCardDetails().getCvc())); params.add(new BasicNameValuePair("card[exp_month]", request.getAuthCardDetails().expiryMonth())); params.add(new BasicNameValuePair("card[exp_year]", request.getAuthCardDetails().expiryYear())); params.add(new BasicNameValuePair("card[number]", request.getAuthCardDetails().getCardNo())); params.add(new BasicNameValuePair("card[name]", request.getAuthCardDetails().getCardHolder())); request.getAuthCardDetails().getAddress().ifPresent(address -> { params.add(new BasicNameValuePair("card[address_line1]", address.getLine1())); if (StringUtils.isNotBlank(address.getLine2())) { params.add(new BasicNameValuePair("card[address_line2]", address.getLine2())); } params.add(new BasicNameValuePair("card[address_city]", address.getCity())); params.add(new BasicNameValuePair("card[address_country]", address.getCountry())); params.add(new BasicNameValuePair("card[address_zip]", address.getPostcode())); }); return URLEncodedUtils.format(params, UTF_8); }
Source:
protected EmbeddedCacheManager addClusterEnabledCacheManager(TransportFlags flags, GlobalConfigurationBuilder gcb, ConfigurationBuilder builder) { GlobalConfigurationBuilder clone = GlobalConfigurationBuilder.defaultClusteredBuilder(); Transport transport = clone.transport().getTransport(); GlobalConfiguration original = gcb.build(); clone.read(original); clone.transport().transport(transport); clone.serialization().addContextInitializer(TestDataSCI.INSTANCE); clone.transport().clusterName("ISPN(SITE " + siteName + ")"); if (original.globalJmxStatistics().enabled()) { clone.globalJmxStatistics().jmxDomain(original.globalJmxStatistics().domain() + cacheManagers.size()); } EmbeddedCacheManager cm = TestCacheManagerFactory.createClusteredCacheManager(clone, builder, flags); cacheManagers.add(cm); return cm; }

Target:
protected EmbeddedCacheManager addClusterEnabledCacheManager(TransportFlags flags, GlobalConfigurationBuilder gcb, ConfigurationBuilder builder) { GlobalConfigurationBuilder clone = GlobalConfigurationBuilder.defaultClusteredBuilder(); Transport transport = clone.transport().getTransport(); GlobalConfiguration original = gcb.build(); clone.read(original); clone.transport().transport(transport); clone.transport().clusterName("ISPN(SITE " + siteName + ")"); if (original.globalJmxStatistics().enabled()) { clone.globalJmxStatistics().jmxDomain(original.globalJmxStatistics().domain() + cacheManagers.size()); } EmbeddedCacheManager cm = TestCacheManagerFactory.createClusteredCacheManager(clone, builder, flags); cacheManagers.add(cm); return cm; }
Source:
public void write(ByteBuf src) throws IOException { int copied = 0; boolean shouldForceWrite = false; synchronized (this) { int len = src.readableBytes(); while (copied < len) { int bytesToCopy = Math.min(src.readableBytes() - copied, writeBuffer.writableBytes()); writeBuffer.writeBytes(src, src.readerIndex() + copied, bytesToCopy); copied += bytesToCopy; if (!writeBuffer.isWritable()) { flushInternal(); } } position.addAndGet(copied); unpersistedBytes.addAndGet(copied); if (unpersistedBytesBound > 0) { if (unpersistedBytes.get() >= unpersistedBytesBound) { flushInternal(); shouldForceWrite = true; } } } if (shouldForceWrite) { forceWrite(false); } }

Target:
public void write(ByteBuf src) throws IOException { int copied = 0; boolean shouldForceWrite = false; synchronized (this) { int len = src.readableBytes(); while (copied < len) { int bytesToCopy = Math.min(src.readableBytes() - copied, writeBuffer.writableBytes()); writeBuffer.writeBytes(src, src.readerIndex() + copied, bytesToCopy); copied += bytesToCopy; if (!writeBuffer.isWritable()) { flush(); } } position.addAndGet(copied); unpersistedBytes.addAndGet(copied); if (unpersistedBytesBound > 0) { if (unpersistedBytes.get() >= unpersistedBytesBound) { flush(); shouldForceWrite = true; } } } if (shouldForceWrite) { forceWrite(false); } }
Source:
public String getWorkflowConfigurationFileContents(String workflowId) throws Exception { File configDir = new File(WORKFLOW_CONFIGURATION_PATH); File defaultsDir = new File(DEFAULTS_CONFIGURATION_PATH); WorkflowConfigurationParser parser = new WorkflowConfigurationParser(defaultsDir).parseConfiguration(configDir); String filePath = parser.getWorkflowConfiguration().getWorkflowJSFileName(new WorkflowID(workflowId)); if (filePath == null) { return null; } try { return FileUtils.readFileToString(new File(filePath)); } catch (IOException e) { LOGGER.error("Failed to load JS config file: " + filePath + ": " + e.getMessage(), e); throw e; } }

Target:
public String getWorkflowConfigurationFileContents(String workflowId) throws Exception { WorkflowConfigurationParser parser = getWorkflowConfigurationParser(); String filePath = parser.getWorkflowConfiguration().getWorkflowJSFileName(new WorkflowID(workflowId)); if (filePath == null) { return null; } return FileUtils.readFileToString(new File(filePath)); }
Source:
public CompletableFuture<Void> deleteAsync(K key) { delete(key); return CompletableFuture.completedFuture(null); }

Target:
public CompletableFuture<Void> deleteAsync(K key) { CompletableFuture<Void> future = new CompletableFuture(); try { delete(key); future.complete(null); } catch (Exception e) { future.completeExceptionally(e); } return future; }
Source:
public void testPostNullMessage() throws Exception { WebResource resource = client().resource("/api/metrics/store"); WebResource.Builder builder = resource.type(MediaType.APPLICATION_JSON_TYPE); boolean badStatus = false; try { builder.post(Control.class, null); } catch (UniformInterfaceException e) { badStatus = true; assertEquals("Unexpected status", 400, e.getResponse().getClientResponseStatus().getStatusCode()); } if (!badStatus){ fail("expected 400 status"); } }

Target:
public void testPostNullMessage() throws Exception { WebResource resource = client().resource("/api/metrics/store"); WebResource.Builder builder = resource.type(MediaType.APPLICATION_JSON_TYPE); try { builder.post(Control.class, null); fail("expected 400 status"); } catch (UniformInterfaceException e) { assertEquals("Unexpected status", 400, e.getResponse().getClientResponseStatus().getStatusCode()); } }
Source:
public boolean renderFileFromAttachment(String filename, XWikiDocument doc, XWikiContext context) throws IOException, XWikiException { _Logger.debug("... as attachment"); try { IAttFileNameMatcherRole matcher = Utils.getComponent(IAttFileNameMatcherRole.class); 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; }

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:
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); validateContainerReferenceContext(); checkReferenceContexts(commonRefContext.getReferenceContextID()); }

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:
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; } return getVdsToRunOn(Arrays.asList(new VDS[] { target_vds })); } } return Guid.Empty; }

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:
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); when(this.scheduledTaskRepository.findByCorrelationUid(anyString())).thenReturn(scheduledTask); this.deviceResponseMessageService.processMessage(message); verify(this.domainResponseMessageSender, never()).send(message); verify(this.scheduledTaskRepository, never()).delete(scheduledTask); assertEquals(new Timestamp(scheduledRetryTime.getTime()), scheduledTask.getscheduledTime()); }

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:
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, 1024 * 1024), newSimpleAggregatedMemoryContext(), sliceInput.getRetainedSize()), signed); } catch (OrcCorruptionException e) { throw new UncheckedIOException("Unable to create LongInputStream from LongOutputStream", e); } }

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:
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) .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 ); tripPatternsForDate.add(tripPatternForDate); } tripPatternsByStopByDate.put(localDate, tripPatternsForDate); } for (List<TripPatternForDate> list : tripPatternsByStopByDate.values()) { list.sort(Comparator.comparingInt(p -> p.getTripPattern().getId())); } return tripPatternsByStopByDate; }

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:
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; } } readHostControllerStatus(getDomainSlaveClient(), TIMEOUT); }

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:
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); } } } } 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; } }

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:
public String toString() { String str = "push " + uri + " " + getRefs().toString(); if (retryCount == 0) { return str; } return "(retry " + retryCount + ") " + str; }

Target:
public String toString() { String print = "[" + HexFormat.fromInt(id) + "] push " + uri + " " + getRefs().toString(); if (retryCount > 0) { print = "(retry " + retryCount + ") " + print; } return print; }
Source:
public List<Sample> getLastWeek( @Scope({OAuthScope.SENSORS_BASIC}) final AccessToken accessToken, @PathParam("sensor") final String sensor, @QueryParam("from") Long clientUtcTimestamp) { final int slotDurationInMinutes = 5; final int queryDurationInHours = 24; validateQueryRange(clientUtcTimestamp, DateTime.now(), accessToken.accountId, allowedRangeInSeconds); return deviceDataDAO.generateTimeSerie(clientUtcTimestamp, accessToken.accountId, slotDurationInMinutes, queryDurationInHours, sensor); }

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:
public void setUp() throws Exception { assumeTrue(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(); }

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:
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: String message = responseAsString; 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(); } } }

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:
private boolean isMavenProject() { return model.getLocation().append("pom.xml").toFile().exists(); }

Target:
private boolean isMavenProject() { return model.getLocation().append(MAVEN_POM_XML_FILE).toFile().exists(); }
Source:
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; } 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; }

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; }