auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
private Set<OmniEclipseProject> fetchEclipseProjects(GradleBuild build, SubMonitor progress) { progress.setTaskName("Loading Gradle project models"); Collection<EclipseProject> models = build.fetchCompositeModel(EclipseProject.class, getToken(), progress); ImmutableSet.Builder<OmniEclipseProject> projects = ImmutableSet.builder(); for (EclipseProject model : models) { projects.addAll(DefaultOmniEclipseProject.from(model).getAll()); } return projects.build(); }

Target:
private Set<OmniEclipseProject> fetchEclipseProjects(GradleBuild build, SubMonitor progress) { progress.setTaskName("Loading Gradle project models"); ModelProvider modelProvider = build.getModelProvider(); return modelProvider.fetchEclipseGradleProjects(FetchStrategy.FORCE_RELOAD, getToken(), progress); }
Source:
public ColumnGroupReader( StreamReader[] streamReaders, Set<Integer> presentColumns, int[] channelColumns, List<Type> types, int[] internalChannels, int[] outputChannels, Map<Integer, Filter> filters, FilterFunction[] filterFunctions, boolean enforceMemoryBudget, Block[] constantBlocks) { this.reorderFilters = true; this.enforceMemoryBudget = enforceMemoryBudget; this.outputChannels = requireNonNull(outputChannels, "outputChannels is null"); this.constantBlocks = constantBlocks; channelToStreamReader = new HashMap(); for (int i = 0; i < channelColumns.length; i++) { int columnIndex = channelColumns[i]; if (presentColumns != null && !presentColumns.contains(columnIndex)) { continue; } int internalChannel = i < internalChannels.length ? internalChannels[i] : -1; Filter filter = filters.get(columnIndex); if (internalChannel == -1 && filter == null) { if (streamReaders[columnIndex] != null) { throw new IllegalArgumentException("There should be no StreamReader if there is no filter and the value of the column is unreferenced"); } continue; } StreamReader streamReader = streamReaders[columnIndex]; streamReader.setFilterAndChannel(filter, internalChannel, columnIndex, types.get(i)); if (internalChannel != -1) { channelToStreamReader.put(internalChannel, streamReader); } } this.filterFunctions = requireNonNull(filterFunctions, "filterFunctions is null"); for (int i = 0; i < outputChannels.length; i++) { maxOutputChannel = Math.max(maxOutputChannel, outputChannels[i]); } setupStreamOrder(streamReaders); }

Target:
public ColumnGroupReader( StreamReader[] streamReaders, Set<Integer> presentColumns, int[] channelColumns, List<Type> types, int[] internalChannels, int[] outputChannels, Map<Integer, Filter> filters, FilterFunction[] filterFunctions, boolean enforceMemoryBudget, Block[] constantBlocks) { this.reorderFilters = true; this.enforceMemoryBudget = enforceMemoryBudget; this.outputChannels = requireNonNull(outputChannels, "outputChannels is null"); this.constantBlocks = requireNonNull(constantBlocks, "constantBlocks is null"); channelToStreamReader = new HashMap(); for (int i = 0; i < channelColumns.length; i++) { int columnIndex = channelColumns[i]; if (presentColumns != null && !presentColumns.contains(columnIndex)) { continue; } int internalChannel = i < internalChannels.length ? internalChannels[i] : -1; Filter filter = filters.get(columnIndex); if (internalChannel == -1 && filter == null) { if (streamReaders[columnIndex] != null) { throw new IllegalArgumentException("There should be no StreamReader if there is no filter and the value of the column is unreferenced"); } continue; } StreamReader streamReader = streamReaders[columnIndex]; streamReader.setFilterAndChannel(filter, internalChannel, columnIndex, types.get(i)); if (internalChannel != -1) { channelToStreamReader.put(internalChannel, streamReader); } } this.filterFunctions = requireNonNull(filterFunctions, "filterFunctions is null"); for (int i = 0; i < outputChannels.length; i++) { maxOutputChannel = Math.max(maxOutputChannel, outputChannels[i]); } setupStreamOrder(streamReaders); }
Source:
private void cancel(Job[] jobs) { for (Job job : jobs) { job.cancel(); } }

Target:
private void cancel(Job[] jobs) { for (Job job : jobs) job.cancel(); }
Source:
public boolean onCreateOptionsMenu(Menu menu) { menu.clear(); getSupportMenuInflater().inflate(R.menu.main_menu, menu); statsModeMenuItem = menu.findItem(R.id.itemMainmenuStatsMode); if (isRefreshing()) { if (swipeRefresh != null && !swipeRefresh.isRefreshing()) swipeRefresh.setRefreshing(true); } updateStatsMode(); return true; }

Target:
public boolean onCreateOptionsMenu(Menu menu) { menu.clear(); getSupportMenuInflater().inflate(R.menu.main_menu, menu); statsModeMenuItem = menu.findItem(R.id.itemMainmenuStatsMode); if (isRefreshing()) menu.findItem(R.id.itemMainmenuRefresh).setActionView( R.layout.action_bar_indeterminate_progress); updateStatsMode(); return true; }
Source:
default AnnotatedTypeConfigurator<T> configure() { return null; }

Target:
public default AnnotatedTypeConfigurator<T> configure() { throw new UnsupportedOperationException("Configuration not supported here"); }
Source:
public List<Aggregator> generateInternalAggs(final Schema inputSchema) throws DbException { Objects.requireNonNull(inputSchema, "inputSchema"); Preconditions.checkArgument( initializers.size() == updaters.size(), "must have the same number of aggregate state initializers (%s) and updaters (%s)", initializers.size(), updaters.size()); for (int i = 0; i < initializers.size(); i++) { Preconditions.checkArgument( Objects.equals(initializers.get(i).getOutputName(), updaters.get(i).getOutputName()), "initializers[i] and updaters[i] have different names (%s) != (%s)", initializers.get(i).getOutputName(), updaters.get(i).getOutputName()); } Schema stateSchema = generateStateSchema(inputSchema); initEvaluator = getEvalScript(initializers, new ExpressionOperatorParameter(inputSchema)); updateEvaluator = getEvalScript(updaters, new ExpressionOperatorParameter(inputSchema, stateSchema)); ExpressionOperatorParameter emitParams = new ExpressionOperatorParameter(null, stateSchema); ImmutableList.Builder<Type> types = ImmutableList.builder(); ImmutableList.Builder<String> names = ImmutableList.builder(); for (Expression e : emitters) { types.add(e.getOutputType(emitParams)); names.add(e.getOutputName()); } resultSchema = new Schema(types, names); return ImmutableList.of( new UserDefinedAggregator(initEvaluator, updateEvaluator, resultSchema, stateSchema)); }

