auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { if (contentRepository != null) { AuthorizationResult authorizationResult = context.authorize(operation, ACTION_EFFECT_SET); if (authorizationResult.getDecision() == AuthorizationResult.Decision.DENY) { throw ControllerLogger.ROOT_LOGGER.unauthorized(operation.get(ModelDescriptionConstants.OP).asString(), PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)), authorizationResult.getExplanation()); } try { InputStream is = getContentInputStream(context, operation); try { byte[] hash = contentRepository.addContent(is); context.getResult().set(hash); } finally { safeClose(is); } } catch (IOException e) { throw new RuntimeException(e); } } context.stepCompleted(); }

Target:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { if (contentRepository != null) { AuthorizationResult authorizationResult = context.authorize(operation, ACTION_EFFECT_SET); if (authorizationResult.getDecision() == AuthorizationResult.Decision.DENY) { throw ControllerLogger.ROOT_LOGGER.unauthorized(operation.get(ModelDescriptionConstants.OP).asString(), PathAddress.pathAddress(operation.get(ModelDescriptionConstants.OP_ADDR)), authorizationResult.getExplanation()); } try { InputStream is = getContentInputStream(context, operation); try { byte[] hash = contentRepository.addContent(is); context.getResult().set(hash); } finally { safeClose(is); } } catch (IOException e) { throw DEPLOYMENT_LOGGER.caughtIOExceptionUploadingContent(e); } } context.stepCompleted(); }
Source:
public void testNetworks() throws Exception { assumeTrue("Docker API should be at least v1.21 to support Container Creation with " + "HostConfig, got " + sut.version().apiVersion(), compareVersion(sut.version().apiVersion(), "1.21") >= 0); assumeFalse(CIRCLECI); final String networkName = randomName(); final Ipam ipam = Ipam.builder().driver("default").config("192.168.0.0/24", "192.168.0.0/24", "192.168.0.1") .build(); final NetworkConfig networkConfig = NetworkConfig.builder().name(networkName).driver("bridge").checkDuplicate(true).ipam(ipam) .build(); final NetworkCreation networkCreation = sut.createNetwork(networkConfig); assertThat(networkCreation.id(), is(notNullValue())); assertThat(networkCreation.getWarnings(), is(nullValue())); final List<Network> networks = sut.listNetworks(); assertTrue(networks.size() > 0); Network network = null; for (Network n : networks) { if (n.name().equals(networkName)) { network = n; } } assertThat(network, is(notNullValue())); assertThat(network.id(), is(notNullValue())); assertThat(sut.inspectNetwork(network.id()).name(), is(networkName)); assertThat(network.ipam(), equalTo(ipam)); sut.removeNetwork(network.id()); try { sut.inspectNetwork(network.id()); fail(); } catch (NetworkNotFoundException e) { } catch (Exception e) { fail(); } }

Target:
public void testNetworks() throws Exception { assumeTrue("Docker API should be at least v1.21 to support Container Creation with " + "HostConfig, got " + sut.version().apiVersion(), compareVersion(sut.version().apiVersion(), "1.21") >= 0); assumeFalse(CIRCLECI); final String networkName = randomName(); final Ipam ipam = Ipam.builder().driver("default").config("192.168.0.0/24", "192.168.0.0/24", "192.168.0.1") .build(); final NetworkConfig networkConfig = NetworkConfig.builder().name(networkName).driver("bridge").checkDuplicate(true).ipam(ipam) .build(); final NetworkCreation networkCreation = sut.createNetwork(networkConfig); assertThat(networkCreation.id(), is(notNullValue())); assertThat(networkCreation.warnings(), is(nullValue())); final List<Network> networks = sut.listNetworks(); assertTrue(networks.size() > 0); Network network = null; for (Network n : networks) { if (n.name().equals(networkName)) { network = n; } } assertThat(network, is(notNullValue())); assertThat(network.id(), is(notNullValue())); assertThat(sut.inspectNetwork(network.id()).name(), is(networkName)); assertThat(network.ipam(), equalTo(ipam)); sut.removeNetwork(network.id()); exception.expect(NetworkNotFoundException.class); sut.inspectNetwork(network.id()); }
Source:
public Connection createConnection() throws SQLException { Connection con = null; if (username != null && pass != null) { con = DriverManager.getConnection(connectionUrl, username, pass); } else { con = DriverManager.getConnection(connectionUrl); } return con; }

Target:
private Connection createConnection() throws SQLException { return JDBCUtils.createConnection(connectionUrl, username, pass); }
Source:
public Result loadInBackground() { try { return actOn(request.execute()); } catch (Failure failure) { if (failure.getCause() instanceof HttpRequest.HttpRequestException) { return Result.NETWORK_FAILURE; } else { if (failure.getMessage().equals("")) { return Result.FAILURE; } else { Result result = Result.ERROR; result.setResultMessage(failure.getMessage()); return result; } } } }

Target:
public Result loadInBackground() { try { return actOn(request.execute()); } catch (Failure failure) { return actOnFailure(failure); } }
Source:
public void testSetAttribute_multiple_set() { Connection ept = new Connection(defaultConnectionDefinition); Value v = new BooleanValue(true); ept.setAttribute("v", v); Value v2 = new BooleanValue(false); ept.setAttribute("v", v2); }

Target:
public void testSetAttribute_multiple_set() { Connection ept = new Connection(defaultConnectionDefinition); Type boolType = new BooleanType(); Value v = new BooleanValue(boolType, true); ept.setAttribute("v", v); Value v2 = new BooleanValue(boolType, false); ept.setAttribute("v", v2); }
Source:
public TestingPhoenixServer() { this.conf.setInt(HConstants.MASTER_INFO_PORT, -1); this.conf.setInt(HConstants.REGIONSERVER_INFO_PORT, -1); this.conf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 1); this.conf.set("hbase.regionserver.wal.codec", "org.apache.hadoop.hbase.regionserver.wal.IndexedWALEditCodec"); this.conf.setBoolean("phoenix.schema.isNamespaceMappingEnabled", true); this.htu = new HBaseTestingUtility(conf); try { this.port = randomPort(); this.htu.startMiniZKCluster(1, port); MiniHBaseCluster hbm = htu.startMiniHBaseCluster(1, 4); hbm.waitForActiveAndReadyMaster(); LOG.info("Phoenix server ready: %s", getJdbcUrl()); } catch (Exception e) { throw new IllegalStateException("Can't start phoenix server.", e); } Runtime.getRuntime().addShutdownHook(new Thread(() -> { if (htu != null) { try { LOG.info("Shutting down HBase cluster."); htu.shutdownMiniHBaseCluster(); htu.shutdownMiniZKCluster(); } catch (IOException e) { Thread.currentThread().interrupt(); throw new PrestoException(SERVER_SHUTTING_DOWN, "Failed to shutdown HTU instance", e); } htu = null; } })); }

