auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void handleScheduleRepeatingJobEvent(MotechEvent event) { Map<String, Object> parameters = event.getParameters(); Map<String, Object> metadata = event.getMetadata(); String jobSubject = (String) metadata.get(JOB_SUBJECT); parameters.remove(JOB_SUBJECT); Integer repeatCount = (Integer) metadata.get(REPEAT_COUNT); parameters.remove(REPEAT_COUNT); Integer repeatIntervalInSeconds = (Integer) metadata.get(REPEAT_INTERVAL_TIME); parameters.remove(REPEAT_COUNT); MotechEvent jobEvent = new MotechEvent(jobSubject, parameters, null, metadata); RepeatingSchedulableJob repeatingJob = new RepeatingSchedulableJob(jobEvent, repeatCount, repeatIntervalInSeconds, DateTime.now(), null, false); schedulerService.scheduleRepeatingJob(repeatingJob); }

Target:
public void handleScheduleRepeatingJobEvent(MotechEvent event) { Map<String, Object> parameters = event.getParameters(); Map<String, Object> metadata = event.getMetadata(); String jobSubject = (String) metadata.get(JOB_SUBJECT); Integer repeatCount = (Integer) metadata.get(REPEAT_COUNT); Integer repeatIntervalInSeconds = (Integer) metadata.get(REPEAT_INTERVAL_TIME); MotechEvent jobEvent = new MotechEvent(jobSubject, parameters, null, metadata); RepeatingSchedulableJob repeatingJob = new RepeatingSchedulableJob(jobEvent, repeatCount, repeatIntervalInSeconds, DateTime.now(), null, false); schedulerService.scheduleRepeatingJob(repeatingJob); }
Source:
public void updatePathGroup(List<Variable> variables, IPath node, IPath selection) { final int segmentsSelection = selection.segmentCount(); for (final Variable variable : variables) if (variable.getPath().uptoSegment(segmentsSelection).equals(selection.makeAbsolute())) { final IPath oldPath = variable.getPath(); final int count = selection.segmentCount(); variable.setPath(buildPath(oldPath, node, count)); } }

Target:
public static void updatePathGroup(List<Variable> variables, IPath node, IPath selection) { final int segmentsSelection = selection.segmentCount(); for (final Variable variable : variables) if (variable.getPath().uptoSegment(segmentsSelection).equals(selection.makeAbsolute())) { final IPath oldPath = variable.getPath(); final int count = selection.segmentCount(); variable.setPath(buildPath(oldPath, node, count)); } }
Source:
static <T> WorkProcessor<T> mergeSorted(Iterable<WorkProcessor<T>> processorIterable, Comparator<T> comparator) { requireNonNull(comparator, "comparator is null"); Iterator<WorkProcessor<T>> processorIterator = requireNonNull(processorIterable, "processorIterable is null").iterator(); checkArgument(processorIterator.hasNext(), "There must be at least one base processor"); PriorityQueue<ElementAndProcessor<T>> queue = new PriorityQueue<>(2, comparing(ElementAndProcessor::getElement, comparator)); return create(new WorkProcessor.Process<T>() { WorkProcessor<T> processor = processorIterator.next(); @Override public ProcessorState<T> process() { while (true) { if (processor.process()) { if (!processor.isFinished()) { queue.add(new ElementAndProcessor<>(processor.getResult(), processor)); } } else if (processor.isBlocked()) { return ProcessorState.blocked(processor.getBlockedFuture()); } else { return ProcessorState.yield(); } if (processorIterator.hasNext()) { processor = processorIterator.next(); continue; } if (queue.isEmpty()) { return ProcessorState.finished(); } ElementAndProcessor<T> elementAndProcessor = queue.poll(); processor = elementAndProcessor.getProcessor(); return ProcessorState.ofResult(elementAndProcessor.getElement()); } } }); }

Target:
static <T> WorkProcessor<T> mergeSorted(Iterable<WorkProcessor<T>> processorIterable, Comparator<T> comparator) { requireNonNull(comparator, "comparator is null"); Iterator<WorkProcessor<T>> processorIterator = requireNonNull(processorIterable, "processorIterable is null").iterator(); checkArgument(processorIterator.hasNext(), "There must be at least one base processor"); PriorityQueue<ElementAndProcessor<T>> queue = new PriorityQueue<>(2, comparing(ElementAndProcessor::getElement, comparator)); return create(new WorkProcessor.Process<T>() { WorkProcessor<T> processor = requireNonNull(processorIterator.next()); @Override public ProcessorState<T> process() { while (true) { if (processor.process()) { if (!processor.isFinished()) { queue.add(new ElementAndProcessor<>(processor.getResult(), processor)); } } else if (processor.isBlocked()) { return ProcessorState.blocked(processor.getBlockedFuture()); } else { return ProcessorState.yield(); } if (processorIterator.hasNext()) { processor = processorIterator.next(); continue; } if (queue.isEmpty()) { return ProcessorState.finished(); } ElementAndProcessor<T> elementAndProcessor = queue.poll(); processor = elementAndProcessor.getProcessor(); return ProcessorState.ofResult(elementAndProcessor.getElement()); } } }); }
Source:
public void recordConnectionAcquiredNanos(long elapsedAcquiredNanos) { super.recordConnectionAcquiredNanos(elapsedAcquiredNanos); }

Target:
public void recordConnectionAcquiredNanos(long elapsedAcquiredNanos) { elapsedAcquiredSummary.observe(elapsedAcquiredNanos); }
Source:
public List<Location> getLocations() { final ArrayList<Location> locations = new ArrayList<>(); final Location top = this.getLocation(); if (this.getBase() == null) { return locations; } final Location iterLoc = this.getBase().getLocation(); final double ySpacing = 2; while (iterLoc.getY() <= top.getY()) { locations.add(iterLoc.clone()); iterLoc.add(0, ySpacing, 0); } return locations; }

Target:
public List<Location> getLocations() { if (this.getBase() == null) { return new ArrayList<>(); } final ArrayList<Location> locations = new ArrayList<>(); final Location top = this.getLocation(); final Location iterLoc = this.getBase().getLocation(); final double ySpacing = 2; while (iterLoc.getY() <= top.getY()) { locations.add(iterLoc.clone()); iterLoc.add(0, ySpacing, 0); } return locations; }
Source:
public String shell(PyObject[] args, String[] kws) { ArgParser ap = JythonUtils.createArgParser(args, kws); Preconditions.checkNotNull(ap); String cmd = ap.getString(0); if(args.length == 2) return impl.shell(cmd, ap.getInt(1)); else return impl.shell(cmd); }

