auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void testForValueOff() { final AdministrativeStatusType administrativeStatusType = AdministrativeStatusType.OFF; final AdministrativeStatusTypeDto administrativeStatusTypeDto = this.configurationMapper.map( administrativeStatusType, AdministrativeStatusTypeDto.class); assertNotNull(administrativeStatusType); assertNotNull(administrativeStatusTypeDto); assertEquals(administrativeStatusType.value(), administrativeStatusTypeDto.value()); }

Target:
public void testForValueOff() { final AdministrativeStatusType administrativeStatusType = AdministrativeStatusType.OFF; final AdministrativeStatusTypeDto administrativeStatusTypeDto = this.configurationMapper.map( administrativeStatusType, AdministrativeStatusTypeDto.class); assertNotNull(administrativeStatusTypeDto); assertEquals(administrativeStatusType.value(), administrativeStatusTypeDto.value()); }
Source:
public PMML4Result evaluate(KiePMMLModel model, PMMLContext pmmlContext, String releaseId) { if (!(model instanceof KiePMMLDroolsModel)) { throw new KiePMMLModelException("Expected a KiePMMLDroolsModel, received a " + model.getClass().getName()); } final KiePMMLDroolsModel drooledModel = (KiePMMLDroolsModel) model; final Map<String, Object> requestData = getUnwrappedParametersMap(pmmlContext.getRequestData().getMappedRequestParams()); return (PMML4Result) drooledModel.evaluate(requestData); }

Target:
public PMML4Result evaluate(KiePMMLModel model, PMMLContext pmmlContext, String releaseId) { if (!(model instanceof KiePMMLDroolsModel)) { throw new KiePMMLModelException("Expected a KiePMMLDroolsModel, received a " + model.getClass().getName()); } final KiePMMLDroolsModel droolsModel = (KiePMMLDroolsModel) model; final Map<String, Object> requestData = getUnwrappedParametersMap(pmmlContext.getRequestData().getMappedRequestParams()); return (PMML4Result) droolsModel.evaluate(requestData); }
Source:
public final I18nResolver getI18nResolver() { return i18nResolver; }

Target:
protected final I18nResolver getI18nResolver() { return i18nResolver; }
Source:
public int hashCode() { return Objects.hash(getId()); }

Target:
public int hashCode() { return Objects.hash(getName(), getPassPercentage(), getContent(), getDescription(), getProperties(), getState()); }
Source:
public Build scheduleBuild(Map<String, ?> params) { visit(""); int nb = getJson().get("nextBuildNumber").intValue(); if (parameters.isEmpty()) { clickLink("Build Now"); } else { clickLink("Build with Parameters"); for (Parameter def : parameters) { Object v = params.get(def.getName()); if (v != null) { def.fillWith(v); } } clickButton("Build"); } return build(nb); }

Target:
public Build scheduleBuild(Map<String, ?> params) { open(); int nb = getJson().get("nextBuildNumber").intValue(); if (parameters.isEmpty()) { clickLink("Build Now"); } else { clickLink("Build with Parameters"); for (Parameter def : parameters) { Object v = params.get(def.getName()); if (v != null) { def.fillWith(v); } } clickButton("Build"); } return build(nb); }
Source:
public static LocalPaxosServices createInstrumentedLocalServices( MetricsManager metricsManager, LeaderConfig config, UserAgent userAgent) { Set<String> remoteLeaderUris = Sets.newHashSet(config.leaders()); remoteLeaderUris.remove(config.localServer()); RemotePaxosServerSpec remotePaxosServerSpec = ImmutableRemotePaxosServerSpec.builder() .remoteLeaderUris(remoteLeaderUris) .remoteAcceptorUris(remoteLeaderUris) .remoteLearnerUris(remoteLeaderUris) .build(); return createInstrumentedLocalServices( metricsManager, config, remotePaxosServerSpec, () -> RemotingClientConfig.ALWAYS_USE_LEGACY, userAgent, LeadershipObserver.NO_OP); }

Target:
public static LocalPaxosServices createInstrumentedLocalServices( MetricsManager metricsManager, LeaderConfig config, UserAgent userAgent) { Set<String> remoteLeaderUris = Sets.newHashSet(config.leaders()); remoteLeaderUris.remove(config.localServer()); RemotePaxosServerSpec remotePaxosServerSpec = ImmutableRemotePaxosServerSpec.builder() .remoteLeaderUris(remoteLeaderUris) .remoteAcceptorUris(remoteLeaderUris) .remoteLearnerUris(remoteLeaderUris) .build(); return createInstrumentedLocalServices( metricsManager, config, remotePaxosServerSpec, () -> RemotingClientConfigs.ALWAYS_USE_LEGACY, userAgent, LeadershipObserver.NO_OP); }
Source:
public void testVisitForHayes() { ConfigureForDosVisitor conDos = new ConfigureForDosVisitor(); Hayes hayes = mock(Hayes.class); ((HayesVisitor)conDos).visit(hayes); assertThat(logger.getLoggingEvents()).extracting("level", "message").contains( tuple(INFO, hayes + " used with Dos configurator.")); }

Target:
public void testVisitForHayes() { ConfigureForDosVisitor conDos = new ConfigureForDosVisitor(); Hayes hayes = new Hayes(); conDos.visit(hayes); assertThat(logger.getLoggingEvents()).extracting("level", "message").contains( tuple(INFO, hayes + " used with Dos configurator.")); }
Source:
public void upgradeTo(final ChannelHandlerContext ctx, FullHttpRequest upgradeRequest) { int firstHandlerIdx = 0; try { ctx.pipeline().addAfter(ctx.name(), handlerName, connectionHandler); if (handlers != null && handlers.length > 0 && handlers[firstHandlerIdx] instanceof Http2MultiplexHandler) { ChannelHandlerContext connectionHandlerCtx = ctx.pipeline().context(connectionHandler); ctx.pipeline().addAfter(connectionHandlerCtx.name(), null, handlers[firstHandlerIdx++]); } connectionHandler.onHttpServerUpgrade(settings); } catch (Http2Exception e) { ctx.fireExceptionCaught(e); ctx.close(); return; } if (handlers != null) { final String name = ctx.pipeline().context(connectionHandler).name(); for (int i = handlers.length - 1; i >= firstHandlerIdx; i--) { ctx.pipeline().addAfter(name, null, handlers[i]); } } }