Target:
public TestingPhoenixServer() { this.conf.setInt(HConstants.MASTER_INFO_PORT, -1); this.conf.setInt(HConstants.REGIONSERVER_INFO_PORT, -1); this.conf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 1); this.conf.set("hbase.regionserver.wal.codec", "org.apache.hadoop.hbase.regionserver.wal.IndexedWALEditCodec"); this.conf.setBoolean("phoenix.schema.isNamespaceMappingEnabled", true); this.hbaseTestingUtility = new HBaseTestingUtility(conf); try { this.port = randomPort(); this.hbaseTestingUtility.startMiniZKCluster(1, port); MiniHBaseCluster hbm = hbaseTestingUtility.startMiniHBaseCluster(1, 4); hbm.waitForActiveAndReadyMaster(); LOG.info("Phoenix server ready: %s", getJdbcUrl()); } catch (Exception e) { throw new IllegalStateException("Can't start phoenix server.", e); } Runtime.getRuntime().addShutdownHook(new Thread(() -> { close(); })); }
Source:
public String systemStreamToStreamId(SystemStream systemStream) { List<String> streamIds = getStreamIdsForSystem(systemStream.getSystem()).stream() .filter(streamId -> systemStream.getStream().equals(getPhysicalName(streamId))).collect(Collectors.toList()); if (streamIds.size() > 1) { throw new IllegalStateException(String.format("There was more than one stream found for system stream %s", systemStream)); } return streamIds.isEmpty() ? null : streamIds.get(0); }

Target:
private String systemStreamToStreamId(SystemStream systemStream) { List<String> streamIds = getStreamIdsForSystem(systemStream.getSystem()).stream() .filter(streamId -> systemStream.getStream().equals(getPhysicalName(streamId))).collect(Collectors.toList()); if (streamIds.size() > 1) { throw new IllegalStateException(String.format("There was more than one stream found for system stream %s", systemStream)); } return streamIds.isEmpty() ? null : streamIds.get(0); }
Source:
public double getDistanceSafely() throws InvalidSensorException { return super.readSensor()[0]; }

Target:
public double getDistanceSafely() throws InvalidSensorException { return super.readSensor()[CANInfraredDistanceSensor.DISTANCE_SENSOR_ARRAY_INDEX]; }
Source:
public BlockFamily createBlockFamily(BlockFamilyDefinition definition, BlockShape shape, BlockBuilderHelper blockBuilder) { switch( shape.getBlockShapePlacement().getType() ) { case Edge: return edge.createBlockFamily(definition, shape, blockBuilder); case HorizontalSide: return horizontal.createBlockFamily(definition, shape, blockBuilder); default: return symmetric.createBlockFamily(definition, shape, blockBuilder); } }

Target:
public BlockFamily createBlockFamily(BlockFamilyDefinition definition, BlockShape shape, BlockBuilderHelper blockBuilder) { switch( shape.getBlockShapePlacement().getType() ) { case SIDE: return side.createBlockFamily(definition, shape, blockBuilder); case EDGE: return edge.createBlockFamily(definition, shape, blockBuilder); case CORNER: return corner.createBlockFamily(definition, shape, blockBuilder); case HORIZONTAL_SIDE: return horizontal.createBlockFamily(definition, shape, blockBuilder); case CUBE: return symmetric.createBlockFamily(definition, shape, blockBuilder); } return symmetric.createBlockFamily(definition, shape, blockBuilder); }
Source:
private static Connector createTestSessionConnector() { return new Connector() { @Override public ConnectorTransactionHandle beginTransaction(IsolationLevel isolationLevel, boolean readOnly) { return new ConnectorTransactionHandle() {}; } @Override public ConnectorMetadata getMetadata(ConnectorTransactionHandle transaction) { return new TestingConnectorMetadata(new SystemTablesMetadata(new ConnectorId("test_session_connector"), new StaticSystemTablesProvider(ImmutableSet.of()))); } @Override public ConnectorSplitManager getSplitManager() { throw new UnsupportedOperationException(); } }; }

Target:
private static Connector createTestSessionConnector() { return new Connector() { @Override public ConnectorTransactionHandle beginTransaction(IsolationLevel isolationLevel, boolean readOnly) { return new ConnectorTransactionHandle() {}; } @Override public ConnectorMetadata getMetadata(ConnectorTransactionHandle transaction) { return new SystemTablesMetadata(new ConnectorId("test_session_connector"), new StaticSystemTablesProvider(ImmutableSet.of())); } @Override public ConnectorSplitManager getSplitManager() { throw new UnsupportedOperationException(); } }; }
Source:
protected void forceCommit() { log.info("Force commit after a move"); final Map<TopicPartition, OffsetAndMetadata> offsets = new HashMap<>(topicPartitions.size()); topicPartitions.forEach(topicPartition -> offsets.put(topicPartition, new OffsetAndMetadata(consumer.position(topicPartition)))); consumer.commitSync(offsets); offsets.forEach((topicPartition, offset) -> lastCommittedOffsets.put(topicPartition, offset.offset())); consumerMoved = false; lastOffsets.clear(); }

Target:
protected void forceCommit() { log.info("Force commit after a move"); Map<TopicPartition, OffsetAndMetadata> offsets = topicPartitions.stream().collect(toMap(tp -> tp, tp -> new OffsetAndMetadata(consumer.position(tp)))); consumer.commitSync(offsets); offsets.forEach((topicPartition, offset) -> lastCommittedOffsets.put(topicPartition, offset.offset())); consumerMoved = false; lastOffsets.clear(); }
Source:
private EObject getEObjectUsingURIFragmentAsId(String uriFragment) { if (isLoading) { EObject eObject = super.getEObject(uriFragment); if (eObject != null) { String fragment = EcoreUtil.getURI(eObject).fragment(); if (fragment != null) { setID(eObject, fragment); } } return eObject; } else { EObject eObject = getEObjectByID(uriFragment); if (eObject == null) { eObject = super.getEObject(uriFragment); if (eObject != null) { String fragment = EcoreUtil.getURI(eObject).fragment(); if (fragment != null) { setID(eObject, fragment); return getEObject(uriFragment); } } } return eObject; } }