Target:
public String shell(PyObject[] args, String[] kws) { ArgParser ap = JythonUtils.createArgParser(args, kws); Preconditions.checkNotNull(ap); String cmd = ap.getString(0); if (args.length == 2) { return impl.shell(cmd, ap.getInt(1)); } else { return impl.shell(cmd); } }
Source:
public void renameList() { onBrickAtPosition(0).checkShowsText(R.string.brick_when_started); onBrickAtPosition(1).checkShowsText(R.string.brick_change_size_by); onBrickAtPosition(1).onChildView(withId(R.id.brick_change_size_by_edit_text)).perform(click()); onView(withId(R.id.formula_editor_keyboard_data)).perform(click()); onView(withId(R.id.button_add)).perform(click()); onView(withId(R.id.dialog_formula_editor_data_is_list_checkbox)).perform(setCheckboxChecked(true)); onView(withId(R.id.dialog_formula_editor_data_name_edit_text)).perform(typeText(variableNameOld)); onView(withText(R.string.ok)).perform(click()); onView(withText(variableNameOld)).perform(click()); onView(withId(R.id.formula_editor_edit_field)).check(matches(withText(getUserListEditText(variableNameOld)))); onView(withId(R.id.formula_editor_keyboard_data)).perform(click()); onView(withText(variableNameOld)).perform(longClick()); onView(withText(R.string.rename)).perform(click()); onView(withId(R.id.dialog_formula_rename_variable_name_edit_text)) .perform(clearText(), typeText(variableNameNew)); onView(withText(R.string.ok)).perform(click()); pressBack(); onView(withId(R.id.formula_editor_edit_field)).check(matches(withText(getUserListEditText(variableNameNew)))); }

Target:
public void renameList() { onBrickAtPosition(whenBrickPosition).checkShowsText(R.string.brick_when_started); onBrickAtPosition(changeSizeBrickPosition).checkShowsText(R.string.brick_change_size_by); onBrickAtPosition(changeSizeBrickPosition).onChildView(withId(R.id.brick_change_size_by_edit_text)) .perform(click()); onView(withId(R.id.formula_editor_keyboard_data)) .perform(click()); onView(withId(R.id.button_add)) .perform(click()); onView(withId(R.id.dialog_formula_editor_data_name_edit_text)) .perform(replaceText(variableNameOld), closeSoftKeyboard()); onView(withId(R.id.dialog_formula_editor_data_is_list_checkbox)) .perform(click()); onView(withText(R.string.ok)) .perform(click()); onView(withText(variableNameOld)) .perform(click()); onView(withId(R.id.formula_editor_edit_field)) .check(matches(withText(getUserListEditText(variableNameOld)))); onView(withId(R.id.formula_editor_keyboard_data)) .perform(click()); onView(withText(variableNameOld)) .perform(longClick()); onView(withText(R.string.rename)) .perform(click()); onView(withId(R.id.dialog_formula_rename_variable_name_edit_text)) .perform(replaceText(variableNameNew), closeSoftKeyboard()); onView(withText(R.string.ok)) .perform(click()); pressBack(); onView(withId(R.id.formula_editor_edit_field)).check(matches(withText(getUserListEditText(variableNameNew)))); }
Source:
public void setSamples(List<String> samples) { int i = 0; int size = samples == null? 0 : samples.size(); sampleIds = new HashMap<>(size); idSamples = new HashMap<>(size); if (samples != null) { for (String sample : samples) { sampleIds.put(sample, i); idSamples.put(i, sample); i++; } } }

Target:
public void setSamples(List<String> samples) { int i = 0; assert samples != null; int size = samples.size(); sampleIds = new HashMap<>(size); idSamples = new HashMap<>(size); for (String sample : samples) { sampleIds.put(sample, i); idSamples.put(i, sample); i++; } }
Source:
AzureClient(String storageConnectionString) { try { account = CloudStorageAccount.parse(storageConnectionString); blobClient = account.createCloudBlobClient(); tableClient = account.createCloudTableClient(); } catch (IllegalArgumentException | URISyntaxException e) { LOG.info("\nConnection string specifies an invalid URI."); LOG.info("Please confirm the connection string is in the Azure connection string format."); throw new SamzaException(e); } catch (InvalidKeyException e) { LOG.info("\nConnection string specifies an invalid key."); LOG.info("Please confirm the AccountName and AccountKey in the connection string are valid."); throw new SamzaException(e); } }

Target:
AzureClient(String storageConnectionString) { try { account = CloudStorageAccount.parse(storageConnectionString); blobClient = account.createCloudBlobClient(); tableClient = account.createCloudTableClient(); } catch (IllegalArgumentException | URISyntaxException e) { LOG.error("\nConnection string specifies an invalid URI.", storageConnectionString); LOG.error("Please confirm the connection string is in the Azure connection string format."); throw new SamzaException(e); } catch (InvalidKeyException e) { LOG.error("\nConnection string specifies an invalid key.", storageConnectionString); LOG.error("Please confirm the AccountName and AccountKey in the connection string are valid."); throw new SamzaException(e); } }
Source:
protected void unregisterVersioningFilter(VersioningFilterDescriptor contrib) { versioningFiltersRegistry.removeContribution(contrib); log.info("Unregistered versioning policy: " + contrib.getId()); recompute(); }

Target:
protected void unregisterVersioningFilter(VersioningFilterDescriptor contrib) { versioningFiltersRegistry.removeContribution(contrib); log.info("Unregistered versioning filter: " + contrib.getId()); recompute(); }
Source:
public DatagramSocketImpl(VertxInternal vertx, DatagramSocketOptions options) { super(vertx, createChannel(copiedOptions(options)), vertx.getOrCreateContext(), new DatagramMetrics(vertx)); ContextImpl creatingContext = vertx.getContext(); if (creatingContext != null && creatingContext.isMultithreaded()) { throw new IllegalStateException("Cannot use DatagramSocket in a multi-threaded worker verticle"); } context.getEventLoop().register(channel); channel.pipeline().addLast("handler", new DatagramServerHandler(this.vertx, this)); channel().config().setMaxMessagesPerRead(1); }