Target:
public List<Aggregator> generateInternalAggs(final Schema inputSchema) throws DbException { for (int i = 0; i < initializers.size(); ++i) { initEvaluators.add( getEvaluator(initializers.get(i), new ExpressionOperatorParameter(inputSchema), i)); } Schema stateSchema = generateStateSchema(inputSchema); ExpressionOperatorParameter param = new ExpressionOperatorParameter(inputSchema, stateSchema, pyFuncReg); for (int i = 0; i < updaters.size(); ++i) { if (updaters.get(i).isRegisteredPythonUDF()) { updateEvaluators.add(new PythonUDFEvaluator(updaters.get(i), param)); } else { updateEvaluators.add(getEvaluator(updaters.get(i), param, i)); } } ExpressionOperatorParameter emitParams = new ExpressionOperatorParameter(null, stateSchema); ImmutableList.Builder<Type> types = ImmutableList.builder(); ImmutableList.Builder<String> names = ImmutableList.builder(); for (Expression e : emitters) { types.add(e.getOutputType(emitParams)); names.add(e.getOutputName()); } resultSchema = new Schema(types, names); return ImmutableList.of( new UserDefinedAggregator(initEvaluators, updateEvaluators, resultSchema, stateSchema)); }
Source:
public void visitMethodInvocation(MethodInvocationTree mit) { super.visitMethodInvocation(mit); if (LOGGING_METHODS.anyMatch(mit)) { Iterator<UsageStatus> iterator = usageStatusStack.iterator(); while (iterator.hasNext()) { iterator.next().addLoggingMethodInvocation(mit); } } }

Target:
public void visitMethodInvocation(MethodInvocationTree mit) { super.visitMethodInvocation(mit); if (LOGGING_METHODS.anyMatch(mit)) { usageStatusStack.forEach(usageStatus -> usageStatus.addLoggingMethodInvocation(mit)); } }
Source:
public ExternalBeanDefinition(String beanInfo) throws Exception { if (beanInfo == null || beanInfo.isEmpty()) { throw new Exception("External type name missing"); } int lastPos = beanInfo.lastIndexOf("."); if (lastPos >= 0) { this.beanPackageName = beanInfo.substring(0, lastPos); this.beanName = beanInfo.substring(lastPos + 1); } else { this.beanPackageName = DEFAULT_BEAN_PKG; this.beanName = beanInfo; } }

Target:
public ExternalBeanDefinition(String beanInfo) throws IllegalArgumentException { if (beanInfo == null || beanInfo.isEmpty()) { throw new IllegalArgumentException("External type name missing"); } int lastPos = beanInfo.lastIndexOf("."); if (lastPos >= 0) { this.beanPackageName = beanInfo.substring(0, lastPos); this.beanName = beanInfo.substring(lastPos + 1); } else { this.beanPackageName = DEFAULT_BEAN_PKG; this.beanName = beanInfo; } }
Source:
public static InputStream getInputStreamFromName(String name) { int prefixEnd = name.indexOf(":"); String prefix = null; String path = name; if (prefixEnd != -1) { prefix = name.substring(0, prefixEnd); path = name.substring(prefixEnd + 1); } if (prefix == null) { throw new TechnicalException("prefix is not defined"); } switch (prefix) { case RESOURCE_PREFIX: if (!path.startsWith("/")) { path = "/" + path; } return CommonHelper.class.getResourceAsStream(path); case CLASSPATH_PREFIX: return Thread.currentThread().getContextClassLoader().getResourceAsStream(path); case HTTP_PREFIX: logger.warn("IdP metadata is retrieved from an insecure http endpoint [{}]", path); return getInputStreamViaHttp(name); case HTTPS_PREFIX: return getInputStreamViaHttp(name); default: try { return new FileInputStream(path); } catch (FileNotFoundException e) { throw new TechnicalException(e); } } }

Target:
public static InputStream getInputStreamFromName(String name) { int prefixEnd = name.indexOf(":"); String prefix = null; String path = name; if (prefixEnd != -1) { prefix = name.substring(0, prefixEnd); path = name.substring(prefixEnd + 1); } if (prefix == null || prefix.isEmpty()) { try { return new FileInputStream(path); } catch (FileNotFoundException e) { throw new TechnicalException(e); } } switch (prefix) { case RESOURCE_PREFIX: if (!path.startsWith("/")) { path = "/" + path; } return CommonHelper.class.getResourceAsStream(path); case CLASSPATH_PREFIX: return Thread.currentThread().getContextClassLoader().getResourceAsStream(path); case HttpConstants.SCHEME_HTTP: logger.warn("file is retrieved from an insecure http endpoint [{}]", path); return getInputStreamViaHttp(name); case HttpConstants.SCHEME_HTTPS: return getInputStreamViaHttp(name); default: throw new TechnicalException("prefix is not handled:" + prefix); } }
Source:
public Map<String, String> query(Serializer serializer) { if (serializer == null) { serializer = Serializer.defaultSerializer(); } Map<String, String> map = new HashMap<>(); DateTimeFormatter formatter = serializer.dateTimeFormatter(); if (offset != null) { map.put("offset", offset.toString()); } if (limit != null) { map.put("limit", limit.toString()); } if (from != null) { map.put("from", from.atZone(ZoneId.of("Z")).format(formatter)); } if (to != null) { map.put("to", to.atZone(ZoneId.of("Z")).format(formatter)); } if (order != null) { map.put("order", serializer.serializeToQueryParams(order)); } return Collections.unmodifiableMap(map); }

Target:
public Map<String, String> query(Serializer serializer) { if (serializer == null) { serializer = Serializer.defaultSerializer(); } Map<String, String> map = new HashMap<>(); DateTimeFormatter formatter = serializer.dateTimeFormatter(); if (offset != null) { map.put("offset", offset.toString()); } if (limit != null) { map.put("limit", limit.toString()); } if (from != null) { map.put("from", formatter.format(from)); } if (to != null) { map.put("to", formatter.format(to)); } if (order != null) { map.put("order", serializer.serializeToQueryParams(order)); } return Collections.unmodifiableMap(map); }
Source:
public static <E> GenericData getDataModelForType(Class<E> type) { if (SpecificRecord.class.isAssignableFrom(type)) { return new SpecificData(type.getClassLoader()); } else if (GenericRecord.class.isAssignableFrom(type)) { return GenericData.get(); } else if (IndexedRecord.class.isAssignableFrom(type)) { return GenericData.get(); } else { return ReflectData.get(); } }