Target:
public void upgradeTo(final ChannelHandlerContext ctx, FullHttpRequest upgradeRequest) { try { ctx.pipeline().addAfter(ctx.name(), handlerName, connectionHandler); if (handlers != null) { final String name = ctx.pipeline().context(connectionHandler).name(); for (int i = handlers.length - 1; i >= 0; i--) { ctx.pipeline().addAfter(name, null, handlers[i]); } } connectionHandler.onHttpServerUpgrade(settings); } catch (Http2Exception e) { ctx.fireExceptionCaught(e); ctx.close(); } }
Source:
public boolean isSubscribed() { return conn.getStatus() == Status.CONNECTED && dispatcher.isActive(); }

Target:
public boolean isSubscribed() { return conn.getStatus() == Status.CONNECTED && dispatcher != null && dispatcher.isActive(); }
Source:
private Map<String, Object> getCommonProperties() { Map<String, Object> properties = new HashMap<>(); properties.put(KEY_EDITOR, mCurrentEditor.toString().toLowerCase(Locale.ROOT)); properties.put(KEY_CONTENT_TYPE, mContentType); properties.put(KEY_POST_TYPE, mPostType); properties.put(KEY_BLOG_TYPE, mBlogType); properties.put(KEY_SESSION_ID, mSessionId); properties.put(KEY_HAS_UNSUPPORTED_BLOCKS, mHasUnsupportedBlocks ? "1" : "0"); if (mUnsupportedBlocks != null && mUnsupportedBlocks.size() > 0) { properties.put(KEY_UNSUPPORTED_BLOCKS, mUnsupportedBlocks); } return properties; }

Target:
private Map<String, Object> getCommonProperties() { Map<String, Object> properties = new HashMap<>(); properties.put(KEY_EDITOR, mCurrentEditor.toString().toLowerCase(Locale.ROOT)); properties.put(KEY_CONTENT_TYPE, mContentType); properties.put(KEY_POST_TYPE, mPostType); properties.put(KEY_BLOG_TYPE, mBlogType); properties.put(KEY_SESSION_ID, mSessionId); properties.put(KEY_HAS_UNSUPPORTED_BLOCKS, mHasUnsupportedBlocks ? "1" : "0"); return properties; }
Source:
private MetaDataMutationResult doDropSchema(long clientTimeStamp, String schemaName, byte[] key, List<Mutation> schemaMutations, List<ImmutableBytesPtr> invalidateList) throws IOException, SQLException { PSchema schema = loadSchema(env, key, new ImmutableBytesPtr(key), clientTimeStamp, clientTimeStamp); boolean areTablesExists = false; if (schema == null) { return new MetaDataMutationResult(MutationCode.SCHEMA_NOT_FOUND, EnvironmentEdgeManager.currentTimeMillis(), null); } if (schema.getTimeStamp() < clientTimeStamp) { Region region = env.getRegion(); Scan scan = MetaDataUtil.newTableRowsScan(SchemaUtil.getKeyForSchema(null, schemaName), MIN_TABLE_TIMESTAMP, clientTimeStamp); List<Cell> results = Lists.newArrayList(); try (RegionScanner scanner = region.getScanner(scan);) { scanner.next(results); if (results.isEmpty()) { return new MetaDataMutationResult(MutationCode.SCHEMA_NOT_FOUND, EnvironmentEdgeManager.currentTimeMillis(), null); } do { Cell kv = results.get(0); if (Bytes.compareTo(kv.getRowArray(), kv.getRowOffset(), kv.getRowLength(), key, 0, key.length) != 0) { areTablesExists = true; break; } results.clear(); scanner.next(results); } while (!results.isEmpty()); } if (areTablesExists) { return new MetaDataMutationResult(MutationCode.UNALLOWED_SCHEMA_MUTATION, schema, EnvironmentEdgeManager.currentTimeMillis()); } return new MetaDataMutationResult(MutationCode.SCHEMA_ALREADY_EXISTS, schema, EnvironmentEdgeManager.currentTimeMillis()); } return new MetaDataMutationResult(MutationCode.SCHEMA_NOT_FOUND, EnvironmentEdgeManager.currentTimeMillis(), null); }

Target:
private MetaDataMutationResult doDropSchema(long clientTimeStamp, String schemaName, byte[] key, List<Mutation> schemaMutations, List<ImmutableBytesPtr> invalidateList) throws IOException, SQLException { PSchema schema = loadSchema(env, key, new ImmutableBytesPtr(key), clientTimeStamp, clientTimeStamp); boolean areTablesExists = false; if (schema == null) { return new MetaDataMutationResult(MutationCode.SCHEMA_NOT_FOUND, EnvironmentEdgeManager.currentTimeMillis(), null); } if (schema.getTimeStamp() < clientTimeStamp) { Region region = env.getRegion(); Scan scan = MetaDataUtil.newTableRowsScan(SchemaUtil.getKeyForSchema(null, schemaName), MIN_TABLE_TIMESTAMP, clientTimeStamp); List<Cell> results = Lists.newArrayList(); try (RegionScanner scanner = region.getScanner(scan);) { scanner.next(results); if (results.isEmpty()) { return new MetaDataMutationResult(MutationCode.SCHEMA_NOT_FOUND, EnvironmentEdgeManager.currentTimeMillis(), null); } do { Cell kv = results.get(0); if (Bytes.compareTo(kv.getRowArray(), kv.getRowOffset(), kv.getRowLength(), key, 0, key.length) != 0) { areTablesExists = true; break; } results.clear(); scanner.next(results); } while (!results.isEmpty()); } if (areTablesExists) { return new MetaDataMutationResult(MutationCode.TABLES_EXIST_ON_SCHEMA, schema, EnvironmentEdgeManager.currentTimeMillis()); } return new MetaDataMutationResult(MutationCode.SCHEMA_ALREADY_EXISTS, schema, EnvironmentEdgeManager.currentTimeMillis()); } return new MetaDataMutationResult(MutationCode.SCHEMA_NOT_FOUND, EnvironmentEdgeManager.currentTimeMillis(), null); }
Source:
public void endToEndSSLReplicationWithMultiNodeSinglePartitionTest() throws InterruptedException, IOException, InstantiationException { DataNodeId dataNodeId = sslCluster.getFirstDataNode(); endToEndReplicationWithMultiNodeSinglePartitionTest(sslCluster, "DC2,DC3", dataNodeId.getPort(), new Port(dataNodeId.getSSLPort(), PortType.SSL), new Port(dataNodeId.getSSLPort() + 3, PortType.SSL), new Port(dataNodeId.getSSLPort() + 6, PortType.SSL)); }