Target:
public DatagramSocketImpl(VertxInternal vertx, DatagramSocketOptions options) { super(vertx, createChannel(options.isIpV6() ? io.vertx.core.datagram.impl.InternetProtocolFamily.IPv6 : io.vertx.core.datagram.impl.InternetProtocolFamily.IPv4, DatagramSocketOptions.copiedOptions(options)), vertx.getOrCreateContext(), vertx.metricsSPI().register(null, options)); ContextImpl creatingContext = vertx.getContext(); if (creatingContext != null && creatingContext.isMultithreaded()) { throw new IllegalStateException("Cannot use DatagramSocket in a multi-threaded worker verticle"); } channel().config().setOption(ChannelOption.DATAGRAM_CHANNEL_ACTIVE_ON_REGISTRATION, true); context.getEventLoop().register(channel); channel.pipeline().addLast("handler", new DatagramServerHandler(this.vertx, this)); channel().config().setMaxMessagesPerRead(1); }
Source:
public static boolean hasUnresolvedCalls(@NotNull List<GoExpression> expressionList) { for (GoExpression expression : expressionList) { if (expression instanceof GoCallExpr) { expression = ((GoCallExpr)expression).getExpression(); if (expression.getGoType(null) == null) { if (expression.getReference() != null) { if (expression.getReference().resolve() == null) { return true; } continue; } return true; } } } return false; }

Target:
public static boolean hasUnresolvedCalls(@NotNull List<GoExpression> expressionList) { for (GoExpression expression : expressionList) { if (!(expression instanceof GoCallExpr)) continue; expression = ((GoCallExpr)expression).getExpression(); if (expression.getGoType(null) != null) continue; PsiReference ref = expression.getReference(); if (ref == null || ref.resolve() == null) return true; } return false; }
Source:
public JsonNode getEventSchema(String eventString) { JsonNode event = this.schemaLoader.parse(eventString, false); return this.getEventSchema(event); }

Target:
public JsonNode getEventSchema(String eventString) { JsonNode event = this.schemaLoader.parse(eventString); return this.getEventSchema(event); }
Source:
public Float getFinishedPercentage() { return (float) (finalFeatureList.size() == 0?0:1); }

Target:
public Float getFinishedPercentage() { if (objPeakDetection != null) return objPeakDetection.getFinishedPercent(); else return (float) 0; }
Source:
public synchronized String get(String key) { synchronized (LOCK) { if (isPersistenceEnabled) { final String actualKey = key + SHARED_PREFERENCES_DATA_IDENTIFIER_SUFFIX; if (!sharedPreferences.contains(actualKey)) { return null; } final int keyValueStoreVersion = Integer.parseInt( sharedPreferences .getString(actualKey + SHARED_PREFERENCES_STORE_VERSION_SUFFIX, null)); if (keyValueStoreVersion != AWS_KEY_VALUE_STORE_VERSION) { logger.error("The version of the data read from SharedPreferences for " + key + " does not match the version of the store."); return null; } final String encryptedData = sharedPreferences.getString(actualKey, null); byte[] iv = getInitializationVector(actualKey); try { String decryptedDataInString = decrypt(apiLevel >= ANDROID_API_LEVEL_23 ? new GCMParameterSpec(CIPHER_AES_GCM_NOPADDING_TAG_LENGTH_LENGTH_IN_BITS, iv) : new IvParameterSpec(iv), encryptedData); cache.put(key, decryptedDataInString); return decryptedDataInString; } catch (Exception ex) { logger.error("Error in decrypting data. ", ex); return null; } } else { return cache.get(key); } } }

Target:
public synchronized String get(String key) { synchronized (LOCK) { if (isPersistenceEnabled) { final String actualKey = key + SHARED_PREFERENCES_DATA_IDENTIFIER_SUFFIX; if (!sharedPreferences.contains(actualKey)) { return null; } try { final int keyValueStoreVersion = Integer.parseInt( sharedPreferences .getString(actualKey + SHARED_PREFERENCES_STORE_VERSION_SUFFIX, null)); if (keyValueStoreVersion != AWS_KEY_VALUE_STORE_VERSION) { logger.error("The version of the data read from SharedPreferences for " + key + " does not match the version of the store."); return null; } final String encryptedData = sharedPreferences.getString(actualKey, null); byte[] iv = getInitializationVector(actualKey); String decryptedDataInString = decrypt(apiLevel >= ANDROID_API_LEVEL_23 ? new GCMParameterSpec(CIPHER_AES_GCM_NOPADDING_TAG_LENGTH_LENGTH_IN_BITS, iv) : new IvParameterSpec(iv), encryptedData); cache.put(key, decryptedDataInString); return decryptedDataInString; } catch (Exception ex) { logger.error("Error in decrypting data. ", ex); return null; } } else { return cache.get(key); } } }
Source:
public static long hammingDistance(@SqlType("varchar(x)") Slice left, @SqlType("varchar(y)") Slice right) { int[] leftCodePoints = castToCodePoints(left); int[] rightCodePoints = castToCodePoints(right); checkCondition( leftCodePoints.length == rightCodePoints.length, INVALID_FUNCTION_ARGUMENT, "The input strings for Hamming distance must have the same length"); int distance = 0; for (int i = 0; i < leftCodePoints.length; i++) { if (leftCodePoints[i] != rightCodePoints[i]) { distance++; } } return distance; }

Target:
public static long hammingDistance(@SqlType("varchar(x)") Slice left, @SqlType("varchar(y)") Slice right) { int distance = 0; int leftPosition = 0; int rightPosition = 0; while (leftPosition < left.length() && rightPosition < right.length()) { int codePointLeft = tryGetCodePointAt(left, leftPosition); int codePointRight = tryGetCodePointAt(right, rightPosition); if (codePointLeft != codePointRight) { distance++; } leftPosition += codePointLeft > 0 ? lengthOfCodePoint(codePointLeft) : -codePointLeft; rightPosition += codePointRight > 0 ? lengthOfCodePoint(codePointRight) : -codePointRight; } checkCondition( leftPosition == left.length() && rightPosition == right.length(), INVALID_FUNCTION_ARGUMENT, "The input strings to hamming_distance function must have the same length"); return distance; }
Source:
public ImportNetworksModel(final com.google.inject.Provider<CommonModel> commonModelProvider, NetworkListModel sourceListModel) { this(sourceListModel, commonModelProvider); }