Target:
public static <E> GenericData getDataModelForType(Class<E> type) { if (SpecificRecord.class.isAssignableFrom(type)) { return new SpecificData(type.getClassLoader()); } else if (IndexedRecord.class.isAssignableFrom(type)) { return GenericData.get(); } else { return ReflectData.AllowNull.get(); } }
Source:
public void run() { try { DataInputStream in = new DataInputStream(s.getInputStream()); PrintWriter out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(s.getOutputStream(),"UTF-8")), true); byte[] head = new byte[10]; in.readFully(head); String header = new String(head, Charsets.US_ASCII); if (header.startsWith("GET ")) { respondHello(header,s); return; } String s = new DataInputStream(new SequenceInputStream(new ByteArrayInputStream(head),in)).readUTF(); if(s.startsWith("Protocol:")) { String protocol = s.substring(9); AgentProtocol p = AgentProtocol.of(protocol); if (p!=null) { if (Jenkins.getInstance().getAgentProtocols().contains(protocol)) { LOGGER.log(Level.INFO, "Accepted {0} connection #{1} from {2}", new Object[] {protocol, id, this.s.getRemoteSocketAddress()}); p.handle(this.s); } else { error(out, "Disabled protocol:" + s); } } else error(out, "Unknown protocol:" + s); } else { error(out, "Unrecognized protocol: "+s); } } catch (InterruptedException e) { LOGGER.log(Level.WARNING,"Connection #"+id+" aborted",e); try { s.close(); } catch (IOException _) { } } catch (IOException e) { LOGGER.log(Level.WARNING,"Connection #"+id+" failed",e); try { s.close(); } catch (IOException _) { } } }

Target:
public void run() { try { LOGGER.log(Level.FINE, "Accepted connection #{0} from {1}", new Object[] {id, s.getRemoteSocketAddress()}); DataInputStream in = new DataInputStream(s.getInputStream()); PrintWriter out = new PrintWriter( new BufferedWriter(new OutputStreamWriter(s.getOutputStream(),"UTF-8")), true); byte[] head = new byte[10]; in.readFully(head); String header = new String(head, Charsets.US_ASCII); if (header.startsWith("GET ")) { respondHello(header,s); return; } String s = new DataInputStream(new SequenceInputStream(new ByteArrayInputStream(head),in)).readUTF(); if(s.startsWith("Protocol:")) { String protocol = s.substring(9); AgentProtocol p = AgentProtocol.of(protocol); if (p!=null) { if (Jenkins.getInstance().getAgentProtocols().contains(protocol)) { LOGGER.log(Level.INFO, "Accepted {0} connection #{1} from {2}", new Object[] {protocol, id, this.s.getRemoteSocketAddress()}); p.handle(this.s); } else { error(out, "Disabled protocol:" + s); } } else error(out, "Unknown protocol:" + s); } else { error(out, "Unrecognized protocol: "+s); } } catch (InterruptedException e) { LOGGER.log(Level.WARNING,"Connection #"+id+" aborted",e); try { s.close(); } catch (IOException _) { } } catch (IOException e) { LOGGER.log(Level.WARNING,"Connection #"+id+" failed",e); try { s.close(); } catch (IOException _) { } } }
Source:
public List<Block> execute(RssMacroParameters parameters, String content, MacroTransformationContext context) throws MacroExecutionException { List<Block> result; SyndFeed feed = this.romeFeedFactory.createFeed(parameters); this.setFeed(feed); if (parameters.isDecoration()) { result = super.execute(parameters, content == null ? StringUtils.EMPTY : content, context); } else { result = Arrays.<Block>asList(new GroupBlock(Collections.singletonMap(CLASS_ATTRIBUTE, FEED_CLASS_VALUE))); } generateEntries(result.get(0), feed, parameters); return result; }

Target:
public List<Block> execute(RssMacroParameters parameters, String content, MacroTransformationContext context) throws MacroExecutionException { List<Block> result; SyndFeed feed = this.romeFeedFactory.createFeed(parameters); this.setFeed(feed); if (parameters.isDecoration()) { result = super.execute(parameters, content == null ? StringUtils.EMPTY : content, context); } else { result = Arrays.<Block>asList(new GroupBlock(Collections.singletonMap(CLASS_ATTRIBUTE, FEED_CLASS_VALUE))); } generateEntries(result.get(0), feed, parameters); this.removeContextFeed(); return result; }
Source:
public byte[] performRequest(String endpointUrl, List<NameValuePair> params) throws IOException, OutOfMemoryError { if (MPConfig.DEBUG) Log.d(LOGTAG, "Attempting request to " + endpointUrl); byte[] response = null; int retries = 0; boolean succeeded = false; while (retries < 3 && !succeeded) { InputStream in = null; OutputStream out = null; BufferedOutputStream bout = null; HttpURLConnection connection = null; try { final URL url = new URL(endpointUrl); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(2000); connection.setReadTimeout(10000); if (null != params) { connection.setDoOutput(true); final UrlEncodedFormEntity form = new UrlEncodedFormEntity(params, "UTF-8"); connection.setRequestMethod("POST"); connection.setFixedLengthStreamingMode((int)form.getContentLength()); out = connection.getOutputStream(); bout = new BufferedOutputStream(out); form.writeTo(bout); bout.close(); bout = null; out.close(); out = null; } in = connection.getInputStream(); response = slurp(in); in.close(); in = null; succeeded = true; } catch (final EOFException e) { if (MPConfig.DEBUG) Log.d(LOGTAG, "Failure to connect, likely caused by a known issue with Android lib. Retrying."); retries = retries + 1; } finally { if (null != bout) try { bout.close(); } catch (final IOException e) { ; } if (null != out) try { out.close(); } catch (final IOException e) { ; } if (null != in) try { in.close(); } catch (final IOException e) { ; } if (null != connection) connection.disconnect(); } } return response; }