Target:
private EObject getEObjectUsingURIFragmentAsId(String uriFragment) { EObject eObject = null; if (isLoading) { eObject = getEObjectAndUpdateIDMap(uriFragment); } else { eObject = getEObjectByID(uriFragment); if (eObject == null) { eObject = getEObjectAndUpdateIDMap(uriFragment); } } return eObject; }
Source:
public void createTable(String tableName, String... columnFamilies) throws IOException { final StringBuilder createTableBuilder = new StringBuilder(); createTableBuilder.append("create").append(" "); createTableBuilder.append(String.format("'%s'", tableName)).append(","); for (final String columnFamily : columnFamilies) { createTableBuilder .append(String.format("{NAME=>'%s'}", columnFamily)) .append(","); } createTableBuilder.deleteCharAt(createTableBuilder.lastIndexOf(",")); executeHBaseShell(createTableBuilder.toString()); }

Target:
public void createTable(String tableName, String... columnFamilies) throws IOException { final String createTable = String.format("create '%s',", tableName) + Arrays.stream(columnFamilies) .map(cf -> String.format("{NAME=>'%s'}", cf)) .collect(Collectors.joining(",")); executeHBaseShell(createTable); }
Source:
public void processQualifier_useInvalidUsername_getUsernameWarning() { TurboUser user = new TurboUser(REPO, "fox", "charlie"); IModel model = TestUtils.singletonModel(new Model(REPO, new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), new ArrayList<>(Arrays.asList(user)))); verifyUserWarning(model, "involves:bOb", Arrays.asList(String.format( USER_WARNING_ERROR_FORMAT, "bOb", REPO))); verifyUserWarning(model, "involves:foxX", Arrays.asList(String.format( USER_WARNING_ERROR_FORMAT, "foxX", REPO))); verifyUserWarning(model, "author:alice", Arrays.asList(String.format( USER_WARNING_ERROR_FORMAT, "alice", REPO))); }

Target:
public void processQualifier_useInvalidUsername_getUsernameWarning() { TurboUser user = new TurboUser(REPO, "fox", "charlie"); IModel model = TestUtils.singletonModel(createModelFromUsers(REPO, user)); verifyUserWarning(model, "involves:bOb", Arrays.asList(String.format(USER_WARNING_ERROR_FORMAT, "bOb", REPO))); verifyUserWarning(model, "involves:foxX", Arrays.asList(String.format(USER_WARNING_ERROR_FORMAT, "foxX", REPO))); verifyUserWarning(model, "author:alice", Arrays.asList(String.format(USER_WARNING_ERROR_FORMAT, "alice", REPO))); }
Source:
public AssignmentMetadataStore(HelixManager helixManager) { _dataAccessor = new ZkBucketDataAccessor(helixManager.getMetadataStoreConnectionString()); _baselinePath = "/" + helixManager.getClusterName() + "/" + ASSIGNMENT_METADATA_KEY + "/" + BASELINE_KEY; _bestPossiblePath = "/" + helixManager.getClusterName() + "/" + ASSIGNMENT_METADATA_KEY + "/" + BEST_POSSIBLE_KEY; }

Target:
AssignmentMetadataStore(HelixManager helixManager) { _dataAccessor = new ZkBucketDataAccessor(helixManager.getMetadataStoreConnectionString()); _baselinePath = String.format(BASELINE_TEMPLATE, helixManager.getClusterName(), ASSIGNMENT_METADATA_KEY); _bestPossiblePath = String.format(BEST_POSSIBLE_TEMPLATE, helixManager.getClusterName(), ASSIGNMENT_METADATA_KEY); }
Source:
protected IDataSet getDataSet() throws Exception { try (java.io.InputStream resourceAsStream = getClass() .getClassLoader() .getResourceAsStream("dbunit/data.xml")) { return new FlatXmlDataSetBuilder().build(resourceAsStream); } }

Target:
protected IDataSet getDataSet() throws Exception { try (InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream("dbunit/data.xml")) { return new FlatXmlDataSetBuilder().build(resourceAsStream); } }
Source:
private void updateDiseaseOccurrenceFinalWeighting(DiseaseOccurrence occurrence, Set<DiseaseOccurrence> pendingSave) { double locationResolutionWeighting = occurrence.getLocation().getResolutionWeighting(); double feedWeighting = occurrence.getAlert().getFeed().getWeighting(); double diseaseGroupTypeWeighting = occurrence.getDiseaseGroup().getWeighting(); double weighting; if (locationResolutionWeighting == 0.0 || diseaseGroupTypeWeighting == 0.0) { weighting = 0.0; } else { weighting = average(Arrays.asList(locationResolutionWeighting, feedWeighting, diseaseGroupTypeWeighting, occurrence.getValidationWeighting())); } if (occurrence.getFinalWeighting() == null || occurrence.getFinalWeighting() != weighting) { pendingSave.add(occurrence); occurrence.setFinalWeighting(weighting); } }

Target:
private void updateDiseaseOccurrenceFinalWeighting(DiseaseOccurrence occurrence, Set<DiseaseOccurrence> pendingSave) { double locationResolutionWeighting = occurrence.getLocation().getResolutionWeighting(); double feedWeighting = occurrence.getAlert().getFeed().getWeighting(); double diseaseGroupTypeWeighting = occurrence.getDiseaseGroup().getWeighting(); double weighting; if (locationResolutionWeighting == 0.0 || diseaseGroupTypeWeighting == 0.0) { weighting = 0.0; } else { weighting = (double) avg(Arrays.asList(locationResolutionWeighting, feedWeighting, diseaseGroupTypeWeighting, occurrence.getValidationWeighting())); } if (hasWeightingChanged(occurrence.getFinalWeighting(), weighting)) { pendingSave.add(occurrence); occurrence.setFinalWeighting(weighting); } }
Source:
protected boolean canDoAction() { boolean returnValue = checkStoragePool(); if (returnValue) { if (getStoragePool().getStatus() == StoragePoolStatus.Uninitialized) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_STATUS_ILLEGAL); return false; } else if (getStorageDomain() != null && getStorageDomain().getStatus() != null && getStorageDomain().getStatus() == StorageDomainStatus.Active) { addStorageDomainStatusIllegalMessage(); returnValue = false; } else if (electNewMaster(false) != null) { getReturnValue().getCanDoActionMessages().add( VdcBllMessages.STORAGE_POOL_REINITIALIZE_WITH_MORE_THAN_ONE_DATA_DOMAIN.toString()); returnValue = false; } else { StorageDomain domain = getNewMasterDomain(); if (domain.getStorageDomainSharedStatus() != StorageDomainSharedStatus.Unattached) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL); returnValue = false; } } } return returnValue && initializeVds(); }