Target:
public void endToEndSSLReplicationWithMultiNodeSinglePartitionTest() throws InterruptedException, IOException, InstantiationException { cluster = new MockCluster(notificationSystem, true, "DC1,DC2,DC3"); DataNodeId dataNodeId = cluster.getClusterMap().getDataNodeIds().get(0); ArrayList<String> dataCenterList = new ArrayList<String>(Arrays.asList("DC1", "DC2", "DC3")); List<DataNodeId> dataNodes = cluster.getOneDataNodeFromEachDatacenter(dataCenterList); endToEndReplicationWithMultiNodeSinglePartitionTest("DC1", "DC2,DC3", dataNodeId.getPort(), new Port(dataNodes.get(0).getSSLPort(), PortType.SSL), new Port(dataNodes.get(1).getSSLPort(), PortType.SSL), new Port(dataNodes.get(2).getSSLPort(), PortType.SSL)); }
Source:
private long lastModified(String modelFilePath) { try { System.currentTimeMillis(); return Files.readAttributes(Paths.get(modelFilePath), BasicFileAttributes.class) .lastModifiedTime() .toMillis(); } catch (IOException e) { logger.error("Error reading file last modified time"); logger.debug("Error reading file last modified time", e); return -1; } }

Target:
private long lastModified(String modelFilePath) { try { return Files.readAttributes(Paths.get(modelFilePath), BasicFileAttributes.class) .lastModifiedTime() .toMillis(); } catch (IOException e) { logger.error("Error reading file last modified time"); logger.debug("Error reading file last modified time", e); return -1; } }
Source:
public SynchronizationResult synchronize(NewProjectHandler newProjectHandler, CancellationTokenSource tokenSource, IProgressMonitor monitor) { synchronizingBuilds.add(this); monitor = monitor != null ? monitor : new NullProgressMonitor(); SynchronizeOperation operation = new SynchronizeOperation(newProjectHandler); try { CorePlugin.operationManager().run(operation, tokenSource, monitor); return newSynchronizationResult(Status.OK_STATUS); } catch (CoreException e) { return newSynchronizationResult(e.getStatus()); } finally { synchronizingBuilds.remove(this); } }