Target:
public byte[] performRequest(String endpointUrl, List<NameValuePair> params) throws IOException { if (MPConfig.DEBUG) Log.d(LOGTAG, "Attempting request to " + endpointUrl); byte[] response = null; int retries = 0; boolean succeeded = false; while (retries < 3 && !succeeded) { InputStream in = null; OutputStream out = null; BufferedOutputStream bout = null; HttpURLConnection connection = null; try { final URL url = new URL(endpointUrl); connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(2000); connection.setReadTimeout(10000); if (null != params) { connection.setDoOutput(true); final UrlEncodedFormEntity form = new UrlEncodedFormEntity(params, "UTF-8"); connection.setRequestMethod("POST"); connection.setFixedLengthStreamingMode((int)form.getContentLength()); out = connection.getOutputStream(); bout = new BufferedOutputStream(out); form.writeTo(bout); bout.close(); bout = null; out.close(); out = null; } in = connection.getInputStream(); response = slurp(in); in.close(); in = null; succeeded = true; } catch (final EOFException e) { if (MPConfig.DEBUG) Log.d(LOGTAG, "Failure to connect, likely caused by a known issue with Android lib. Retrying."); retries = retries + 1; } finally { if (null != bout) try { bout.close(); } catch (final IOException e) { ; } if (null != out) try { out.close(); } catch (final IOException e) { ; } if (null != in) try { in.close(); } catch (final IOException e) { ; } if (null != connection) connection.disconnect(); } } return response; }
Source:
private void setUpHttpLogging() throws IOException { if ( !getConfig().get( http_logging_enabled ) ) { return; } AsyncRequestLog requestLog = new AsyncRequestLog( dependencyResolver.resolveDependency( FileSystemAbstraction.class ), config.get( GraphDatabaseSettings.log_timezone ).getZoneId(), config.get( http_log_path ).toString(), config.get( http_logging_rotation_size ), config.get( http_logging_rotation_keep_number ) ); webServer.setRequestLog( requestLog ); }

Target:
private void setUpHttpLogging() throws IOException { if ( !getConfig().get( http_logging_enabled ) ) { return; } AsyncRequestLog requestLog = new AsyncRequestLog( dependencyResolver.resolveDependency( FileSystemAbstraction.class ), config.get( log_timezone ).getZoneId(), config.get( http_log_path ).toString(), config.get( http_logging_rotation_size ), config.get( http_logging_rotation_keep_number ) ); webServer.setRequestLog( requestLog ); }
Source:
public CandidateWidget(Candidate candidate, int nbOfVotes) { widget = binder.createAndBindUi(this); company.setInnerHTML(candidate.getCompany()); name.setInnerHTML(candidate.getName()); image.setResource(candidate.getPicture()); nbVotes.setInnerHTML(String.valueOf(nbOfVotes)); }

Target:
public CandidateWidget(Candidate candidate, int nbOfVotes) { widget = binder.createAndBindUi(this); company.setInnerText(candidate.getCompany()); name.setInnerText(candidate.getName()); if (candidate.getPicture() != null) { image.setResource(candidate.getPicture()); } nbVotes.setInnerText(String.valueOf(nbOfVotes)); }
Source:
public void onEntityPickup(EntityPickupItemEvent e) { if (SlimefunUtils.hasNoPickupFlag(e.getItem())) { e.setCancelled(true); } else if (e.getItem().getItemStack().hasItemMeta() && e.getItem().getItemStack().getItemMeta().hasDisplayName() && e.getItem().getItemStack().getItemMeta().getDisplayName().startsWith(ITEM_PREFIX)) { e.setCancelled(true); e.getItem().remove(); } else if (SlimefunPlugin.getMinecraftVersion().isAtLeast(MinecraftVersion.MINECRAFT_1_16)) { if (e.getEntityType().equals(EntityType.PIGLIN)) { if (SlimefunItem.getByItem(e.getItem().getItemStack()) != null) { e.setCancelled(true); } } } }

Target:
public void onEntityPickup(EntityPickupItemEvent e) { if (SlimefunUtils.hasNoPickupFlag(e.getItem())) { e.setCancelled(true); } else if (e.getItem().getItemStack().hasItemMeta() && e.getItem().getItemStack().getItemMeta().hasDisplayName() && e.getItem().getItemStack().getItemMeta().getDisplayName().startsWith(ITEM_PREFIX)) { e.setCancelled(true); e.getItem().remove(); } }
Source:
private boolean decodeLightingParameters(Cardio2eLightingTransaction receivedCardio2eTransaction, List<String> digestedTransaction) { boolean decodeComplete = false; switch (receivedCardio2eTransaction.getTransactionType()){ case ACK: case GET: if (digestedTransaction.size() == 3) { try { receivedCardio2eTransaction.setObjectNumber (Short.parseShort(digestedTransaction.get(2))); decodeComplete = true; } catch (IllegalArgumentException e1) { e1.printStackTrace(); } } break; case NACK: decodeComplete = decodeNACK(receivedCardio2eTransaction, digestedTransaction); break; case INFORMATION: case SET: if (digestedTransaction.size() == 4) { try { receivedCardio2eTransaction.setObjectNumber (Short.parseShort(digestedTransaction.get(2))); receivedCardio2eTransaction.setLightIntensity (Byte.parseByte(digestedTransaction.get(3))); decodeComplete = true; } catch (IllegalArgumentException e1) { e1.printStackTrace(); } } break; } return decodeComplete; }

Target:
private boolean decodeLightingParameters( Cardio2eLightingTransaction receivedCardio2eTransaction, List<String> digestedTransaction) { boolean decodeComplete = false; switch (receivedCardio2eTransaction.getTransactionType()) { case ACK: case GET: if (digestedTransaction.size() == 3) { try { receivedCardio2eTransaction.setObjectNumber(Short .parseShort(digestedTransaction.get(2))); decodeComplete = true; } catch (IllegalArgumentException ex) { logger.warn( "Illegal argument in decoding LIGHTING transaction: '{}'", ex.toString()); } } break; case NACK: decodeComplete = decodeNACK(receivedCardio2eTransaction, digestedTransaction); break; case INFORMATION: case SET: if (digestedTransaction.size() == 4) { try { receivedCardio2eTransaction.setObjectNumber(Short .parseShort(digestedTransaction.get(2))); receivedCardio2eTransaction.setLightIntensity(Byte .parseByte(digestedTransaction.get(3))); decodeComplete = true; } catch (IllegalArgumentException ex) { logger.warn( "Illegal argument in decoding LIGHTING transaction: '{}'", ex.toString()); } } break; } return decodeComplete; }
Source:
public boolean isDomainsReportedAsProblematic(List<VDSDomainsData> vdsDomainsData) { Set<Guid> domainsInPool = new HashSet<Guid>( DbFacade.getInstance().getStorageDomainStaticDAO().getAllIds( _storagePoolId, StorageDomainStatus.Active)); domainsInPool.addAll(DbFacade.getInstance().getStorageDomainStaticDAO().getAllIds( _storagePoolId, StorageDomainStatus.Unknown)); List<Guid> domainWhicWereSeen = new ArrayList<Guid>(); for (VDSDomainsData vdsDomainData : vdsDomainsData) { if (domainsInPool.contains(vdsDomainData.getDomainId())) { if (isDomainReportedAsProblematic(vdsDomainData, true)) { return true; } domainWhicWereSeen.add(vdsDomainData.getDomainId()); } } domainsInPool.removeAll(domainWhicWereSeen); if (domainsInPool.size() > 0) { for (Guid domainId : domainsInPool) { log.errorFormat("Domain {0} was not seen by host", domainId); } return true; } return false; }