Target:
public ImportNetworksModel(final com.google.inject.Provider<CommonModel> commonModelProvider, NetworkListModel sourceListModel) { super(sourceListModel, commonModelProvider); }
Source:
public void registerSchemaDefinitions(SchemaDefinitions sd) { this.sd = sd; sd.validateSchema(); RemoteCache<String,String> protobufCache = getProtobufCache(); sd.deploySchema( schemaFileName, protobufCache, schemaCapture, schemaOverrideService ); try { marshaller.getSerializationContext().registerProtoFiles( sd.asFileDescriptorSource() ); } catch (DescriptorParserException | IOException e) { throw log.errorAtProtobufParsing( e ); } this.sequences = new HotRodSequenceHandler( this, marshaller, sd.getSequenceDefinitions() ); if ( createCachesEnabled ) { cacheHandler = new HotRodCacheCreationHandler( cacheConfiguration, sd.getCacheConfigurationByName() ); } else { cacheHandler = new HotRodCacheValidationHandler( sd.getCacheConfigurationByName().keySet() ); } cacheHandler.startAndValidateCaches( hotrodClient ); perCacheSchemaMappers = sd.generateSchemaMappingAdapters( this, sd, marshaller ); }

Target:
public void registerSchemaDefinitions(SchemaDefinitions sd) { this.sd = sd; sd.validateSchema(); RemoteCache<String,String> protobufCache = getProtobufCache(); sd.deploySchema( schemaFileName, protobufCache, schemaCapture, schemaOverrideService ); try { marshaller.getSerializationContext().registerProtoFiles( sd.asFileDescriptorSource() ); } catch (DescriptorParserException | IOException e) { throw log.errorAtProtobufParsing( e ); } this.sequences = new HotRodSequenceHandler( this, marshaller, sd.getSequenceDefinitions() ); if ( createCachesEnabled ) { cacheHandler = new HotRodCacheCreationHandler( cacheConfiguration, sd.getCacheConfigurationByName() ); } else { cacheHandler = new HotRodCacheValidationHandler( sd.getCacheConfigurationByName().keySet() ); } try { cacheHandler.startAndValidateCaches( hotrodClient ); } catch ( HotRodClientException ex ) { log.errorAtCachesStart( ex ); } perCacheSchemaMappers = sd.generateSchemaMappingAdapters( this, sd, marshaller ); }
Source:
public Object decode(Response response, Type type) throws IOException, FeignException { if (response.status() == 204 && Types.getRawType(type).equals(Optional.class)) { return Optional.absent(); } else { System.out.println("here I am"); if (isOptional(type)) { Type innerType = getInnerType(type); return Optional.of(delegate.decode(response, innerType)); } return delegate.decode(response, type); } }

Target:
public Object decode(Response response, Type type) throws IOException, FeignException { if (Types.getRawType(type).equals(Optional.class)) { if (response.status() == 204) { return Optional.absent(); } else { Object decoded = checkNotNull(delegate.decode(response, getInnerType(type)), "Unexpected null content for response status %d", response.status()); return Optional.of(decoded); } } else { return delegate.decode(response, type); } }
Source:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (!getParameters().isForceAction() && getParameters().getAction() != GlusterTaskOperation.COMMIT) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_NOT_SUPPORTED_FOR_GLUSTER); return false; } if (getGlusterVolume().getVolumeType().isReplicatedType()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_NOT_SUPPORTED_FOR_VOLUME_TYPE); return false; } if (!getGlusterVolume().isOnline()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_GLUSTER_VOLUME_IS_DOWN); return false; } if (getParameters().getExistingBrick() == null || getParameters().getNewBrick() == null) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_BRICKS_REQUIRED); return false; } if (!updateBrickServerAndInterfaceName(getParameters().getExistingBrick(), true)) { return false; } if (!updateBrickServerAndInterfaceName(getParameters().getNewBrick(), true)) { return false; } if (!isValidVolumeBrick(getParameters().getExistingBrick())) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_NOT_A_GLUSTER_VOLUME_BRICK); return false; } return true; }

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (!getGlusterVolume().getVolumeType().isReplicatedType()) { addCanDoActionMessage(EngineMessage.ACTION_TYPE_NOT_SUPPORTED_FOR_VOLUME_TYPE); return false; } if (!getGlusterVolume().isOnline()) { addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_GLUSTER_VOLUME_IS_DOWN); return false; } if (getGlusterVolume().getAsyncTask() != null && getGlusterVolume().getAsyncTask().getStatus() == JobExecutionStatus.STARTED) { addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_GLUSTER_VOLUME_HAS_RUNNING_TASKS); return false; } if (getParameters().getExistingBrick() == null || getParameters().getNewBrick() == null) { addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_BRICKS_REQUIRED); return false; } if (!updateBrickServerAndInterfaceName(getParameters().getExistingBrick(), true)) { return false; } if (!updateBrickServerAndInterfaceName(getParameters().getNewBrick(), true)) { return false; } if (!isValidVolumeBrick(getParameters().getExistingBrick())) { addCanDoActionMessage(EngineMessage.ACTION_TYPE_FAILED_NOT_A_GLUSTER_VOLUME_BRICK); return false; } return true; }
Source:
protected void initialiseRoleIds(ContentEntity entity) { this.roleIds = entity.getRoleAccessIds(); this.inheritedRoleIds = entity.getInheritedRoleAccessIds(); }

Target:
protected void initialiseRoleIds(ContentEntity entity) { for (String roleId : availableRoleIds()) { if (contentService.isInheritingRoleView(entity.getId(), roleId)) { this.inheritedRoleIds.add(roleId); } else if (contentService.isRoleView(entity.getId(), roleId)) { this.roleIds.add(roleId); } } }
Source:
private static HttpUriRequest getDownloadFileRequest(URI uri, int socketTimeoutMs) { RequestBuilder requestBuilder = RequestBuilder.get(uri).setVersion(HttpVersion.HTTP_1_1); setTimeout(requestBuilder, socketTimeoutMs); if (uri.getUserInfo() != null) { String encoded = Base64.encodeBase64String(StringUtil.encodeUtf8(uri.getUserInfo())); String authHeader = "Basic " + encoded; requestBuilder.addHeader(HttpHeaders.AUTHORIZATION, authHeader); } return requestBuilder.build(); }