Target:
public SynchronizationResult synchronize(NewProjectHandler newProjectHandler, CancellationTokenSource tokenSource, IProgressMonitor monitor) { monitor = monitor != null ? monitor : new NullProgressMonitor(); SynchronizeOperation operation = new SynchronizeOperation(this.gradleBuild, newProjectHandler); SynchronizeOperation runningOperation = syncOperations.putIfAbsent(this, operation); if (runningOperation != null && (newProjectHandler == NewProjectHandler.NO_OP || Objects.equals(newProjectHandler, runningOperation.newProjectHandler))) { return newSynchronizationResult(Status.OK_STATUS); } try { CorePlugin.operationManager().run(operation, tokenSource, monitor); return newSynchronizationResult(Status.OK_STATUS); } catch (CoreException e) { return newSynchronizationResult(e.getStatus()); } finally { syncOperations.remove(this); } }
Source:
private ResultQueueEntry<ReadRowsResponse> getNext() throws IOException, ScanTimeoutException { ResultQueueEntry<ReadRowsResponse> queueEntry; try { queueEntry = resultQueue.poll(readPartialRowTimeoutMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Interrupted while waiting for next result", e); } if (queueEntry == null) { throw new ScanTimeoutException("Timeout while merging responses."); } return queueEntry; }

Target:
private ResultQueueEntry<ReadRowsResponse> getNext() throws IOException { ResultQueueEntry<ReadRowsResponse> queueEntry; try { queueEntry = resultQueue.poll(readPartialRowTimeoutMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException("Interrupted while waiting for next result", e); } if (queueEntry == null) { throw new ScanTimeoutException("Timeout while merging responses."); } return queueEntry; }
Source:
public final Optional<TYPE> first() { List<TYPE> list = first(1).asList(); if(list.isEmpty()) { return Optional.empty(); } return Optional.of(list.get(0)); }

Target:
public final Optional<TYPE> first() { Iterator<TYPE> resultIterator = first(1).iterator(); return resultIterator.hasNext() ? Optional.of(resultIterator.next()) : Optional.empty(); }
Source:
public ValuedParameter[] getValuedParameters() { if (valuedParameters == null) { valuedParameters = new ValuedParameter[0]; } return valuedParameters; }

Target:
public ValuedParameter[] getValuedParameters() { createValuedParameter(controllerMethod); return valuedParameters; }
Source:
public boolean configure(StaplerRequest req, JSONObject json) throws FormException { Jenkins j = Jenkins.getInstance(); try { String num = json.getString("numExecutors"); if (!num.matches("^(\\d+)")) { throw new FormException(Messages.Hudson_Computer_IncorrectNumberOfExecutors(),"numExecutors"); } j.setNumExecutors(json.getInt("numExecutors")); if (req.hasParameter("master.mode")) j.setMode(Mode.valueOf(req.getParameter("master.mode"))); else j.setMode(Mode.NORMAL); j.setLabelString(json.optString("labelString", "")); return true; } catch (IOException e) { throw new FormException(e,"numExecutors"); } }

Target:
public boolean configure(StaplerRequest req, JSONObject json) throws FormException { Jenkins j = Jenkins.getInstance(); try { String num = json.getString("numExecutors"); if (!num.matches("\\d+")) { throw new FormException(Messages.Hudson_Computer_IncorrectNumberOfExecutors(),"numExecutors"); } j.setNumExecutors(json.getInt("numExecutors")); if (req.hasParameter("master.mode")) j.setMode(Mode.valueOf(req.getParameter("master.mode"))); else j.setMode(Mode.NORMAL); j.setLabelString(json.optString("labelString", "")); return true; } catch (IOException e) { throw new FormException(e,"numExecutors"); } }
Source:
protected List<String> getConsoleDevicesForEntity(Guid id) { return getEntity(List.class, VdcQueryType.GetConsoleDevices, new IdQueryParameters(id), null, true); }

Target:
protected List<String> getConsoleDevicesForEntity(Guid id) { return getEntity(List.class, VdcQueryType.GetConsoleDevices, new IdQueryParameters(id), "GetConsoleDevices", true); }
Source:
public RemoteDescriptorProvider(TaskRunner taskRunner, String url, String username, String password) { this.url = url; this.username = username; this.password = password; latch = new CountDownLatch(1); taskRunner.run(new Task() { @Override public void execute() throws Exception { try { downloadDescriptors(); } finally { latch.countDown(); } } }, null); }

Target:
public RemoteDescriptorProvider(TaskRunner taskRunner, String url, String username, String password) { this.url = url; this.username = username; this.password = password; data.requestLoad(); }
Source:
protected Command getCommand() { PapyrusClipboard.getInstance().resetTarget(); List<IGraphicalEditPart> selectedElements = getSelectedElements(); if (selectedElements.size() == 1) { if (!(selectedElements.get(0) instanceof GraphicalEditPart)) { return UnexecutableCommand.INSTANCE; } GraphicalEditPart targetOwnerEditPart = (GraphicalEditPart) selectedElements.get(0); org.eclipse.gef.commands.CompoundCommand compoundCommand = new org.eclipse.gef.commands.CompoundCommand("Paste all elements"); List<IStrategy> allStrategies = PasteStrategyManager.getInstance().getAllActiveStrategies(); for (IStrategy iStrategy : allStrategies) { IPasteStrategy iPasteStrategy = (IPasteStrategy) iStrategy; Command graphicalCommand = iPasteStrategy.getGraphicalCommand(getEditingDomain(), targetOwnerEditPart, PapyrusClipboard.getInstance()); if (graphicalCommand != null) { compoundCommand.add(graphicalCommand); } } return compoundCommand; } return UnexecutableCommand.INSTANCE; }

Target:
protected Command getCommand() { PapyrusClipboard.getInstance().resetTarget(); List<IGraphicalEditPart> selectedElements = getSelectedElements(); if (selectedElements.size() == 1 && (selectedElements.get(0) instanceof GraphicalEditPart)) { GraphicalEditPart targetOwnerEditPart = (GraphicalEditPart) selectedElements.get(0); org.eclipse.gef.commands.CompoundCommand compoundCommand = new org.eclipse.gef.commands.CompoundCommand("Paste all elements"); List<IStrategy> allStrategies = PasteStrategyManager.getInstance().getAllActiveStrategies(); for (IStrategy iStrategy : allStrategies) { IPasteStrategy iPasteStrategy = (IPasteStrategy) iStrategy; Command graphicalCommand = iPasteStrategy.getGraphicalCommand(getEditingDomain(), targetOwnerEditPart, PapyrusClipboard.getInstance()); if (graphicalCommand != null) { compoundCommand.add(graphicalCommand); } } return compoundCommand; } return UnexecutableCommand.INSTANCE; }
Source:
abstract protected ResultSet getColumns() throws SQLException; public Map<String, DbParameterAccessor> getParams() throws SQLException { Map<String, DbParameterAccessor> allParams = new HashMap<String, DbParameterAccessor>(); try (ResultSet rs = getColumns()) { while (rs.next()) { String paramName = getColumnName(rs); allParams.put(NameNormaliser.normaliseName(paramName), createColumnAccessor(paramName, rs)); } } return allParams; }

Target:
abstract protected ResultSet getColumns() throws SQLException; public Map<String, DbParameterAccessor> getParams() throws SQLException { Map<String, DbParameterAccessor> allParams = new HashMap<>(); try (ResultSet rs = getColumns()) { while (rs.next()) { DbParameterAccessor accessor = createColumnAccessor(rs); allParams.put(normaliseName(accessor.getName()), accessor); } } return allParams; }
Source:
private void loadData() { MyShowsClient client = MyShowsClientImpl.getInstance(); client.ratingShows() .compose(bindToLifecycle()) .subscribe(shows -> { ratingShows = shows; if (userShows != null) { setAdapter(); } } ); client.profileShows() .compose(bindToLifecycle()) .map(shows -> { Map<Integer, UserShow> userShows = new HashMap<>(); for (UserShow show : shows) { userShows.put(show.getShowId(), show); } return userShows; }) .subscribe(shows -> { userShows = shows; if (ratingShows != null) { setAdapter(); } }); }

Target:
private void loadData() { MyShowsClient client = MyShowsClientImpl.getInstance(); client.ratingShows() .compose(bindToLifecycle()) .subscribe(shows -> { ratingShows = shows; trySetAdapter(); } ); client.profileShows() .compose(bindToLifecycle()) .map(shows -> { Map<Integer, UserShow> userShows = new HashMap<>(); for (UserShow show : shows) { userShows.put(show.getShowId(), show); } return userShows; }) .subscribe(shows -> { userShows = shows; trySetAdapter(); }); }
Source:
public TmfModelResponse<ITmfXyModel> fetchXY(TimeQueryFilter filter, @Nullable IProgressMonitor monitor) { boolean allCommon = true; List<P> providers = getProviders(); for (P dataProvider : providers) { if (!(dataProvider instanceof ITmfCommonXAxisModel)) { allCommon = false; break; } } if (allCommon) { return getCommonXResponse(filter, monitor, providers); } return getXyResponse(filter, monitor, providers); }

Target:
public TmfModelResponse<ITmfXyModel> fetchXY(TimeQueryFilter filter, @Nullable IProgressMonitor monitor) { List<P> providers = getProviders(); boolean allCommon = Iterables.all(providers, p -> p instanceof ITmfCommonXAxisModel); if (allCommon) { return getCommonXResponse(filter, monitor, providers); } return getXyResponse(filter, monitor, providers); }
Source:
public void testDelete() throws StripeException { Coupon resource = Coupon.retrieve(RESOURCE_ID); resource.delete(); verifyRequest( APIResource.RequestMethod.DELETE, String.format("/v1/coupons/%s", resource.getId()) ); }

Target:
public void testDelete() throws StripeException { final Coupon coupon = getCouponFixture(); final DeletedCoupon deletedCoupon = coupon.delete(); assertNotNull(deletedCoupon); verifyRequest( APIResource.RequestMethod.DELETE, String.format("/v1/coupons/%s", coupon.getId()) ); }
Source:
private LogicalVariable translateObjectConstructor(TranslationContext tCtx, ObjectConstructor obj) throws SystemException { List<ILogicalExpression> content = new ArrayList<ILogicalExpression>(); for (ASTNode aVal : obj.getContent()) { if (aVal instanceof PairConstructor) { ILogicalExpression ke = string(data(vre(translateExpression(((PairConstructor) aVal).getKey(), tCtx)))); content.add(ke); ILogicalExpression ve = vre(translateExpression(((PairConstructor) aVal).getValue(), tCtx)); content.add(ve); ILogicalExpression qmce = ce(SequenceType.create(BuiltinTypeRegistry.XS_BOOLEAN, Quantifier.QUANT_ONE), ((PairConstructor) aVal).isQuestionMarkColon()); content.add(qmce); } else { ILogicalExpression aExpr = aVal == null ? sfce(BuiltinOperators.CONCATENATE) : vre(translateExpression(aVal, tCtx)); return createAssignment(sfce(BuiltinOperators.SIMPLE_OBJECT_UNION, aExpr), tCtx); } } return createAssignment( sfce(BuiltinOperators.OBJECT_CONSTRUCTOR, content.toArray(new ILogicalExpression[content.size()])), tCtx); }

Target:
private LogicalVariable translateObjectConstructor(TranslationContext tCtx, ObjectConstructor obj) throws SystemException { List<ILogicalExpression> content = new ArrayList<ILogicalExpression>(); PairConstructor pc; for (ASTNode aVal : obj.getContent()) { if (aVal.getTag()==ASTTag.PAIR_CONSTRUCTOR) { pc=(PairConstructor) aVal; ILogicalExpression ke = string(data(vre(translateExpression(pc.getKey(), tCtx)))); content.add(ke); ILogicalExpression ve = vre(translateExpression(pc.getValue(), tCtx)); content.add(ve); ILogicalExpression qmce = ce(SequenceType.create(BuiltinTypeRegistry.XS_BOOLEAN, Quantifier.QUANT_ONE), pc.isQuestionMarkColon()); content.add(qmce); } else { ILogicalExpression aExpr = aVal == null ? sfce(BuiltinOperators.CONCATENATE) : vre(translateExpression(aVal, tCtx)); return createAssignment(sfce(BuiltinOperators.SIMPLE_OBJECT_UNION, aExpr), tCtx); } } return createAssignment( sfce(BuiltinOperators.OBJECT_CONSTRUCTOR, content.toArray(new ILogicalExpression[content.size()])), tCtx); }
Source:
public String createAgentRequestBody(String autoRegisterKey, String environment, Map<String, String> configuration, JobIdentifier jobIdentifier) { final JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("auto_register_key", autoRegisterKey); jsonObject.add("properties", mapToJsonObject(configuration)); jsonObject.addProperty("environment", environment); return jsonObject.toString(); }

Target:
String createAgentRequestBody(String autoRegisterKey, String environment, Map<String, String> configuration, JobIdentifier jobIdentifier) { final JsonObject jsonObject = new JsonObject(); jsonObject.addProperty("auto_register_key", autoRegisterKey); jsonObject.add("properties", mapToJsonObject(configuration)); jsonObject.addProperty("environment", environment); return jsonObject.toString(); }
Source:
public void shouldMapNonEmptyList() { final List<Integer> list = Collections.unmodifiableList(Arrays.asList(1, 3, 5, 7)); final List<Integer> actual = ListOps.map(list, x -> x + 1); final List<Integer> expected = Arrays.asList(2, 4, 6, 8); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(expected, actual); }

Target:
public void shouldMapNonEmptyList() { final List<Integer> list = Collections.unmodifiableList(Arrays.asList(1, 3, 5, 7)); final List<Integer> actual = ListOps.map(list, x -> x + 1); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(Arrays.asList(2, 4, 6, 8), actual); }
Source:
public void actionPerformed(ActionEvent e) { ProxyConnection.ProxyType proxyType; if (schemaComboBox.getSelectedIndex() == 0) { proxyType = ProxyConnection.ProxyType.NO_PROXY; } else if (schemaComboBox.getSelectedIndex() == 1) { proxyType = ProxyConnection.ProxyType.HTTP; } else { proxyType = ProxyConnection.ProxyType.HTTPS; } try { BriefcasePreferences.setBriefcaseProxyProperty(new ProxyConnection(txtHost.getText(), Integer.parseInt(txtPort.getText()), proxyType)); txtHost.setEnabled(false); txtPort.setEnabled(false); } catch (NumberFormatException e1) { JOptionPane.showMessageDialog(new JFrame(), MessageStrings.PORT_ERROR_MESSAGE, "Dialog", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } }

Target:
public void actionPerformed(ActionEvent e) { ProxyConnection.ProxyType proxyType; if (schemaComboBox.getSelectedIndex() == 0) { BriefcasePreferences.setBriefcaseProxyProperty(null); txtHost.setEnabled(false); txtPort.setEnabled(false); return; } if (schemaComboBox.getSelectedIndex() == 1) { proxyType = ProxyConnection.ProxyType.HTTP; } else { proxyType = ProxyConnection.ProxyType.HTTPS; } try { BriefcasePreferences.setBriefcaseProxyProperty(new ProxyConnection(txtHost.getText(), Integer.parseInt(txtPort.getText()), proxyType)); txtHost.setEnabled(false); txtPort.setEnabled(false); } catch (NumberFormatException e1) { JOptionPane.showMessageDialog(new JFrame(), MessageStrings.PORT_ERROR_MESSAGE, "Dialog", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } }
Source:
public Set<GAV> getProjectGAVs() { return Collections.unmodifiableSet(new LinkedHashSet<>(gavs)); }

Target:
public synchronized Set<GAV> getProjectGAVs() { return Collections.unmodifiableSet(new LinkedHashSet<>(gavs)); }
Source:
public AsyncTask submit(Runnable task, String displayName, DataService dataService, long requestId) { synchronized(mutex) { String taskId = Long.toString(++counter); Fuseki.serverLog.info(format("Task : %s : %s",taskId, displayName)); Callable<Object> c = ()->{ try { task.run(); } catch (Throwable th) { Fuseki.serverLog.error(format("Exception in task %s execution", taskId), th); } return null; }; AsyncTask asyncTask = new AsyncTask(c, this, taskId, displayName, dataService, requestId); try { executor.submit(asyncTask); runningTasks.put(taskId, asyncTask); return asyncTask; } catch (RejectedExecutionException ex) { ServletOps.errorBadRequest("Async task request rejected"); return null; } } }

Target:
public AsyncTask submit(Runnable task, String displayName, DataService dataService, long requestId) { synchronized(mutex) { String taskId = Long.toString(++counter); Fuseki.serverLog.info(format("Task : %s : %s",taskId, displayName)); Callable<Object> c = ()->{ try { task.run(); } catch (Throwable th) { Fuseki.serverLog.error(format("Exception in task %s execution", taskId), th); } return null; }; AsyncTask asyncTask = new AsyncTask(c, this, taskId, displayName, dataService, requestId); try { executor.submit(asyncTask); runningTasks.put(taskId, asyncTask); return asyncTask; } catch (RejectedExecutionException ex) { ServletOps.errorBadRequest("Async task request rejected - exceeds the limit of "+nMaxThreads+" tasks"); return null; } } }
Source:
@Override public URL getDiffLink(Path path) throws IOException { if (path.getEditType() != EditType.EDIT) { return null; } int r = path.getLogEntry().getRevision(); String value = String.format("%s/commit/r%d/head%s", url, r, path.getValue()); LOGGER.fine("DiffLink URL: " + value); return new URL(value); }

Target:
public URL getDiffLink(Path path) throws IOException { if (path.getEditType() != EditType.EDIT) { return null; } int r = path.getLogEntry().getRevision(); String value = String.format("%s/commit/r%d/head%s", url, r, path.getValue()); if (LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("DiffLink URL: " + value); } return new URL(value); }
Source:
private Object transformValue(final Object field) { if (field instanceof GenericData.Array) { return Lists.transform((List<?>) field, String::valueOf); } if (field instanceof ByteBuffer) { if (binaryAsString) { return StringUtils.fromUtf8(((ByteBuffer) field).array()); } else { return ((ByteBuffer) field).array(); } } if (field instanceof Utf8) { return field.toString(); } if (field instanceof List) { return ((List<?>) field).stream().filter(Objects::nonNull).collect(Collectors.toList()); } return field; }

Target:
private Object transformValue(final Object field) { if (field instanceof ByteBuffer) { if (binaryAsString) { return StringUtils.fromUtf8(((ByteBuffer) field).array()); } else { return ((ByteBuffer) field).array(); } } else if (field instanceof Utf8) { return field.toString(); } else if (field instanceof List) { return ((List<?>) field).stream().filter(Objects::nonNull).collect(Collectors.toList()); } return field; }
Source:
public void validate_shouldPassValidationForEqualObsPersonValueWithEncounterPatient() { EncounterService es = Context.getEncounterService(); PersonService ps = Context.getPersonService(); Obs obs = new Obs(); obs.setPerson(ps.getPerson(2)); obs.setEncounter(es.getEncounter(2)); Errors errors = new BindException(obs, "obs"); new ObsValidator().validate(obs, errors); assertFalse(errors.hasFieldErrors("person")); }

Target:
public void validate_shouldPassValidationForEqualObsPersonValueWithEncounterPatient() { EncounterService es = Context.getEncounterService(); PersonService ps = Context.getPersonService(); Obs obs = new Obs(); obs.setPerson(ps.getPerson(2)); obs.setEncounter(es.getEncounter( 3 )); obs.getEncounter().setPatient(new Patient( 3 ) ); assertFalse( Objects.equals(obs.getPerson(),obs.getEncounter().getPatient()) ); Errors errors = new BindException(obs, "obs"); new ObsValidator().validate(obs, errors); assertTrue(errors.hasFieldErrors("person")); }
Source:
public SerializableVoid runTask(NoopPlanConfig config, SerializableVoid args, RunTaskContext runTaskContext) throws Exception { throw new IllegalStateException("Should never get here."); }

Target:
public SerializableVoid runTask(NoopPlanConfig config, SerializableVoid args, RunTaskContext runTaskContext) throws Exception { throw new IllegalStateException("NoopPlanDefinition should never run a task"); }
Source:
public void setCookieGeo(String countryCode) { String cookieName = "Geo"; try { JSONObject geo = new JSONObject(); geo.put("country", countryCode); String value = geo.toString(); setCookie(cookieName, value); } catch (JSONException ex) { PageObjectLogging.log("setCookieGeo", "Cannot set cookie ('" + cookieName + "')", true); } }

Target:
public void setCookieGeo(String countryCode) { String cookieName = "Geo"; try { JSONObject geo = new JSONObject(); geo.put("country", countryCode); setCookie(cookieName, geo.toString()); } catch (JSONException ex) { PageObjectLogging.log("setCookieGeo", "Cannot set cookie ('" + cookieName + "')", true); } }
Source:
public void enterBlurryWord() { String word = getWordFromCaptcha(); blurryWordField.sendKeys(word); PageObjectLogging.log("enterBlurryWord ", "Blurry word field populated", true, driver); }

Target:
public void enterBlurryWord() { String word = getWordFromCaptcha(); blurryWordField.sendKeys(word); PageObjectLogging.log("enterBlurryWord ", "Blurry word field populated", true); }
Source:
public Set<? extends NodeMetadata> listNodesByIds(Iterable<String> ids) { Multimap<String, String> idsByHandles = index(ids, splitHandle(1)); Multimap<String, String> idsByRegions = transformValues(idsByHandles, splitHandle(0)); Multimap<String, String> idsByConfiguredRegions = filterKeys(idsByRegions, in(regions.get())); Iterable<? extends RunningInstance> instances; if (idsByConfiguredRegions.isEmpty()) { return ImmutableSet.of(); } else { instances = pollRunningInstancesByRegionsAndIds(idsByConfiguredRegions); } Iterable<? extends NodeMetadata> nodes = transform(filter(instances, notNull()), runningInstanceToNodeMetadata); return ImmutableSet.copyOf(nodes); }

Target:
public Set<? extends NodeMetadata> listNodesByIds(Iterable<String> ids) { Multimap<String, String> idsByHandles = index(ids, splitHandle(1)); Multimap<String, String> idsByRegions = transformValues(idsByHandles, splitHandle(0)); Multimap<String, String> idsByConfiguredRegions = filterKeys(idsByRegions, in(regions.get())); if (idsByConfiguredRegions.isEmpty()) { return ImmutableSet.of(); } Iterable<? extends RunningInstance> instances = pollRunningInstancesByRegionsAndIds(idsByConfiguredRegions); Iterable<? extends NodeMetadata> nodes = transform(filter(instances, notNull()), runningInstanceToNodeMetadata); return ImmutableSet.copyOf(nodes); }
Source:
public TriggeredBuildSelector(boolean fallbackToLastSuccessful, UpstreamFilterStrategy upstreamFilterStrategy, boolean allowUpstreamDependencies) { this.fallbackToLastSuccessful = fallbackToLastSuccessful ? Boolean.TRUE : null; this.upstreamFilterStrategy = upstreamFilterStrategy; this.allowUpstreamDependencies = allowUpstreamDependencies ? Boolean.TRUE : null; }

Target:
public TriggeredBuildSelector(boolean fallbackToLastSuccessful, UpstreamFilterStrategy upstreamFilterStrategy, boolean allowUpstreamDependencies) { this.fallbackToLastSuccessful = fallbackToLastSuccessful ? Boolean.TRUE : null; this.upstreamFilterStrategy = upstreamFilterStrategy; this.allowUpstreamDependencies = allowUpstreamDependencies; }
Source:
public ChromeCommandExecutor(URL serviceUrl) { super(chromeCommandsNameToUrl, serviceUrl); this.service = null; }

Target:
public ChromeCommandExecutor(URL serviceUrl) { super(CHROME_COMMANDS_NAME_TO_URL, serviceUrl); this.service = null; }
Source:
public void run() { SurfaceHolder holder = getHolder(); Canvas canvas = null; if (Build.VERSION.SDK_INT >= 18) { try { Thread.sleep(20); } catch (Exception e) { } } synchronized (holder) { try { canvas = holder.lockCanvas(); if (canvas != null && mSurfaceCanBeUsed == true) { doDraw(canvas); } } finally { if (canvas != null) { holder.unlockCanvasAndPost(canvas); } } } }

Target:
public void run() { SurfaceHolder holder = getHolder(); Canvas canvas = null; if (Build.VERSION.SDK_INT >= 18) { try { Thread.sleep(20); } catch (InterruptedException e) { Log.w(PaintroidApplication.TAG, "DrawingSurface: sleeping thread was interrupted"); } } synchronized (holder) { try { canvas = holder.lockCanvas(); if (canvas != null && mSurfaceCanBeUsed == true) { doDraw(canvas); } } finally { if (canvas != null) { holder.unlockCanvasAndPost(canvas); } } } }
Source:
private static ConnectorTableMetadata getTableMetadata(String schemaName, TpchTable<?> tpchTable, ColumnNaming columnNaming) { ImmutableList.Builder<ColumnMetadata> columns = ImmutableList.builder(); for (TpchColumn<? extends TpchEntity> column : tpchTable.getColumns()) { columns.add(new ColumnMetadata(columnNaming.getName(column), getPrestoType(column), null, null, false, false, emptyMap())); } columns.add(new ColumnMetadata(ROW_NUMBER_COLUMN_NAME, BIGINT, null, true)); SchemaTableName tableName = new SchemaTableName(schemaName, tpchTable.getTableName()); return new ConnectorTableMetadata(tableName, columns.build()); }

Target:
private static ConnectorTableMetadata getTableMetadata(String schemaName, TpchTable<?> tpchTable, ColumnNaming columnNaming) { ImmutableList.Builder<ColumnMetadata> columns = ImmutableList.builder(); for (TpchColumn<? extends TpchEntity> column : tpchTable.getColumns()) { columns.add(new ColumnMetadata(columnNaming.getName(column), getPrestoType(column), false, null, null, false, emptyMap())); } columns.add(new ColumnMetadata(ROW_NUMBER_COLUMN_NAME, BIGINT, null, true)); SchemaTableName tableName = new SchemaTableName(schemaName, tpchTable.getTableName()); return new ConnectorTableMetadata(tableName, columns.build()); }
Source:
public void handleConfigureDefinableLoadProfileResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleConfigureDefinableLoadProfileResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error("Configure Definable Load Profile Response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } this.webServiceResponseMessageSender.send(ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(), deviceMessageMetadata.getMessageType()); }

Target:
public void handleConfigureDefinableLoadProfileResponse(final DeviceMessageMetadata deviceMessageMetadata, final ResponseMessageResultType deviceResult, final OsgpException exception) { LOGGER.info("handleConfigureDefinableLoadProfileResponse for MessageType: {}", deviceMessageMetadata.getMessageType()); ResponseMessageResultType result = deviceResult; if (exception != null) { LOGGER.error("Configure Definable Load Profile Response not ok. Unexpected Exception", exception); result = ResponseMessageResultType.NOT_OK; } ResponseMessage responseMessage = ResponseMessage.newResponseMessageBuilder() .withCorrelationUid(deviceMessageMetadata.getCorrelationUid()) .withOrganisationIdentification(deviceMessageMetadata.getOrganisationIdentification()) .withDeviceIdentification(deviceMessageMetadata.getDeviceIdentification()).withResult(result) .withOsgpException(exception).withMessagePriority(deviceMessageMetadata.getMessagePriority()).build(); this.webServiceResponseMessageSender.send(responseMessage, deviceMessageMetadata.getMessageType()); }
Source:
protected boolean canAuthenticate(final WebContext context) { val grantType = context.getRequestParameter(OAuth20Constants.GRANT_TYPE); if (grantType.isPresent() && OAuth20Utils.isGrantType(grantType.get(), OAuth20GrantTypes.PASSWORD)) { LOGGER.debug("Skipping Client credential authentication to use password authentication"); return false; } if (grantType.isPresent() && OAuth20Utils.isGrantType(grantType.get(), OAuth20GrantTypes.REFRESH_TOKEN) && context.getRequestParameter(OAuth20Constants.CLIENT_ID).isPresent() && !context.getRequestParameter(OAuth20Constants.CLIENT_SECRET).isPresent()) { LOGGER.debug("Skipping Client credential authentication to use refresh_token authentication"); return false; } val code = context.getRequestParameter(OAuth20Constants.CODE); if (code.isPresent()) { LOGGER.debug("Checking if the OAuth code issued contains code challenge"); val token = this.ticketRegistry.getTicket(code.get(), OAuth20Code.class); if (token != null && StringUtils.isNotEmpty(token.getCodeChallenge())) { LOGGER.debug("The OAuth code issued contains code challenge which requires PKCE Authentication", code.get()); return false; } } return true; }

Target:
protected boolean canAuthenticate(final WebContext context) { val grantType = context.getRequestParameter(OAuth20Constants.GRANT_TYPE); if (grantType.isPresent() && OAuth20Utils.isGrantType(grantType.get(), OAuth20GrantTypes.PASSWORD)) { LOGGER.debug("Skipping Client credential authentication to use password authentication"); return false; } if (grantType.isPresent() && OAuth20Utils.isGrantType(grantType.get(), OAuth20GrantTypes.REFRESH_TOKEN) && context.getRequestParameter(OAuth20Constants.CLIENT_ID).isPresent() && !context.getRequestParameter(OAuth20Constants.CLIENT_SECRET).isPresent()) { LOGGER.debug("Skipping client credential authentication to use refresh token authentication"); return false; } val code = context.getRequestParameter(OAuth20Constants.CODE); if (code.isPresent()) { LOGGER.debug("Checking if the OAuth code issued contains code challenge"); val token = this.ticketRegistry.getTicket(code.get(), OAuth20Code.class); if (token != null && StringUtils.isNotEmpty(token.getCodeChallenge())) { LOGGER.debug("The OAuth code issued contains code challenge which requires PKCE Authentication", code.get()); return false; } } return true; }
Source:
private void registerWithExistingTarget(DropTarget target) { Transfer[] transfers = target.getTransfer(); boolean exists = false; if (transfers != null) { for (Transfer transfer : transfers) { if (transfer instanceof URLTransfer) { exists = true; break; } } if (!exists) { Transfer[] newTransfers = new Transfer[transfers.length + 1]; System.arraycopy(transfers, 0, newTransfers, 0, transfers.length); newTransfers[transfers.length] = URLTransfer.getInstance(); target.setTransfer(newTransfers); } } }

Target:
private void registerWithExistingTarget(DropTarget target) { Transfer[] transfers = target.getTransfer(); if (transfers != null) { for (Transfer transfer : transfers) { if (transfer instanceof URLTransfer) { return; } } Transfer[] newTransfers = new Transfer[transfers.length + 1]; System.arraycopy(transfers, 0, newTransfers, 0, transfers.length); newTransfers[transfers.length] = URLTransfer.getInstance(); target.setTransfer(newTransfers); } }
Source:
public GoApiResponse process(GoPluginDescriptor pluginDescriptor, GoApiRequest goPluginApiRequest) { try { if (goPluginApiRequest.api().equals(GET_PLUGIN_SETTINGS)) { GoPluginExtension extension = extensionFor(pluginDescriptor.id()); PluginSettings pluginSettings = pluginSettingsFor(pluginDescriptor.id()); DefaultGoApiResponse response = new DefaultGoApiResponse(200); response.setResponseBody(extension.pluginSettingsJSON(pluginDescriptor.id(), pluginSettings.getSettingsAsKeyValuePair())); return response; } } catch (Exception e) { LOGGER.error(format("Error processing PluginSettings request from plugin: %s.", pluginDescriptor.id()), e); } return new DefaultGoApiResponse(400); }

Target:
public GoApiResponse process(GoPluginDescriptor pluginDescriptor, GoApiRequest goPluginApiRequest) { try { GoPluginExtension extension = extensionFor(pluginDescriptor.id()); PluginSettings pluginSettings = pluginSettingsFor(pluginDescriptor.id()); DefaultGoApiResponse response = new DefaultGoApiResponse(200); response.setResponseBody(extension.pluginSettingsJSON(pluginDescriptor.id(), pluginSettings.getSettingsAsKeyValuePair())); return response; } catch (Exception e) { LOGGER.error(format("Error processing PluginSettings request from plugin: %s.", pluginDescriptor.id()), e); DefaultGoApiResponse errorResponse = new DefaultGoApiResponse(400); errorResponse.setResponseBody(format("Error while processing get PluginSettings request - %s", e.getMessage())); return errorResponse; } }
Source:
public void verifyCanChangeIcon() throws IOException, InterruptedException { topologyUIPage.selectTopologyProvider(() -> LABEL); topologyUIPage.findVertex("North Region").contextMenu().click("Navigate To", "Markets (North Region)"); String label = "North 1"; topologyUIPage.findVertex(label).select(); topologyUIPage.findVertex(label).contextMenu().click("Change Icon"); String newIconName = "microwave_backhaul_1"; findElementByXpath(" assertEquals(newIconName, topologyUIPage.findVertex(label).getIconName()); }

Target:
public void verifyCanChangeIcon() throws IOException, InterruptedException { topologyUIPage.selectTopologyProvider(() -> LABEL); waitFor(1); topologyUIPage.findVertex("North Region").contextMenu().click("Navigate To", "Markets (North Region)"); String label = "North 1"; String oldIconName = topologyUIPage.findVertex(label).getIconName(); String newIconName = "microwave_backhaul_1"; if(newIconName.equals(oldIconName)){ newIconName = "IP_service"; } topologyUIPage.findVertex(label).changeIcon(newIconName); topologyUIPage.refreshNow(); assertEquals(newIconName, topologyUIPage.findVertex(label).getIconName()); }
Source:
public <T> ParamConverter<T> getConverter(final Class<T> rawType, final Type genericType, final Annotation[] annotations) { final List<ClassTypePair> ctps = ReflectionHelper.getTypeArgumentAndClass(genericType); final ClassTypePair ctp = (ctps.size() == 1) ? ctps.get(0) : null; if (ctp == null || ctp.rawClass() == String.class) { return new ParamConverter<T>() { @Override public T fromString(final String value) { return rawType.cast(Optional.fromNullable(value)); } @Override public String toString(final T value) throws IllegalArgumentException { return value.toString(); } }; } final Set<ParamConverterProvider> converterProviders = Providers.getProviders(locator, ParamConverterProvider.class); for (ParamConverterProvider provider : converterProviders) { @SuppressWarnings("unchecked") final ParamConverter<?> converter = provider.getConverter(ctp.rawClass(), ctp.type(), annotations); if (converter != null) { return new ParamConverter<T>() { @Override public T fromString(final String value) { return rawType.cast(Optional.fromNullable(value) .transform(new Function<String, Object>() { @Override public Object apply(final String s) { return converter.fromString(value); } })); } @Override public String toString(final T value) throws IllegalArgumentException { return value.toString(); } }; } } return null; }

Target:
public <T> ParamConverter<T> getConverter(final Class<T> rawType, final Type genericType, final Annotation[] annotations) { if (Optional.class.equals(rawType)) { final List<ClassTypePair> ctps = ReflectionHelper.getTypeArgumentAndClass(genericType); final ClassTypePair ctp = (ctps.size() == 1) ? ctps.get(0) : null; if (ctp == null || ctp.rawClass() == String.class) { return new ParamConverter<T>() { @Override public T fromString(final String value) { return rawType.cast(Optional.fromNullable(value)); } @Override public String toString(final T value) throws IllegalArgumentException { return value.toString(); } }; } final Set<ParamConverterProvider> converterProviders = Providers.getProviders(locator, ParamConverterProvider.class); for (ParamConverterProvider provider : converterProviders) { final ParamConverter<?> converter = provider.getConverter(ctp.rawClass(), ctp.type(), annotations); if (converter != null) { return new ParamConverter<T>() { @Override public T fromString(final String value) { return rawType.cast(Optional.fromNullable(value) .transform(new Function<String, Object>() { @Override public Object apply(final String s) { return converter.fromString(value); } })); } @Override public String toString(final T value) throws IllegalArgumentException { return value.toString(); } }; } } } return null; }
Source:
public void findAll() { Iterator<Product> iterator = repo.findAll().iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } }

Target:
public void findAll() { Iterator<Product> iterator = repo.findAll().iterator(); printResult(iterator); }