Target:
protected boolean canDoAction() { boolean returnValue = checkStoragePool(); if (!validate(new StorageDomainValidator(getStorageDomain()).isInProcess()) || !validate(new StoragePoolValidator(getStoragePool()).isAnyDomainInProcess())) { return false; } if (returnValue) { if (getStoragePool().getStatus() == StoragePoolStatus.Uninitialized) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_POOL_STATUS_ILLEGAL); return false; } else if (getStorageDomain() != null && getStorageDomain().getStatus() != null && getStorageDomain().getStatus() == StorageDomainStatus.Active) { addStorageDomainStatusIllegalMessage(); returnValue = false; } else if (electNewMaster(false) != null) { getReturnValue().getCanDoActionMessages().add( VdcBllMessages.STORAGE_POOL_REINITIALIZE_WITH_MORE_THAN_ONE_DATA_DOMAIN.toString()); returnValue = false; } else { StorageDomain domain = getNewMasterDomain(); if (domain.getStorageDomainSharedStatus() != StorageDomainSharedStatus.Unattached) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL); returnValue = false; } } } return returnValue && initializeVds(); }
Source:
public void aboutToBeShown() { this.getController().onNewLabel(new IConsumer<String>() { @Override public void apply(String value) { if (!label.isDisposed() && !(label.getText() != null && label.getText().equals(value))) { label.setText(value); } } }); this.getController().onNewHelp(new IConsumer<String>() { @Override public void apply(String value) { if (help != null && !help.isDisposed() && !(help.getText() != null && help.getText().equals(value))) { help.setToolTipText(value); } } }); this.getController().onValidation(new IConsumer<List<IValidationRuleResult>>() { @Override public void apply(List<IValidationRuleResult> validationRuleResults) { IMessageManager messageManager = page.getForm().getMessageManager(); for (IValidationRuleResult validationRuleResult : validationRuleResults) { if (validationRuleResult instanceof IInvalidValidationRuleResult) { IInvalidValidationRuleResult result = (IInvalidValidationRuleResult) validationRuleResult; messageManager.addMessage(result.getValidationRule(), result.getMessage(), result.getData(), result.getSeverity(), getValidationControl()); } else { messageManager.removeMessage(validationRuleResult.getValidationRule(), getValidationControl()); } } } }); }

Target:
public void aboutToBeShown() { super.aboutToBeShown(); this.getController().onNewLabel(new IConsumer<String>() { @Override public void apply(String value) { if (!label.isDisposed() && !(label.getText() != null && label.getText().equals(value))) { label.setText(value); } } }); this.getController().onNewHelp(new IConsumer<String>() { @Override public void apply(String value) { if (help != null && !help.isDisposed() && !(help.getText() != null && help.getText().equals(value))) { help.setToolTipText(value); } } }); }
Source:
public boolean acceptsTurnRelation(OSMTurnRelation relation) { if (relation.isVehicleTypeConcernedByTurnRestriction(restrictions)) { return true; } return false; }

Target:
public boolean acceptsTurnRelation(OSMTurnRelation relation) { return relation.isVehicleTypeConcernedByTurnRestriction(restrictions); }
Source:
public String toString() { return String.format("%s{table=%s}", getClass().getName(), transitions.stream().map(Object::toString).collect(Collectors.joining(", "))); }

Target:
public String toString() { return String.format("%s{transitions=%s}", getClass().getName(), transitions.stream().map(Object::toString).collect(Collectors.joining(", "))); }
Source:
public void refresh() { isRefreshCancelled = false; savedPagesCompleted = 0; progressDialog.show(); for (int i = 0; i < savedPages.size(); i++) { final SavedPage savedPage = savedPages.get(i); new RefreshSavedPageTask(activity, savedPage) { @Override public void onBeforeExecute() { if (isRefreshCancelled) { cancel(); return; } Log.d("Wikipedia", "refreshing start: " + savedPage.getTitle().getDisplayText()); } @Override public void onFinish(List<Section> result) { if (!progressDialog.isShowing()) { isRefreshCancelled = true; return; } savedPagesCompleted++; progressDialog.setProgress(savedPagesCompleted); Log.d("Wikipedia", "Count is " + savedPagesCompleted + " of " + savedPages.size()); if (savedPagesCompleted == savedPages.size()) { progressDialog.dismiss(); FeedbackUtil.showMessage(activity, R.string.saved_pages_refresh_pages_complete); } Log.d("Wikipedia", "refreshing end: " + savedPage.getTitle().getDisplayText()); } @Override public void onCatch(Throwable caught) { isRefreshCancelled = true; if (!progressDialog.isShowing()) { return; } progressDialog.dismiss(); getErrorDialog().show(); } }.execute(); } }

Target:
public void refresh() { isRefreshCancelled = false; savedPagesCompleted = 0; progressDialog.show(); for (int i = 0; i < savedPages.size(); i++) { final SavedPage savedPage = savedPages.get(i); new RefreshSavedPageTask(context, savedPage) { @Override public void onBeforeExecute() { if (isRefreshCancelled) { cancel(); return; } Log.d("Wikipedia", "refreshing start: " + savedPage.getTitle().getDisplayText()); } @Override public void onFinish(List<Section> result) { if (!progressDialog.isShowing()) { isRefreshCancelled = true; return; } savedPagesCompleted++; progressDialog.setProgress(savedPagesCompleted); Log.d("Wikipedia", "Count is " + savedPagesCompleted + " of " + savedPages.size()); if (savedPagesCompleted == savedPages.size()) { progressDialog.dismiss(); } Log.d("Wikipedia", "refreshing end: " + savedPage.getTitle().getDisplayText()); } @Override public void onCatch(Throwable caught) { isRefreshCancelled = true; if (!progressDialog.isShowing()) { return; } progressDialog.dismiss(); getErrorDialog().show(); } }.execute(); } }
Source:
public StateChange getDefaultInstance() { if (defaultInstance == null) { DisplayResolutionDependentFBOs displayResolutionDependentFBOs = CoreRegistry.get(DisplayResolutionDependentFBOs.class); assert(displayResolutionDependentFBOs != null); defaultInstance = new SetViewportToSizeOf(displayResolutionDependentFBOs.getGBufferPair().getWriteFbo()); } return defaultInstance; }