Target:
public boolean isDomainsReportedAsProblematic(List<VDSDomainsData> vdsDomainsData) { Set<Guid> domainsInPool = new HashSet<Guid>( DbFacade.getInstance().getStorageDomainStaticDao().getAllIds( _storagePoolId, StorageDomainStatus.Active)); domainsInPool.addAll(DbFacade.getInstance().getStorageDomainStaticDao().getAllIds( _storagePoolId, StorageDomainStatus.Unknown)); List<Guid> domainWhicWereSeen = new ArrayList<Guid>(); for (VDSDomainsData vdsDomainData : vdsDomainsData) { if (domainsInPool.contains(vdsDomainData.getDomainId())) { if (isDomainReportedAsProblematic(vdsDomainData, true)) { return true; } domainWhicWereSeen.add(vdsDomainData.getDomainId()); } } domainsInPool.removeAll(domainWhicWereSeen); if (domainsInPool.size() > 0) { for (Guid domainId : domainsInPool) { log.errorFormat("Domain {0} is not seen by Host", domainId); } return true; } return false; }
Source:
private void register() { if (getWindow() != null) { return; } ArrayList<VdcActionParametersBase> parametersList = new ArrayList<>(); for (Object item : getSelectedItems()) { DiskImage disk = (DiskImage) item; RegisterDiskParameters parameters = new RegisterDiskParameters(disk, getEntity().getId()); parametersList.add(parameters); } Frontend.getInstance().runMultipleAction(VdcActionType.RegisterDisk, parametersList, new IFrontendMultipleActionAsyncCallback() { @Override public void executed(FrontendMultipleActionAsyncResult result) { } }, this); }

Target:
private void register() { if (getWindow() != null) { return; } for (Object item : getSelectedItems()) { DiskImage disk = (DiskImage) item; GetUnregisteredDiskQueryParameters parameters = new GetUnregisteredDiskQueryParameters(disk.getId(), getEntity().getId(), getEntity().getStoragePoolId()); Frontend.getInstance().runQuery(VdcQueryType.GetUnregisteredDisk, parameters, new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object model, Object ReturnValue) { DiskImage diskImage = ((VdcQueryReturnValue) ReturnValue).getReturnValue(); RegisterDiskParameters registerDiskParams = new RegisterDiskParameters(diskImage, getEntity().getId()); Frontend.getInstance().runAction(VdcActionType.RegisterDisk, registerDiskParams); } })); } }
Source:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((compatibilityVersion == null) ? 0 : compatibilityVersion.hashCode()); result = prime * result + ((network == null) ? 0 : network.hashCode()); result = prime * result + ((storagePoolName == null) ? 0 : storagePoolName.hashCode()); return result; }

Target:
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getCompatibilityVersion() == null) ? 0 : getCompatibilityVersion().hashCode()); result = prime * result + ((getNetwork() == null) ? 0 : getNetwork().hashCode()); result = prime * result + ((getStoragePoolName() == null) ? 0 : getStoragePoolName().hashCode()); return result; }
Source:
public String replaceCredentials(String code) { if (code == null) { return null; } String replaced = code; Pattern userpattern = Pattern.compile("\\{user\\.([^\\}]+)\\}"); Pattern passwordpattern = Pattern.compile("\\{password\\.([^\\}]+)\\}"); Matcher matcher = userpattern.matcher(replaced); while (matcher.find()) { String key = matcher.group(1); UsernamePassword usernamePassword = creds.getUsernamePassword(key); if (usernamePassword != null) { String value = usernamePassword.getUsername(); replaced = matcher.replaceFirst(value); matcher = userpattern.matcher(replaced); } } matcher = passwordpattern.matcher(replaced); while (matcher.find()) { String key = matcher.group(1); UsernamePassword usernamePassword = creds.getUsernamePassword(key); if (usernamePassword != null) { passwords.add(usernamePassword.getPassword()); String value = usernamePassword.getPassword(); replaced = matcher.replaceFirst(value); matcher = passwordpattern.matcher(replaced); } } return replaced; }

Target:
public String replaceCredentials(String code) { if (code == null) { return null; } String replaced = code; Matcher matcher = userpattern.matcher(replaced); while (matcher.find()) { String key = matcher.group(1); UsernamePassword usernamePassword = creds.getUsernamePassword(key); if (usernamePassword != null) { String value = usernamePassword.getUsername(); String quotedValue = Matcher.quoteReplacement(value); replaced = matcher.replaceFirst(quotedValue); matcher = userpattern.matcher(replaced); } } matcher = passwordpattern.matcher(replaced); while (matcher.find()) { String key = matcher.group(1); UsernamePassword usernamePassword = creds.getUsernamePassword(key); if (usernamePassword != null) { passwords.add(usernamePassword.getPassword()); String value = usernamePassword.getPassword(); String quotedValue = Matcher.quoteReplacement(value); replaced = matcher.replaceFirst(quotedValue); matcher = passwordpattern.matcher(replaced); } } return replaced; }
Source:
private void cancelAllRequestsDueToError(Throwable t) { LOGGER.error(t, GraphI18n.executingRequest, sourceName); for (Request request : this.composite.getRequests()) { try { request.cancel(); } finally { request.freeze(); } } try { cancel(true); } finally { this.composite.freeze(); } }

Target:
private void cancelAllRequestsDueToError(Throwable t) { LOGGER.error(t, GraphI18n.executingRequest, sourceName); try { for (Request request : this.composite.getRequests()) { try { request.cancel(); } finally { request.freeze(); } } cancel(true); } finally { this.composite.freeze(); } }
Source:
public boolean isTrue(ZestResponse response) { boolean toReturn = true; for (ZestExpressionElement con : getChildrenCondition()) { toReturn = toReturn && con.evaluate(response); if(!toReturn) break; } return toReturn; }