Target:
private static HttpUriRequest getDownloadFileRequest(URI uri, int socketTimeoutMs) { RequestBuilder requestBuilder = RequestBuilder.get(uri).setVersion(HttpVersion.HTTP_1_1); setTimeout(requestBuilder, socketTimeoutMs); String userInfo = uri.getUserInfo(); if (userInfo != null) { String encoded = Base64.encodeBase64String(StringUtil.encodeUtf8(userInfo)); String authHeader = "Basic " + encoded; requestBuilder.addHeader(HttpHeaders.AUTHORIZATION, authHeader); } return requestBuilder.build(); }
Source:
private AnnotatedTypeMirror getTypeVariableFromDeclaration( AnnotatedTypeVariable type, AnnotatedTypeFactory f) { TypeVariable typeVar = type.getUnderlyingType(); TypeParameterElement tpe = (TypeParameterElement) typeVar.asElement(); Element elt = tpe.getGenericElement(); if (elt instanceof TypeElement) { TypeElement typeElt = (TypeElement) elt; int idx = typeElt.getTypeParameters().indexOf(tpe); ClassTree cls = (ClassTree) f.declarationFromElement(typeElt); if (cls == null || cls.getTypeParameters().isEmpty()) { return type.asUse(); } return visitTypeParameter(cls.getTypeParameters().get(idx), f).asUse(); } else if (elt instanceof ExecutableElement) { ExecutableElement exElt = (ExecutableElement) elt; int idx = exElt.getTypeParameters().indexOf(tpe); MethodTree meth = (MethodTree) f.declarationFromElement(exElt); if (meth == null) { return type.asUse(); } AnnotatedTypeVariable result = visitTypeParameter(meth.getTypeParameters().get(idx), f).shallowCopy(); result.setDeclaration(false); return result; } else if (TypesUtils.isCaptured(typeVar)) { return type.asUse(); } else { throw new BugInCF("TypeFromTree.forTypeVariable: not a supported element: " + elt); } }

Target:
private AnnotatedTypeVariable getTypeVariableFromDeclaration( AnnotatedTypeVariable type, AnnotatedTypeFactory f) { TypeVariable typeVar = type.getUnderlyingType(); TypeParameterElement tpe = (TypeParameterElement) typeVar.asElement(); Element elt = tpe.getGenericElement(); if (elt instanceof TypeElement) { TypeElement typeElt = (TypeElement) elt; int idx = typeElt.getTypeParameters().indexOf(tpe); ClassTree cls = (ClassTree) f.declarationFromElement(typeElt); if (cls == null || cls.getTypeParameters().isEmpty()) { return type.asUse(); } return visitTypeParameter(cls.getTypeParameters().get(idx), f).asUse(); } else if (elt instanceof ExecutableElement) { ExecutableElement exElt = (ExecutableElement) elt; int idx = exElt.getTypeParameters().indexOf(tpe); MethodTree meth = (MethodTree) f.declarationFromElement(exElt); if (meth == null) { return type.asUse(); } AnnotatedTypeVariable result = visitTypeParameter(meth.getTypeParameters().get(idx), f).shallowCopy(); result.setDeclaration(false); return result; } else if (TypesUtils.isCaptured(typeVar)) { return type.asUse(); } else { throw new BugInCF("TypeFromTree.forTypeVariable: not a supported element: " + elt); } }
Source:
protected SQLTranslation findOrCreateTranslation(@Nonnull Mapping field, String lang, String text) { if (!isValidLanguage(lang, field.getName())) { return null; } Optional<SQLTranslation> translation = fetchTranslation(field, lang); if (translation.isPresent()) { return translation.get(); } else { SQLTranslation sqlTranslation = new SQLTranslation(); sqlTranslation.getTranslationData().setOwner(owner.getUniqueName()); sqlTranslation.getTranslationData().setField(field.getName()); sqlTranslation.getTranslationData().setLang(lang); return sqlTranslation; } }

Target:
protected SQLTranslation findOrCreateTranslation(@Nonnull Mapping field, String lang, String text) { assertValidLanguage(lang, field.getName()); Optional<SQLTranslation> translation = fetchTranslation(field, lang); if (translation.isPresent()) { return translation.get(); } else { SQLTranslation sqlTranslation = new SQLTranslation(); sqlTranslation.getTranslationData().setOwner(owner.getUniqueName()); sqlTranslation.getTranslationData().setField(field.getName()); sqlTranslation.getTranslationData().setLang(lang); return sqlTranslation; } }
Source:
public static String readStream(InputStream is) { StringBuffer sb = new StringBuffer(""); try { byte[] b = new byte[4096]; while (true) { int l = is.read(b, 0, b.length); if (l < 0) break; sb.append(new String(b, 0, l)); } is.close(); } catch (IOException e) { e.printStackTrace(); Assert.fail(e.getMessage()); } return sb.toString(); }

Target:
public static String readStream(InputStream is) { StringBuffer sb = new StringBuffer(""); try { byte[] b = new byte[4096]; while (true) { int l = is.read(b, 0, b.length); if (l < 0) break; sb.append(new String(b, 0, l)); } } catch (IOException e) { e.printStackTrace(); Assert.fail(e.getMessage()); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); Assert.fail(e.getMessage()); } } return sb.toString(); }
Source:
private void untrackHashInvalidationForEventualCache(InvalidationCompleteMessage message) { ehcacheStateService.getInvalidationTracker(message.getCacheId()).getInvalidationMap().computeIfPresent(message.getKey(), (key, count) -> { if (count == 1) { return null; } return count--; }); }

Target:
private void untrackHashInvalidationForEventualCache(InvalidationCompleteMessage message) { ehcacheStateService.getInvalidationTracker(message.getCacheId()).getInvalidationMap().computeIfPresent(message.getKey(), (key, count) -> { if (count == 1) { return null; } return count - 1; }); }
Source:
private PieDataset createPerspectiveViewPieDataset() { double divisor = perspectiveDebug + perspectiveJava + perspectiveOther; final DefaultPieDataset result = new DefaultPieDataset(); result.setValue("Java" + printPercent(perspectiveJava, divisor), perspectiveJava); result.setValue("Debug" + printPercent(perspectiveDebug, divisor), perspectiveDebug); result.setValue("Other" + printPercent(perspectiveOther, divisor), perspectiveOther); return result; }