Target:
public StateChange getDefaultInstance() { if (defaultInstance == null) { defaultInstance = new SetViewportToSizeOf(CoreRegistry.get(DisplayResolutionDependentFBOs.class).getGBufferPair().getLastUpdatedFbo()); } return defaultInstance; }
Source:
private void injectImplicitUriParameters(Node node, List<String> templates) { Node parametersNode = NodeSelector.selectFrom(URI_PARAMETERS, node); if (parametersNode != null) { for (Node child : parametersNode.getChildren()) { String parameterName = ((SimpleTypeNode) ((KeyValueNode) child).getKey()).getLiteralValue(); templates.remove(parameterName.endsWith("?") ? parameterName.substring(0, parameterName.length() - 1) : parameterName); } } else if (!templates.isEmpty()) { StringNodeImpl uriParameters = new StringNodeImpl(URI_PARAMETERS); ObjectNodeImpl objectNode = new ObjectNodeImpl(); addUriParameters(templates, objectNode); node.addChild(new KeyValueNodeImpl(uriParameters, objectNode)); } if (parametersNode != null && !templates.isEmpty()) { addUriParameters(templates, parametersNode); } }

Target:
private void injectImplicitUriParameters(Node node, List<String> templates) { Node parametersNode = NodeSelector.selectFrom(URI_PARAMETERS, node); if (parametersNode != null) { for (Node child : parametersNode.getChildren()) { String parameterName = ((SimpleTypeNode) ((KeyValueNode) child).getKey()).getLiteralValue(); templates.remove(parameterName.endsWith("?") ? parameterName.substring(0, parameterName.length() - 1) : parameterName); } if (!templates.isEmpty()) { addUriParameters(templates, parametersNode); } } else if (!templates.isEmpty()) { StringNodeImpl uriParameters = new StringNodeImpl(URI_PARAMETERS); ObjectNodeImpl objectNode = new ObjectNodeImpl(); addUriParameters(templates, objectNode); node.addChild(new KeyValueNodeImpl(uriParameters, objectNode)); } }
Source:
public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration globalConfiguration) { BasicComponentRegistry bcr = gcr.getComponent(BasicComponentRegistry.class); Interpreter interpreter = new Interpreter(); bcr.registerComponent(Interpreter.class, interpreter, true); if (globalConfiguration.statistics()) { try { CacheManagerJmxRegistration jmxRegistration = bcr.getComponent(CacheManagerJmxRegistration.class).running(); jmxRegistration.registerMBean(interpreter); } catch (Exception e) { log.jmxRegistrationFailed(); } } }

Target:
public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration globalConfiguration) { if (globalConfiguration.statistics()) { BasicComponentRegistry bcr = gcr.getComponent(BasicComponentRegistry.class); Interpreter interpreter = new Interpreter(); bcr.registerComponent(Interpreter.class, interpreter, true); try { CacheManagerJmxRegistration jmxRegistration = bcr.getComponent(CacheManagerJmxRegistration.class).running(); jmxRegistration.registerMBean(interpreter); } catch (Exception e) { throw log.jmxRegistrationFailed(e); } } }
Source:
public void deleteAddress() { List<Address> addresses = selectedDomain.getAddress(); for (int i = 0; i < addresses.size(); i++) { if (addresses.get(i).getEmailAddress().equals(getEmailAddress())) { addresses.remove(i); } } UpdateDomain updateDomain = new UpdateDomain(); updateDomain.setDomain(selectedDomain); directService.updateDomain(updateDomain); }

Target:
public void deleteAddress() { List<Address> addresses = selectedDomain.getAddress(); for (int i = 0; i < addresses.size(); i++) { if (addresses.get(i).getEmailAddress().equals(getEmailAddress())) { addresses.remove(i); break; } } UpdateDomain updateDomain = new UpdateDomain(); updateDomain.setDomain(selectedDomain); directService.updateDomain(updateDomain); }
Source:
public FileSetRepository getFileSetRepository() throws Exception { if (fileSetRepository != null) { return fileSetRepository; } if (includeDependencyManagement) { includeDependencyManagement(project, artifactFactory); } DependencyResolver dependencyResolver = new DependencyResolver(project, repositorySession, resolver, system, scopes); String name = (project.getName() != "") ? project.getName() : project.getArtifactId(); return fileSetRepository = dependencyResolver.getFileSetRepository(name, bundles, useMavenDependencies); }

Target:
public FileSetRepository getFileSetRepository() throws Exception { if (fileSetRepository != null) { return fileSetRepository; } if (includeDependencyManagement) { includeDependencyManagement(project, artifactFactory); } DependencyResolver dependencyResolver = new DependencyResolver(project, repositorySession, resolver, system, scopes); String name = project.getName() .isEmpty() ? project.getArtifactId() : project.getName(); return fileSetRepository = dependencyResolver.getFileSetRepository(name, bundles, useMavenDependencies); }
Source:
protected WebRequest getWebRequest() { BroadleafRequestContext requestContext = BroadleafRequestContext.getBroadleafRequestContext(); return new ServletWebRequest(requestContext.getRequest(), requestContext.getResponse()); }

Target:
protected WebRequest getWebRequest() { return BroadleafRequestContext.getBroadleafRequestContext().getWebRequest(); }
Source:
public static <T extends Serializable> void cleanRepoSerializable(final JpaRepository<T, Long> repo) { try { repo.deleteAllInBatch(); } catch (final Exception e) { System.err.println(e); } }

Target:
public static <T extends Serializable> void cleanRepoSerializable(final JpaRepository<T, Long> repo) { try { repo.deleteAllInBatch(); } catch (final Exception ex) { LOGGER.error(ex.getMessage()); } }
Source:
private void exportFilesAsList() throws SemanticException, IOException { try (BufferedWriter writer = writer()) { RemoteIterator<LocatedFileStatus> itr = dataFileSystem.listFiles(dataFileListPath, true); while (itr.hasNext()) { LocatedFileStatus fileStatus = itr.next(); if (shouldExport(fileStatus)) { writer.write(encodedUri(fileStatus)); writer.newLine(); } } } }

Target:
private void exportFilesAsList() throws SemanticException, IOException { try (BufferedWriter writer = writer()) { FileStatus[] fileStatuses = LoadSemanticAnalyzer.matchFilesOrDir(dataFileSystem, dataFileListPath); for (FileStatus fileStatus : fileStatuses) { writer.write(encodedUri(fileStatus)); writer.newLine(); } } }
Source:
public static String decodeString(@Nonnull String s) { String out = ""; try { out = URLDecoder.decode(s,"UTF-8"); } catch (Exception e) return out; }

Target:
public static String decodeString(@Nonnull String s) { try { return URLDecoder.decode(s, "UTF-8"); } catch (UnsupportedEncodingException e) { return s; } }
Source:
public List<ScriptSequenceAction> addActionToSequence(Sprite sprite, ScriptSequenceAction sequence) { sequence.addAction(sprite.getActionFactory().createStitchAction(sprite)); return null; }