Target:
public boolean isTrue(ZestResponse response) { if(getChildrenCondition().isEmpty()) return false; boolean toReturn = true; for (ZestExpressionElement con : getChildrenCondition()) { toReturn = toReturn && con.evaluate(response); if(!toReturn) break; } return toReturn; }
Source:
public Note buildFromBase64EncodedData(String noteId, String base64FullNoteData){ Note note = null; if (base64FullNoteData == null) return null; byte[] b64DecodedPayload = Base64.decode(base64FullNoteData, Base64.DEFAULT); Inflater decompresser = new Inflater(); decompresser.setInput(b64DecodedPayload, 0, b64DecodedPayload.length); byte[] result = new byte[4096]; int resultLength = 0; try { resultLength = decompresser.inflate(result); decompresser.end(); } catch (DataFormatException e) { e.printStackTrace(); } String out = new String(result, 0, resultLength, StandardCharsets.UTF_8); if (out != null) { try { JSONObject jsonObject = new JSONObject(out); if (jsonObject.has("notes")) { JSONArray jsonArray = jsonObject.getJSONArray("notes"); if (jsonArray != null && jsonArray.length() == 1) { jsonObject = jsonArray.getJSONObject(0); } } note = build(noteId, jsonObject); } catch (JSONException e) { e.printStackTrace(); } } return note; }

Target:
public Note buildFromBase64EncodedData(String noteId, String base64FullNoteData){ Note note = null; if (base64FullNoteData == null) return null; byte[] b64DecodedPayload = Base64.decode(base64FullNoteData, Base64.DEFAULT); Inflater decompresser = new Inflater(); decompresser.setInput(b64DecodedPayload, 0, b64DecodedPayload.length); byte[] result = new byte[4096]; int resultLength = 0; try { resultLength = decompresser.inflate(result); decompresser.end(); } catch (DataFormatException e) { AppLog.e(AppLog.T.NOTIFS, e.getMessage()); } String out = null; try { out = new String(result, 0, resultLength, "UTF-8"); } catch(UnsupportedEncodingException e) { AppLog.e(AppLog.T.NOTIFS, e.getMessage()); } if (out != null) { try { JSONObject jsonObject = new JSONObject(out); if (jsonObject.has("notes")) { JSONArray jsonArray = jsonObject.getJSONArray("notes"); if (jsonArray != null && jsonArray.length() == 1) { jsonObject = jsonArray.getJSONObject(0); } } note = build(noteId, jsonObject); } catch (JSONException e) { AppLog.e(AppLog.T.NOTIFS, e.getMessage()); } } return note; }
Source:
public IndexAnalysisSettings3 getSettings(String projectName) throws IOException { if (mappedAnalysisSettings == null) { IndexAnalysisSettingsAccessor dao = new IndexAnalysisSettingsAccessor(); IndexAnalysisSettings3[] setts = dao.read(reader, Short.MAX_VALUE); map(setts); } String k = projectName != null ? projectName : ""; return mappedAnalysisSettings.get(k); }

Target:
public IndexAnalysisSettings3 getSettings(String projectName) throws IOException { if (mappedAnalysisSettings == null) { IndexAnalysisSettingsAccessor dao = new IndexAnalysisSettingsAccessor(); IndexAnalysisSettings3[] setts = dao.read(reader, Short.MAX_VALUE); map(setts); } String projectKey = projectName != null ? projectName : ""; return mappedAnalysisSettings.get(projectKey); }
Source:
public Image getImage(ImageSettingsRequest imageSettings, String region, String platform) { String imageId = imageSettings.getId(); String catalogUrl = Objects.nonNull(imageSettings.getCatalog()) ? imageSettings.getCatalog() : defaultCatalogUrl; String imageOs = Objects.nonNull(imageSettings.getOs()) ? imageSettings.getOs() : defaultOs; ImageCatalog cachedImageCatalog = imageCatalogProvider.getImageCatalog(catalogUrl); return findImageForAppVersion(region, platform, imageId, imageOs, cachedImageCatalog) .or(() -> { LOGGER.debug("Image not found with the parameters: imageId: {}, imageOs: {}, region: {}, platform: {}", imageId, imageOs, region, platform); LOGGER.debug("Evicting image catalog cache to retry."); imageCatalogProvider.evictImageCatalogCache(catalogUrl); ImageCatalog renewedImageCatalog = imageCatalogProvider.getImageCatalog(catalogUrl); return findImageForAppVersion(region, platform, imageId, imageOs, renewedImageCatalog); }) .orElseThrow(() -> { String message = String.format("Could not find any image with id: '%s' in region '%s' with OS '%s'.", imageId, region, imageOs); return new ImageNotFoundException(message); }); }

Target:
public Image getImage(ImageSettingsRequest imageSettings, String region, String platform) { String imageId = imageSettings.getId(); String catalogUrl = Objects.nonNull(imageSettings.getCatalog()) ? imageSettings.getCatalog() : defaultCatalogUrl; String imageOs = Objects.nonNull(imageSettings.getOs()) ? imageSettings.getOs() : defaultOs; ImageCatalog cachedImageCatalog = imageCatalogProvider.getImageCatalog(catalogUrl); return findImageForAppVersion(region, platform, imageId, imageOs, cachedImageCatalog) .or(() -> retryAfterEvictingCache(region, platform, imageId, catalogUrl, imageOs)) .orElseThrow(() -> throwImageNotFoundException(region, imageId, imageOs)); }
Source:
private double getTotalSizeForNewDisks(Collection<DiskImage> diskImages) { double totalSizeForDisks = 0.0; if (null != diskImages) { for (DiskImage diskImage : diskImages) { double sizeForDisk = diskImage.getSize(); if (diskImage.getVolumeFormat() == VolumeFormat.COW) { if (storageDomain.getStorageType().isFileDomain()) { sizeForDisk = EMPTY_QCOW_HEADER_SIZE; } else { sizeForDisk = INITIAL_BLOCK_ALLOCATION_SIZE; } } else if (diskImage.getVolumeType() == VolumeType.Sparse) { sizeForDisk = EMPTY_QCOW_HEADER_SIZE; } totalSizeForDisks += sizeForDisk; } } return totalSizeForDisks; }