Target:
private PieDataset createPerspectiveViewPieDataset() { double divisor = perspectiveDebug + perspectiveJava + perspectiveOther; DefaultPieDataset result = new DefaultPieDataset(); result.setValue("Java" + printPercent(perspectiveJava, divisor), perspectiveJava); result.setValue("Debug" + printPercent(perspectiveDebug, divisor), perspectiveDebug); result.setValue("Other" + printPercent(perspectiveOther, divisor), perspectiveOther); return result; }
Source:
private void restartMeasurementLoader(String ministryId, String mcc, String period) { final LoaderManager manager = this.getSupportLoaderManager(); Bundle args = new Bundle(3); args.putString("ministryId", ministryId); args.putString("mcc", mcc); args.putString("period", period); manager.restartLoader(LOADER_MEASUREMENTS, args, measurementsLoaderCallbacks); }

Target:
private void restartMeasurementLoader(String ministryId, String mcc, String period) { final LoaderManager manager = this.getSupportLoaderManager(); Bundle args = new Bundle(3); args.putString(Constants.ARG_MINISTRY_ID, ministryId); args.putString(Constants.ARG_MCC, mcc); args.putString(Constants.ARG_PERIOD, period); manager.restartLoader(LOADER_MEASUREMENTS, args, measurementsLoaderCallbacks); }
Source:
private void validateAndSetDefaultsSubAccount(AccountingXmlDocumentAccountingLine xmlAccountingLine, AmazonKfsAccountDTO defaultAccountDto, boolean logErrorMessage) { if (StringUtils.isNotBlank(xmlAccountingLine.getSubAccountNumber()) && !validateSubAccountNumber(xmlAccountingLine.getChartCode(), xmlAccountingLine.getAccountNumber(), xmlAccountingLine.getSubAccountNumber(), logErrorMessage)) { if (validateSubAccountNumber(xmlAccountingLine.getChartCode(), xmlAccountingLine.getAccountNumber(), defaultAccountDto.getKfsSubAccount(), logErrorMessage)) { xmlAccountingLine.setSubAccountNumber(defaultAccountDto.getKfsSubAccount()); } } }

Target:
private void validateAndSetDefaultsSubAccount(AccountingXmlDocumentAccountingLine xmlAccountingLine, AmazonKfsAccountDTO defaultAccountDto, boolean logErrorMessage) { if (StringUtils.isNotBlank(xmlAccountingLine.getSubAccountNumber()) && !validateSubAccountNumber(xmlAccountingLine.getChartCode(), xmlAccountingLine.getAccountNumber(), xmlAccountingLine.getSubAccountNumber(), logErrorMessage)) { if (validateSubAccountNumber(xmlAccountingLine.getChartCode(), xmlAccountingLine.getAccountNumber(), defaultAccountDto.getKfsSubAccount(), logErrorMessage)) { xmlAccountingLine.setSubAccountNumber(defaultAccountDto.getKfsSubAccount()); } else { xmlAccountingLine.setSubAccountNumber(StringUtils.EMPTY); } } }
Source:
private PartitionId getPartitionForPut() throws CoordinatorException { List<? extends PartitionId> partitions = clusterMap.getWritablePartitionIds(); if (partitions.isEmpty()) { throw new CoordinatorException("No writable partitions available.", CoordinatorError.AmbryUnavailable); } return partitions.get((int) getRandomLong(randomForPartitionSelection, partitions.size())); }

Target:
private PartitionId getPartitionForPut() throws CoordinatorException { List<PartitionId> partitions = clusterMap.getWritablePartitionIds(); if (partitions.isEmpty()) { throw new CoordinatorException("No writable partitions available.", CoordinatorError.AmbryUnavailable); } return partitions.get((int) getRandomLong(randomForPartitionSelection, partitions.size())); }
Source:
List<DataTypeTreeGridItem> makeTreeGridItems(final DataType dataType, final int level) { final DataTypeTreeGridItem gridItem = getGridItem(); final List<DataType> subDataTypes = dataType.getSubDataTypes(); final List<DataTypeTreeGridItem> gridItems = new ArrayList<>(); gridItem.setupDataType(dataType, level); gridItems.add(gridItem); if (!subDataTypes.isEmpty()) { for (final DataType subDataType : subDataTypes) { gridItems.addAll(makeTreeGridItems(subDataType, level + 1)); } } return gridItems; }

Target:
List<DataTypeTreeGridItem> makeTreeGridItems(final DataType dataType, final int level) { final DataTypeTreeGridItem gridItem = getGridItem(); final List<DataType> subDataTypes = dataType.getSubDataTypes(); final List<DataTypeTreeGridItem> gridItems = new ArrayList<>(); gridItem.setupDataType(dataType, level); gridItems.add(gridItem); for (final DataType subDataType : subDataTypes) { gridItems.addAll(makeTreeGridItems(subDataType, level + 1)); } return gridItems; }
Source:
public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { seriesCount = 0; H5PositionList.clear(); H5PathsToImageData.clear(); cellObjectNames.clear(); if (jhdf != null) { jhdf.close(); } jhdf = null; lastChannel = 0; } }

Target:
public void close(boolean fileOnly) throws IOException { try { super.close(fileOnly); } finally { if (!fileOnly) { seriesCount = 0; H5PositionList.clear(); H5PathsToImageData.clear(); cellObjectNames.clear(); if (jhdf != null) { jhdf.close(); } jhdf = null; lastChannel = 0; } } }
Source:
public GraphFrame(Graph pGraph, TabPane pTabbedPane) { super(); aTabbedPane = pTabbedPane; ToolBar sideBar = new ToolBar(pGraph); aPanel = new GraphPanel(pGraph, sideBar, this); BorderPane layout = new BorderPane(); layout.setRight(sideBar); SwingNode panelNode = new SwingNode(); panelNode.setContent(new JScrollPane(aPanel)); layout.setCenter(panelNode); setTitle(false); setContent(layout); setOnCloseRequest(pEvent -> { pEvent.consume(); EditorFrame editorFrame = (EditorFrame) getTabPane().getParent(); editorFrame.close(this); }); }