Target:
public List<ScriptSequenceAction> addActionToSequence(Sprite sprite, ScriptSequenceAction sequence) { sequence.addAction(ActionFactory.createStitchAction(sprite)); return null; }
Source:
protected Query rewriteTermsQuery(TermsQuery query) { Map<String, List<SpanTermQuery>> spanQueries = new HashMap<>(); try { Field termsField = TermsQuery.class.getDeclaredField("termData"); termsField.setAccessible(true); PrefixCodedTerms terms = (PrefixCodedTerms) termsField.get(query); PrefixCodedTerms.TermIterator it = terms.iterator(); for (int i = 0; i < terms.size(); i++) { BytesRef term = BytesRef.deepCopyOf(it.next()); if (!spanQueries.containsKey(it.field())) { spanQueries.put(it.field(), new ArrayList<SpanTermQuery>()); } spanQueries.get(it.field()).add(new SpanTermQuery(new Term(it.field(), term))); } BooleanQuery.Builder builder = new BooleanQuery.Builder(); for (Map.Entry<String,List<SpanTermQuery>> entry : spanQueries.entrySet()) { List<SpanTermQuery> termQueries = entry.getValue(); builder.add(new SpanOrQuery(termQueries.toArray(new SpanTermQuery[termQueries.size()])), BooleanClause.Occur.SHOULD); } return builder.build(); } catch (Exception e) { throw new IllegalStateException(e); } }

Target:
protected Query rewriteTermsQuery(TermsQuery query) { Map<String, List<SpanTermQuery>> spanQueries = new HashMap<>(); try { Field termsField = TermsQuery.class.getDeclaredField("termData"); termsField.setAccessible(true); PrefixCodedTerms terms = (PrefixCodedTerms) termsField.get(query); PrefixCodedTerms.TermIterator it = terms.iterator(); for (int i = 0; i < terms.size(); i++) { BytesRef term = BytesRef.deepCopyOf(it.next()); if (spanQueries.containsKey(it.field()) == false) { spanQueries.put(it.field(), new ArrayList<SpanTermQuery>()); } spanQueries.get(it.field()).add(new SpanTermQuery(new Term(it.field(), term))); } BooleanQuery.Builder builder = new BooleanQuery.Builder(); for (Map.Entry<String,List<SpanTermQuery>> entry : spanQueries.entrySet()) { List<SpanTermQuery> termQueries = entry.getValue(); builder.add(new SpanOrQuery(termQueries.toArray(new SpanTermQuery[termQueries.size()])), BooleanClause.Occur.SHOULD); } return builder.build(); } catch (Exception e) { throw new IllegalStateException(e); } }
Source:
public Collection<Service> getAll() { if (services == null) { return null; } return services.values(); }

Target:
public Collection<Service> getAll() { return services.values(); }
Source:
public Key(String group, ModuleType type, String label) { Assert.notNull(group, "Stream is required"); Assert.notNull(type, "Type is required"); Assert.hasText(label, "Label is required"); this.group = group; this.type = type; this.label = label; }

Target:
public Key(String group, ModuleType type, String label) { Assert.notNull(group, "Group is required"); Assert.notNull(type, "Type is required"); Assert.hasText(label, "Label is required"); this.group = group; this.type = type; this.label = label; }
Source:
private static int[] calculateLevelOffsets(int numItems, int degree) { List<Integer> offsets = new ArrayList<>(); offsets.add(0); int level = 0; while (numItems > 1) { int capacity = ((numItems + degree - 1) / degree) * degree; offsets.add(offsets.get(level) + ENVELOPE_SIZE * capacity); numItems = capacity / degree; level += 1; } return offsets.stream().mapToInt(Integer::intValue).toArray(); }

Target:
private static int[] calculateLevelOffsets(int numItems, int degree) { List<Integer> offsets = new ArrayList<>(); offsets.add(0); int level = 0; while (numItems > 1) { int numChildren = (int) Math.ceil(1.0 * numItems / degree) * degree; offsets.add(offsets.get(level) + ENVELOPE_SIZE * numChildren); numItems = numChildren / degree; level += 1; } return offsets.stream().mapToInt(Integer::intValue).toArray(); }
Source:
public void testWifiEnterpriseConfigSerializeDeserializeThrowsIllegalArgException() throws Exception { WifiEnterpriseConfig config = new WifiEnterpriseConfig(); config.setFieldValue(WifiEnterpriseConfig.IDENTITY_KEY, TEST_IDENTITY); config.setFieldValue(WifiEnterpriseConfig.ANON_IDENTITY_KEY, TEST_ANON_IDENTITY); config.setFieldValue(WifiEnterpriseConfig.PASSWORD_KEY, TEST_PASSWORD); config.setFieldValue(WifiEnterpriseConfig.CLIENT_CERT_KEY, TEST_CLIENT_CERT); config.setFieldValue(WifiEnterpriseConfig.CA_CERT_KEY, TEST_CA_CERT); config.setFieldValue(WifiEnterpriseConfig.SUBJECT_MATCH_KEY, TEST_SUBJECT_MATCH); config.setFieldValue(WifiEnterpriseConfig.ENGINE_KEY, TEST_ENGINE); config.setFieldValue(WifiEnterpriseConfig.ENGINE_ID_KEY, TEST_ENGINE_ID); config.setFieldValue(WifiEnterpriseConfig.PRIVATE_KEY_ID_KEY, TEST_PRIVATE_KEY_ID); config.setFieldValue(WifiEnterpriseConfig.ALTSUBJECT_MATCH_KEY, TEST_ALTSUBJECT_MATCH); config.setFieldValue(WifiEnterpriseConfig.DOM_SUFFIX_MATCH_KEY, TEST_DOM_SUFFIX_MATCH); config.setFieldValue(WifiEnterpriseConfig.CA_PATH_KEY, TEST_CA_PATH); config.setEapMethod(TEST_EAP_METHOD); config.setPhase2Method(TEST_PHASE2_METHOD); String xmlString = new String(serializeWifiEnterpriseConfig(config)); xmlString = xmlString.replaceAll( String.format(XML_STRING_EAP_METHOD_REPLACE_FORMAT, TEST_EAP_METHOD), String.format(XML_STRING_EAP_METHOD_REPLACE_FORMAT, WifiEnterpriseConfig.Eap.NONE)); deserializeWifiEnterpriseConfig(xmlString.getBytes()); }