Target:
private double getTotalSizeForNewDisks(Collection<DiskImage> diskImages) { double totalSizeForDisks = 0.0; if (diskImages != null) { for (DiskImage diskImage : diskImages) { double sizeForDisk = diskImage.getSize(); if (diskImage.getVolumeFormat() == VolumeFormat.COW) { if (storageDomain.getStorageType().isFileDomain()) { sizeForDisk = EMPTY_QCOW_HEADER_SIZE; } else { sizeForDisk = INITIAL_BLOCK_ALLOCATION_SIZE; } } else if (diskImage.getVolumeType() == VolumeType.Sparse) { sizeForDisk = EMPTY_QCOW_HEADER_SIZE; } totalSizeForDisks += sizeForDisk; } } return totalSizeForDisks; }
Source:
public void launchDaemon() { LOG.info("Starting supervisor for storm version '{}'.", VersionInfo.getVersion()); try { Map<String, Object> conf = getConf(); if (ConfigUtils.isLocalMode(conf)) { throw new IllegalArgumentException("Cannot start server in local mode!"); } launch(); metricsRegistry.registerGauge("supervisor:num-slots-used-gauge", () -> SupervisorUtils.supervisorWorkerIds(conf).size()); metricsRegistry.registerMeter("supervisor:num-launched").mark(); metricsRegistry.registerMeter("supervisor:num-shell-exceptions", ShellUtils.numShellExceptions); killErrorMeter = metricsRegistry.registerMeter("supervisor:num-kill-errors"); metricsRegistry.startMetricsReporters(conf); Utils.addShutdownHookWithForceKillIn1Sec(() -> { metricsRegistry.stopMetricsReporters(); this.close(); }); launchSupervisorThriftServer(conf); } catch (Exception e) { LOG.error("Failed to start supervisor\n", e); System.exit(1); } }

Target:
public void launchDaemon() { LOG.info("Starting supervisor for storm version '{}'.", VersionInfo.getVersion()); try { Map<String, Object> conf = getConf(); if (ConfigUtils.isLocalMode(conf)) { throw new IllegalArgumentException("Cannot start server in local mode!"); } launch(); metricsRegistry.registerGauge("supervisor:num-slots-used-gauge", () -> SupervisorUtils.supervisorWorkerIds(conf).size()); metricsRegistry.registerMeter("supervisor:num-launched").mark(); metricsRegistry.registerMeter("supervisor:num-shell-exceptions", ShellUtils.numShellExceptions); killErrorMeter = metricsRegistry.registerMeter("supervisor:num-kill-worker-errors"); metricsRegistry.startMetricsReporters(conf); Utils.addShutdownHookWithForceKillIn1Sec(() -> { metricsRegistry.stopMetricsReporters(); this.close(); }); launchSupervisorThriftServer(conf); } catch (Exception e) { LOG.error("Failed to start supervisor\n", e); System.exit(1); } }
Source:
public LocalTime fromInt(Integer millisFromMidnight, Schema schema, LogicalType type) { return LocalTime.ofNanoOfDay(1_000_000L * millisFromMidnight); }

Target:
public LocalTime fromInt(Integer millisFromMidnight, Schema schema, LogicalType type) { return LocalTime.ofNanoOfDay(TimeUnit.MILLISECONDS.toNanos(millisFromMidnight)); }
Source:
private void processSingleClusterChanges(ManageNetworkClustersParameters param) { final List<ActionParametersBase> setupNetworksParams = new ArrayList<>( createNetworkClustersToSetupNetworksParametersTransformer().transform( param.getAttachments(), param.getDetachments(), param.getUpdates()) ); HostSetupNetworksParametersBuilder.updateParametersSequencing(setupNetworksParams); setupNetworksParams.forEach(this::withRootCommandInfo); runInternalMultipleActions(ActionType.PersistentHostSetupNetworks, setupNetworksParams, getContext().getExecutionContext()); }

Target:
private void processSingleClusterChanges(ManageNetworkClustersParameters param) { final List<ActionParametersBase> setupNetworksParams = new ArrayList<>( createNetworkClustersToSetupNetworksParametersTransformer().transform( param.getAttachments(), param.getDetachments(), param.getUpdates()) ); HostSetupNetworksParametersBuilder.updateParametersSequencing(setupNetworksParams); setupNetworksParams.forEach(this::withRootCommandInfo); runInternalMultipleActions(ActionType.PersistentHostSetupNetworks, setupNetworksParams); }
Source:
public void testDefaultValue() { StringProperty prop1 = newString("prop1", "value1"); assertNull(prop1.getDefaultValue()); assertNull(prop1.getStringDefaultValue()); StringProperty prop2 = newString("prop2", "value2", "defaultValue2"); assertEquals("defaultValue2", prop2.getDefaultValue()); assertEquals("defaultValue2", prop2.getStringDefaultValue()); StringProperty prop3 = newString("prop3", "value3"); prop3.setValueEvaluator(new PropertyValueEvaluator() { @Override public <T> T evaluate(Property<T> property, Object storedValue) { return (T) storedValue; } }); assertNull(prop3.getDefaultValue()); assertNull(prop3.getStringDefaultValue()); StringProperty prop4 = newString("prop4", "value4", "defaultValue4"); prop3.setValueEvaluator(new PropertyValueEvaluator() { @Override public <T> T evaluate(Property<T> property, Object storedValue) { return (T) storedValue; } }); assertEquals("defaultValue4", prop4.getDefaultValue()); assertEquals("defaultValue4", prop4.getStringDefaultValue()); }

Target:
public void testDefaultValue() { StringProperty prop1 = newString("prop1", "value1"); assertNull(prop1.getDefaultValue()); assertNull(prop1.getStringDefaultValue()); StringProperty prop2 = newString("prop2", "value2", "defaultValue2"); assertEquals("defaultValue2", prop2.getDefaultValue()); assertEquals("defaultValue2", prop2.getStringDefaultValue()); StringProperty prop3 = newString("prop3", "value3"); prop3.setValueEvaluator(new PropertyValueEvaluator() { @Override public <T> T evaluate(Property<T> property, Object storedValue) { return storedValue == null ? null : (T) "prop3".concat((String) storedValue); } }); assertNull(prop3.getDefaultValue()); assertNull(prop3.getStringDefaultValue()); StringProperty prop4 = newString("prop4", "value4", "defaultValue4"); prop4.setValueEvaluator(new PropertyValueEvaluator() { @Override public <T> T evaluate(Property<T> property, Object storedValue) { return storedValue == null ? null : (T) "prop4".concat((String) storedValue); } }); assertEquals("prop4defaultValue4", prop4.getDefaultValue()); assertEquals("prop4defaultValue4", prop4.getStringDefaultValue()); }
Source:
private String getData(String path, Map<String, String> params) throws APIException { HttpURLConnection con = null; try { final String url = getUrl(path, params); con = IOHelper.getConnection(url); con.setReadTimeout(30000); return IOHelper.readString(con.getInputStream()); } catch (Exception e) { throw new APIException("Couldn't request data from the UNSD server", e); } finally { try { con.disconnect(); } catch (Exception ignored) { } } }