Target:
public GraphFrame(Graph pGraph, TabPane pTabbedPane) { aTabbedPane = pTabbedPane; ToolBar sideBar = new ToolBar(pGraph); aPanel = new GraphPanel(pGraph, sideBar, this); BorderPane layout = new BorderPane(); layout.setRight(sideBar); SwingNode panelNode = new SwingNode(); panelNode.setContent(new JScrollPane(aPanel)); layout.setCenter(panelNode); setTitle(false); setContent(layout); setOnCloseRequest(pEvent -> { pEvent.consume(); EditorFrame editorFrame = (EditorFrame) getTabPane().getParent(); editorFrame.close(this); }); }
Source:
public Session<L> findSession(String id) { Map.Entry<MV, AV> value = this.factory.findValue(id); if (value == null) { InfinispanWebLogger.ROOT_LOGGER.infof("Session %s not found", id); return null; } ImmutableSession session = this.factory.createImmutableSession(id, value); if (session.getMetaData().isExpired()) { InfinispanWebLogger.ROOT_LOGGER.infof("Session %s was found, but has expired", id); this.expirationListener.sessionExpired(session); this.factory.remove(id); return null; } this.expirationScheduler.cancel(id); return new ValidSession<>(this.factory.createSession(id, value, this.context), this.expirationScheduler); }

Target:
public Session<L> findSession(String id) { Map.Entry<MV, AV> value = this.factory.findValue(id); if (value == null) { InfinispanWebLogger.ROOT_LOGGER.tracef("Session %s not found", id); return null; } ImmutableSession session = this.factory.createImmutableSession(id, value); if (session.getMetaData().isExpired()) { InfinispanWebLogger.ROOT_LOGGER.tracef("Session %s was found, but has expired", id); this.expirationListener.sessionExpired(session); this.factory.remove(id); return null; } this.expirationScheduler.cancel(id); return new ValidSession<>(this.factory.createSession(id, value, this.context), this.expirationScheduler); }
Source:
public static boolean checkNetwork(Context context, @NonNull View view) { if (isInternetOn(context)) { return true; } else Toast.makeText(context,R.string.internet_is_off,Toast.LENGTH_SHORT).show(); return false; }

Target:
public static boolean checkNetwork(Context context, @NonNull View view) { if (isInternetOn(context)) { return true; } else Snackbar.make(view,R.string.internet_is_off,Snackbar.LENGTH_SHORT).show(); return false; }
Source:
private static void deleteAccount(UserInfo userInfo, String loginFilePath, String groupFilePath, Properties props, Multimap<String, String> groupsMap) throws ManageUsersException { if (userInfo.getLogin().isEmpty()) { warnWithMessage("Provided username is empty, skipping."); return; } if (!props.containsKey(userInfo.getLogin())) { warnWithMessage("USER " + userInfo.getLogin() + " does not exist in login file : " + loginFilePath); } if (!groupsMap.containsKey(userInfo.getLogin())) { warnWithMessage("USER " + userInfo.getLogin() + " does not exist in group file : " + groupFilePath); } props.remove(userInfo.getLogin()); groupsMap.removeAll(userInfo.getLogin()); System.out.println("Deleted user " + userInfo.getLogin()); }

Target:
private static void deleteAccount(UserInfo userInfo, String loginFilePath, String groupFilePath, Properties props, Multimap<String, String> groupsMap) throws ManageUsersException { if (!userInfo.isLoginSet()) { warnWithMessage(PROVIDED_USERNAME + IS_EMPTY_SKIPPING); return; } if (!props.containsKey(userInfo.getLogin())) { warnWithMessage(USER_HEADER + userInfo.getLogin() + DOES_NOT_EXIST_IN_LOGIN_FILE + loginFilePath); } if (!groupsMap.containsKey(userInfo.getLogin())) { warnWithMessage(USER_HEADER + userInfo.getLogin() + DOES_NOT_EXIST_IN_GROUP_FILE + groupFilePath); } props.remove(userInfo.getLogin()); groupsMap.removeAll(userInfo.getLogin()); System.out.println("Deleted user " + userInfo.getLogin()); }
Source:
public void validate(FailureCollector collector) { if (port != null && (port < 1 || port > 65535)) { collector.addFailure("Invalid port.", "Port number must be an integer from 1 to 65535.") .withConfigProperty(Cassandra.PORT); } }

Target:
public void validate(FailureCollector collector) { if (port != null && (port < 1 || port > 65535)) { collector.addFailure("Invalid port number.", "Port number must be an integer from 1 to 65535.") .withConfigProperty(Cassandra.PORT); } }
Source:
protected void decode( ChannelHandlerContext ctx, ByteBuf in, List<Object> out ) { if ( contentTypeProtocol.isExpecting( ContentType.ContentType ) ) { byte b = in.readByte(); ContentType contentType = getContentType( b ); contentTypeProtocol.expect( contentType ); } else { ctx.fireChannelRead( in.retain() ); } }

Target:
protected void decode( ChannelHandlerContext ctx, ByteBuf in, List<Object> out ) { if ( contentTypeProtocol.isExpecting( ContentType.ContentType ) ) { byte messageCode = in.readByte(); ContentType contentType = getContentType( messageCode ); contentTypeProtocol.expect( contentType ); } else { ctx.fireChannelRead( in.retain() ); } }
Source:
public RqSimple(final Iterable<String> head, final InputStream body) { super( new RqOf( () -> head, () -> body ) ); }

Target:
public RqSimple(final Iterable<String> head, final InputStream body) { super(new RequestOf(head, body)); }
Source:
private StringParameterValue checkValue(StringParameterValue value) { if (!choices.contains(value.value)) throw new IllegalArgumentException("For " + getName() + ", illegal choice: " + value.value); return value; }

Target:
private StringParameterValue checkValue(StringParameterValue value) { if (!choices.contains(value.value)) throw new IllegalArgumentException("Illegal choice for parameter " + getName() + ": " + value.value); return value; }
Source:
public ContainerProxy getProxy(String hostname, int port) { String upstream = hostname + ":" + port; return proxies.computeIfAbsent(upstream, __ -> { try { final int toxiPort = nextPort.getAndIncrement(); if (toxiPort > LAST_PROXIED_PORT) { throw new IllegalStateException("Maximum number of proxies exceeded"); } final Proxy proxy = client.createProxy(hostname, "0.0.0.0:" + toxiPort, upstream); return new ContainerProxy(proxy, getContainerIpAddress(), getMappedPort(toxiPort)); } catch (IOException e) { throw new RuntimeException("Proxy could not be created", e); } }); }