Target:
public void testWifiEnterpriseConfigSerializeDeserializeThrowsIllegalArgException() throws Exception { WifiEnterpriseConfig config = new WifiEnterpriseConfig(); config.setFieldValue(WifiEnterpriseConfig.IDENTITY_KEY, TEST_IDENTITY); config.setFieldValue(WifiEnterpriseConfig.ANON_IDENTITY_KEY, TEST_ANON_IDENTITY); config.setFieldValue(WifiEnterpriseConfig.PASSWORD_KEY, TEST_PASSWORD); config.setFieldValue(WifiEnterpriseConfig.CLIENT_CERT_KEY, TEST_CLIENT_CERT); config.setFieldValue(WifiEnterpriseConfig.CA_CERT_KEY, TEST_CA_CERT); config.setFieldValue(WifiEnterpriseConfig.SUBJECT_MATCH_KEY, TEST_SUBJECT_MATCH); config.setFieldValue(WifiEnterpriseConfig.ENGINE_KEY, TEST_ENGINE); config.setFieldValue(WifiEnterpriseConfig.ENGINE_ID_KEY, TEST_ENGINE_ID); config.setFieldValue(WifiEnterpriseConfig.PRIVATE_KEY_ID_KEY, TEST_PRIVATE_KEY_ID); config.setFieldValue(WifiEnterpriseConfig.ALTSUBJECT_MATCH_KEY, TEST_ALTSUBJECT_MATCH); config.setFieldValue(WifiEnterpriseConfig.DOM_SUFFIX_MATCH_KEY, TEST_DOM_SUFFIX_MATCH); config.setFieldValue(WifiEnterpriseConfig.CA_PATH_KEY, TEST_CA_PATH); config.setEapMethod(TEST_EAP_METHOD); config.setPhase2Method(TEST_PHASE2_METHOD); String xmlString = new String(serializeWifiEnterpriseConfig(config)); xmlString = xmlString.replaceAll( String.format(XML_STRING_EAP_METHOD_REPLACE_FORMAT, TEST_EAP_METHOD), String.format(XML_STRING_EAP_METHOD_REPLACE_FORMAT, WifiEnterpriseConfig.Eap.NONE)); deserializeWifiEnterpriseConfig(xmlString.getBytes(StandardCharsets.UTF_8)); }
Source:
public void shouldUploadFileWithDefaultOptions() throws URISyntaxException, IOException { final String uploadingFileName = "Aclass.java"; final String pathToUploadingFileInsideTheProject = format("%s/%s", PROJECT_NAME, uploadingFileName); final Path localPathToFileToUpload = get(PROJECT_SOURCES.getPath()) .resolve("src/main/java/che/eclipse/sample") .resolve(uploadingFileName); openFormAndSelectUploadFile(localPathToFileToUpload); uploadFileDialogPage.clickOnUploadButton(); uploadFileDialogPage.waitOnClose(); notificationPopup.waitExpectedMessageOnProgressPanelAndClosed( format("File '%s' has uploaded successfully", uploadingFileName)); projectExplorer.waitVisibleItem(format("%s/%s", PROJECT_NAME, uploadingFileName)); projectExplorer.openItemByPath(pathToUploadingFileInsideTheProject); editor.typeTextIntoEditor(TEXT_TO_INSERT); projectExplorer.waitAndSelectItem(PROJECT_NAME); openFormAndSelectUploadFile(localPathToFileToUpload); uploadFileDialogPage.clickOnUploadButton(); uploadFileDialogPage.waitOnClose(); notificationPopup.waitExpectedMessageOnProgressPanelAndClosed( format("File '%s' has uploaded successfully", uploadingFileName)); projectExplorer.waitVisibleItem(pathToUploadingFileInsideTheProject); projectExplorer.openItemByPath(pathToUploadingFileInsideTheProject); editor.waitTextIntoEditor(TEXT_TO_INSERT); }

Target:
public void shouldUploadFileWithDefaultOptions() throws URISyntaxException, IOException { final String uploadingFileName = "Aclass.java"; final String pathToUploadingFileInsideTheProject = format("%s/%s", PROJECT_NAME, uploadingFileName); final Path localPathToFileToUpload = get(PROJECT_SOURCES.getPath()) .resolve("src/main/java/che/eclipse/sample") .resolve(uploadingFileName); openFormAndSelectUploadFile(localPathToFileToUpload); uploadFileDialogPage.clickOnUploadButton(); uploadFileDialogPage.waitOnClose(); eventsPanel.clickEventLogBtn(); eventsPanel.waitExpectedMessage( format("File '%s' has uploaded successfully", uploadingFileName)); projectExplorer.waitVisibleItem(format("%s/%s", PROJECT_NAME, uploadingFileName)); projectExplorer.openItemByPath(pathToUploadingFileInsideTheProject); editor.typeTextIntoEditor(TEXT_TO_INSERT); projectExplorer.waitAndSelectItem(PROJECT_NAME); openFormAndSelectUploadFile(localPathToFileToUpload); uploadFileDialogPage.clickOnUploadButton(); uploadFileDialogPage.waitOnClose(); eventsPanel.clickEventLogBtn(); eventsPanel.waitExpectedMessage( format("File '%s' has uploaded successfully", uploadingFileName)); projectExplorer.waitVisibleItem(pathToUploadingFileInsideTheProject); projectExplorer.openItemByPath(pathToUploadingFileInsideTheProject); editor.waitTextIntoEditor(TEXT_TO_INSERT); }
Source:
private void varify() { if (!letConsts.isEmpty()) { for (Node n : letConsts) { if (n.isConst()) { for (Node child : n.children()) { Node declaration = new Node(Token.VAR, child.detachFromParent()); declaration.useSourceInfoFrom(n); JSDocInfo existingInfo = n.getJSDocInfo(); if (existingInfo == null) { existingInfo = child.getJSDocInfo(); child.setJSDocInfo(null); } JSDocInfoBuilder builder = JSDocInfoBuilder.maybeCopyFrom(existingInfo); builder.recordConstancy(); JSDocInfo info = builder.build(); declaration.setJSDocInfo(info); n.getParent().addChildAfter(declaration, n); } n.detachFromParent(); } else { n.setType(Token.VAR); } } compiler.reportCodeChange(); } }