Target:
private String getData(String path, Map<String, String> params) throws APIException { HttpURLConnection con = null; try { final String url = getUrl(path, params); con = IOHelper.getConnection(url); con.setReadTimeout(PropertyUtil.getOptional(PROP_READ_TIMEOUT, 30000)); return IOHelper.readString(con); } catch (Exception e) { throw new APIException("Couldn't request data from the UNSD server", e); } finally { try { con.disconnect(); } catch (Exception ignored) { } } }
Source:
public static Alert fromInternal( final models.internal.alerts.Alert internal, final Optional<JobExecution.Success<AlertEvaluationResult>> mostRecentEvaluation ) { final Alert alert = new Alert(); alert._id = internal.getId(); alert._name = internal.getName(); alert._description = internal.getDescription(); alert._enabled = internal.isEnabled(); alert._additionalMetadata = internal.getAdditionalMetadata(); final AlertFiringState firingState = new AlertFiringState(); mostRecentEvaluation.ifPresent(evaluation -> { firingState.setLastEvaluatedAt(evaluation.getCompletedAt()); firingState.setFiringTags(evaluation.getResult().getFiringTags()); }); alert._firingState = firingState; return alert; }

Target:
public static Alert fromInternal( final models.internal.alerts.Alert internal, final Optional<JobExecution.Success<AlertEvaluationResult>> mostRecentEvaluation ) { final Alert alert = new Alert(); alert._id = internal.getId(); alert._name = internal.getName(); alert._description = internal.getDescription(); alert._enabled = internal.isEnabled(); alert._additionalMetadata = internal.getAdditionalMetadata(); alert._firingState = mostRecentEvaluation.map(evaluation -> { final AlertFiringState firingState = new AlertFiringState(); firingState.setLastEvaluatedAt(evaluation.getCompletedAt()); firingState.setFiringTags(evaluation.getResult().getFiringTags()); return firingState; }); return alert; }
Source:
public Command toDevfileCommand(CommandImpl command) throws WorkspaceExportException { Command devCommand = new Command().withName(command.getName()); Action action = new Action().withCommand(command.getCommandLine()).withType(command.getType()); String workingDir = command.getAttributes().remove(WORKING_DIRECTORY_ATTRIBUTE); if (!isNullOrEmpty(workingDir)) { action.setWorkdir(workingDir); } String toolName = command.getAttributes().remove(Constants.TOOL_NAME_COMMAND_ATTRIBUTE); if (toolName == null) { throw new WorkspaceExportException( format("Command `%s` has no specified tool where it should be run", command.getName())); } action.setTool(toolName); action.setType(Constants.EXEC_ACTION_TYPE); devCommand.getActions().add(action); devCommand.setAttributes(command.getAttributes()); return devCommand; }

Target:
public Command toDevfileCommand(CommandImpl command) throws WorkspaceExportException { String toolName = command.getAttributes().remove(Constants.TOOL_NAME_COMMAND_ATTRIBUTE); if (toolName == null) { throw new WorkspaceExportException( format("Command `%s` has no specified tool where it should be run", command.getName())); } Command devCommand = new Command().withName(command.getName()); Action action = new Action().withCommand(command.getCommandLine()).withType(command.getType()); action.setWorkdir(command.getAttributes().remove(WORKING_DIRECTORY_ATTRIBUTE)); action.setTool(toolName); action.setType(Constants.EXEC_ACTION_TYPE); devCommand.getActions().add(action); devCommand.setAttributes(command.getAttributes()); return devCommand; }
Source:
public boolean canFlipToNextPage() { final boolean hasAtLeastOneFileToScan = !((BatchImportTraceWizard) getWizard()).getFilesToScan().isEmpty(); if( hasAtLeastOneFileToScan ){ setErrorMessage(null); } else { setErrorMessage("Select at least one directory to scan"); } return hasAtLeastOneFileToScan; }

Target:
public boolean canFlipToNextPage() { final Table selectedFiles = (Table) ((Composite) getControl()).getChildren()[0]; boolean canLoad = selectedFiles.getItemCount() >= 0; if (canLoad) { setErrorMessage(null); } else { setErrorMessage(Messages.ImportTraceWizardPageSelectDirectories_4); } return canLoad; }
Source:
public int getNumEntries(boolean crcCheck) throws IOException { boolean wasClosed = false; if (m_closed) { wasClosed = true; open(false, false); } m_numOfEntries = 0; m_size = 0; if (m_fc.size() >= SEGMENT_HEADER_BYTES) { m_segmentHeaderBuf.b().clear(); PBDUtils.readBufferFully(m_fc, m_segmentHeaderBuf.b(), 0); if (crcCheck) { long crc = m_segmentHeaderBuf.b().getLong(); int numOfEntries = m_segmentHeaderBuf.b().getInt(); int size = m_segmentHeaderBuf.b().getInt(); m_segmentHeaderCRC.reset(); m_segmentHeaderCRC.update(numOfEntries); m_segmentHeaderCRC.update(size); if (crc != m_segmentHeaderCRC.getValue()) { LOG.warn("File corruption detected in" + m_file.getName() + ": invalid file header. " + "Discard the file."); return m_numOfEntries; } m_numOfEntries = numOfEntries; m_size = size; } else { m_numOfEntries = m_segmentHeaderBuf.b().getInt(HEADER_NUM_OF_ENTRY_OFFSET); m_size = m_segmentHeaderBuf.b().getInt(HEADER_TOTAL_BYTES_OFFSET); } } if (wasClosed) closeReadersAndFile(); return m_numOfEntries; }

Target:
public int getNumEntries(boolean crcCheck) throws IOException { boolean wasClosed = false; if (m_closed) { wasClosed = true; open(false, false); } m_numOfEntries = 0; m_size = 0; if (m_fc.size() >= SEGMENT_HEADER_BYTES) { m_segmentHeaderBuf.b().clear(); PBDUtils.readBufferFully(m_fc, m_segmentHeaderBuf.b(), 0); if (crcCheck) { int crc = m_segmentHeaderBuf.b().getInt(); int numOfEntries = m_segmentHeaderBuf.b().getInt(); int size = m_segmentHeaderBuf.b().getInt(); m_segmentHeaderCRC.reset(); m_segmentHeaderCRC.update(numOfEntries); m_segmentHeaderCRC.update(size); if (crc != (int)m_segmentHeaderCRC.getValue()) { LOG.warn("File corruption detected in" + m_file.getName() + ": invalid file header. "); throw new IOException("File corruption detected in" + m_file.getName() + ": invalid file header."); } m_numOfEntries = numOfEntries; m_size = size; } else { m_numOfEntries = m_segmentHeaderBuf.b().getInt(HEADER_NUM_OF_ENTRY_OFFSET); m_size = m_segmentHeaderBuf.b().getInt(HEADER_TOTAL_BYTES_OFFSET); } } if (wasClosed) closeReadersAndFile(); return m_numOfEntries; }