Target:
public ContainerProxy getProxy(String hostname, int port) { String upstream = hostname + ":" + port; return proxies.computeIfAbsent(upstream, __ -> { try { final int toxiPort = nextPort.getAndIncrement(); if (toxiPort > LAST_PROXIED_PORT) { throw new IllegalStateException("Maximum number of proxies exceeded"); } final Proxy proxy = client.createProxy(upstream, "0.0.0.0:" + toxiPort, upstream); return new ContainerProxy(proxy, getContainerIpAddress(), getMappedPort(toxiPort)); } catch (IOException e) { throw new RuntimeException("Proxy could not be created", e); } }); }
Source:
public void savePreferences(ActionRequest request, ActionResponse response) throws IOException, PortletException { User sessionUser = UserCacheHolder.getUserFromRequest(request); UserService.Iface userClient = thriftClients.makeUserClient(); try { User user = userClient.getByEmail(sessionUser.getEmail()); user.setWantsMailNotification(false); PortletUtils.setFieldValue(request, user, User._Fields.WANTS_MAIL_NOTIFICATION, User.metaDataMap.get(User._Fields.WANTS_MAIL_NOTIFICATION), ""); if (user.isWantsMailNotification()) { Map<String, Boolean> preferences = new HashMap<>(); SW360Constants.NOTIFICATION_EVENTS_KEYS.forEach(k -> { String value = request.getParameter(User._Fields.NOTIFICATION_PREFERENCES.toString() + k); if (value != null) { preferences.put(k, Boolean.TRUE); } }); user.setNotificationPreferences(preferences); } userClient.updateUser(user); request.setAttribute(PortalConstants.SW360_USER, user); } catch (TException e) { log.error("An error occurred while updating the user record", e); response.setProperty(ResourceResponse.HTTP_STATUS_CODE, Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); } }

Target:
public void savePreferences(ActionRequest request, ActionResponse response) throws IOException, PortletException { User sessionUser = UserCacheHolder.getUserFromRequest(request); UserService.Iface userClient = thriftClients.makeUserClient(); try { User user = userClient.getByEmail(sessionUser.getEmail()); PortletUtils.setFieldValue(request, user, User._Fields.WANTS_MAIL_NOTIFICATION, User.metaDataMap.get(User._Fields.WANTS_MAIL_NOTIFICATION), ""); if (user.isWantsMailNotification()) { Map<String, Boolean> preferences = new HashMap<>(); SW360Constants.NOTIFICATION_EVENTS_KEYS.forEach(k -> { String value = request.getParameter(User._Fields.NOTIFICATION_PREFERENCES.toString() + k); if (value != null) { preferences.put(k, Boolean.TRUE); } }); user.setNotificationPreferences(preferences); } userClient.updateUser(user); request.setAttribute(PortalConstants.SW360_USER, user); } catch (TException e) { log.error("An error occurred while updating the user record", e); response.setProperty(ResourceResponse.HTTP_STATUS_CODE, Integer.toString(HttpServletResponse.SC_INTERNAL_SERVER_ERROR)); } }
Source:
void tryToProvidePreviewSurface() { if (mResolution == null || mSurfaceTexture == null || mSurfaceCompleter == null) { return; } mSurfaceTexture.setDefaultBufferSize(mResolution.getWidth(), mResolution.getHeight()); final Surface surface = new Surface(mSurfaceTexture); mSurfaceReleaseFuture.addListener(() -> { surface.release(); mSurfaceReleaseFuture = null; }, ContextCompat.getMainExecutor(mTextureView.getContext())); mSurfaceCompleter.set(surface); mSurfaceCompleter = null; transformPreview(); }

Target:
void tryToProvidePreviewSurface() { if (mResolution == null || mSurfaceTexture == null || mSurfaceCompleter == null) { return; } mSurfaceTexture.setDefaultBufferSize(mResolution.getWidth(), mResolution.getHeight()); final Surface surface = new Surface(mSurfaceTexture); final ListenableFuture<Void> surfaceReleaseFuture = mSurfaceReleaseFuture; mSurfaceReleaseFuture.addListener(() -> { surface.release(); if (mSurfaceReleaseFuture == surfaceReleaseFuture) { mSurfaceReleaseFuture = null; } }, ContextCompat.getMainExecutor(mTextureView.getContext())); mSurfaceCompleter.set(surface); mSurfaceCompleter = null; transformPreview(); }
Source:
public DataInputStream getChunkDataInputStream(int x, int z) throws IOException { checkBounds(x, z); int offset = getOffset(x, z); if (offset == 0) { return null; } int sectorNumber = offset >> 8; int numSectors = offset & 0xFF; if (sectorNumber + numSectors > totalSectors) { throw new IOException("Invalid sector: " + sectorNumber + "+" + numSectors + " > " + totalSectors); } file.seek(sectorNumber * SECTOR_BYTES); int length = file.readInt(); if (length > SECTOR_BYTES * numSectors) { throw new IOException("Invalid length: " + length + " > " + SECTOR_BYTES * numSectors); } byte version = file.readByte(); if (version == VERSION_GZIP) { byte[] data = new byte[length - 1]; file.read(data); return new DataInputStream(new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(data)))); } else if (version == VERSION_DEFLATE) { byte[] data = new byte[length - 1]; file.read(data); return new DataInputStream(new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(data)))); } throw new IOException("Unknown version: " + version); }

Target:
public DataInputStream getChunkDataInputStream(int x, int z) throws IOException { checkBounds(x, z); int offset = getOffset(x, z); if (offset == 0) { return null; } int sectorNumber = offset >> 8; int numSectors = offset & 0xFF; if (sectorNumber + numSectors > totalSectors) { throw new IOException("Invalid sector: " + sectorNumber + "+" + numSectors + " > " + totalSectors); } file.seek(sectorNumber * SECTOR_BYTES); int length = file.readInt(); if (length > SECTOR_BYTES * numSectors) { throw new IOException("Invalid length: " + length + " > " + SECTOR_BYTES * numSectors); } byte version = file.readByte(); if (version == VERSION_GZIP) { byte[] data = new byte[length - 1]; file.read(data); return new DataInputStream(new BufferedInputStream(new GZIPInputStream(new ByteArrayInputStream(data), 2048))); } else if (version == VERSION_DEFLATE) { byte[] data = new byte[length - 1]; file.read(data); return new DataInputStream(new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(data), new Inflater(), 2048))); } throw new IOException("Unknown version: " + version); }