Target:
private void varify() { if (!letConsts.isEmpty()) { for (Node n : letConsts) { if (n.isConst()) { for (Node child : n.children()) { Node declaration = IR.var(child.detachFromParent()); declaration.useSourceInfoFrom(n); JSDocInfo existingInfo = n.getJSDocInfo(); if (existingInfo == null) { existingInfo = child.getJSDocInfo(); child.setJSDocInfo(null); } JSDocInfoBuilder builder = JSDocInfoBuilder.maybeCopyFrom(existingInfo); builder.recordConstancy(); JSDocInfo info = builder.build(); declaration.setJSDocInfo(info); n.getParent().addChildAfter(declaration, n); } n.detachFromParent(); } else { n.setType(Token.VAR); } } compiler.reportCodeChange(); } }
Source:
public int run() throws Exception { SitePaths sitePaths = new SitePaths(getSitePath()); File newSecureStoreFile = new File(newSecureStoreLib); if (!newSecureStoreFile.exists()) { throw new RuntimeException(String.format("File %s doesn't exists", newSecureStoreFile.getAbsolutePath())); } String newSecureStore = getNewSecureStoreClassName(newSecureStoreFile); String currentSecureStoreName = getCurrentSecureStoreClassName(sitePaths); if (currentSecureStoreName.equals(newSecureStore)) { log.error("Old and new SecureStore implementation names " + "are the same. Migration will not work"); return -1; } IoUtil.loadJARs(newSecureStoreFile); SiteLibraryLoaderUtil.loadSiteLib(sitePaths.lib_dir); log.info("Current secureStoreClass property ({}) will be replaced with {}", currentSecureStoreName, newSecureStore); Injector dbInjector = createDbInjector(SINGLE_USER); SecureStore currentStore = getSecureStore(currentSecureStoreName, dbInjector); SecureStore newStore = getSecureStore(newSecureStore, dbInjector); migrateProperties(currentStore, newStore); removeOldLib(sitePaths, currentSecureStoreName); copyNewLib(sitePaths, newSecureStoreFile); updateGerritConfig(sitePaths, newSecureStore); return 0; }

Target:
public int run() throws Exception { SitePaths sitePaths = new SitePaths(getSitePath()); File newSecureStoreFile = new File(newSecureStoreLib); if (!newSecureStoreFile.exists()) { log.error(String.format("File %s doesn't exists", newSecureStoreFile.getAbsolutePath())); return -1; } String newSecureStore = getNewSecureStoreClassName(newSecureStoreFile); String currentSecureStoreName = getCurrentSecureStoreClassName(sitePaths); if (currentSecureStoreName.equals(newSecureStore)) { log.error("Old and new SecureStore implementation names " + "are the same. Migration will not work"); return -1; } IoUtil.loadJARs(newSecureStoreFile); SiteLibraryLoaderUtil.loadSiteLib(sitePaths.lib_dir); log.info("Current secureStoreClass property ({}) will be replaced with {}", currentSecureStoreName, newSecureStore); Injector dbInjector = createDbInjector(SINGLE_USER); SecureStore currentStore = getSecureStore(currentSecureStoreName, dbInjector); SecureStore newStore = getSecureStore(newSecureStore, dbInjector); migrateProperties(currentStore, newStore); removeOldLib(sitePaths, currentSecureStoreName); copyNewLib(sitePaths, newSecureStoreFile); updateGerritConfig(sitePaths, newSecureStore); return 0; }
Source:
private FilterTypeEntity getFilterTypeEntityById(final Long filterTypeId) throws EntityRetrievalException { Query query = entityManager.createQuery( "from FilterTypeEntity where (NOT deleted = true) " + "AND (id = :filterTypeId) ", FilterTypeEntity.class); query.setParameter("filterTypeId", filterTypeId); List<FilterTypeEntity> result = query.getResultList(); if (result == null || result.size() == 0) { String msg = String.format(messageSource.getMessage(new DefaultMessageSourceResolvable("user.notFound"), LocaleContextHolder.getLocale())); throw new EntityRetrievalException(msg); } else if (result.size() > 1) { throw new EntityRetrievalException("Data error. Duplicate filter type in database."); } if (result.size() == 0) { return null; } return result.get(0); }

Target:
private FilterTypeEntity getFilterTypeEntityById(final Long filterTypeId) throws EntityRetrievalException { Query query = entityManager.createQuery( "from FilterTypeEntity where (NOT deleted = true) " + "AND (id = :filterTypeId) ", FilterTypeEntity.class); query.setParameter("filterTypeId", filterTypeId); List<FilterTypeEntity> result = query.getResultList(); if (result == null || result.size() == 0) { throw new EntityRetrievalException("Date error. Filter type not found in database."); } else if (result.size() > 1) { throw new EntityRetrievalException("Data error. Duplicate filter type in database."); } if (result.size() == 0) { return null; } return result.get(0); }
Source:
public void purgeDeletedCertificateCodeSnippets() { CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); certificateAsyncClient.purgeDeletedCertificate("deletedCertificateName") .subscriberContext(Context.of(key1, value1, key2, value2)) .doOnSuccess(response -> System.out.println("Successfully Purged certificate \n")); END: com.azure.security.keyvault.certificates.CertificateAsyncClient.purgeDeletedCertificate#string }

Target:
public void purgeDeletedCertificateCodeSnippets() { CertificateAsyncClient certificateAsyncClient = getCertificateAsyncClient(); certificateAsyncClient.purgeDeletedCertificate("deletedCertificateName") .subscriberContext(Context.of(key1, value1, key2, value2)) .doOnSuccess(response -> System.out.println("Successfully Purged certificate")); END: com.azure.security.keyvault.certificates.CertificateAsyncClient.purgeDeletedCertificate#string }
Source:
public RealmResults(BaseRealm realm, Collection collection, Class<E> clazz) { super(realm, collection, clazz); }

Target:
RealmResults(BaseRealm realm, Collection collection, Class<E> clazz) { super(realm, collection, clazz); }
Source:
public RepositoryPath moveFromTemporaryDirectory(TempRepositoryPath tempPath) throws IOException { logger.debug(String.format("Mooving [%s]", tempPath.getTarget())); RepositoryPath path = tempPath.getTempTarget(); if (!Files.exists(tempPath.getTarget())) { throw new IOException(String.format("[%s] target for [%s] don't exists!", TempRepositoryPath.class.getSimpleName(), tempPath)); } if (!Files.exists(unwrap(path).getParent())) { Files.createDirectories(unwrap(path).getParent()); } if (Files.exists(path.getTarget())) { Files.delete(path.getTarget()); } Files.move(tempPath.getTarget(), path.getTarget(), StandardCopyOption.ATOMIC_MOVE); return path; }

Target:
public RepositoryPath moveFromTemporaryDirectory(TempRepositoryPath tempPath) throws IOException { logger.debug(String.format("Moving [%s]", tempPath.getTarget())); RepositoryPath path = tempPath.getTempTarget(); if (!Files.exists(tempPath.getTarget())) { throw new IOException(String.format("[%s] target for [%s] don't exists!", TempRepositoryPath.class.getSimpleName(), tempPath)); } if (!Files.exists(unwrap(path).getParent())) { Files.createDirectories(unwrap(path).getParent()); } if (Files.exists(path.getTarget())) { Files.delete(path.getTarget()); } Files.move(tempPath.getTarget(), path.getTarget(), StandardCopyOption.ATOMIC_MOVE); return path; }