auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void handlePost(RestRequestInfo restRequestInfo) throws RestServiceException { if (restRequestInfo.isFirstPart()) { adminMetrics.postOperationRate.mark(); } logger.debug("While trying to perform POST: Unsupported operation - POST"); adminMetrics.unsupportedPostOperation.inc(); throw new RestServiceException("Unsupported operation for Admin service - POST", RestServiceErrorCode.UnsupportedOperation); }

Target:
public void handlePost(RestRequestInfo restRequestInfo) throws RestServiceException { if (restRequestInfo.isFirstPart()) { adminMetrics.postOperationRate.mark(); } adminMetrics.unsupportedPostOperationError.inc(); throw new RestServiceException("Unsupported operation for Admin service - POST", RestServiceErrorCode.UnsupportedOperation); }
Source:
public synchronized void saveDiskQuotaConfig(DiskQuotaConfig config, JDBCConfiguration jdbcConfig) throws ConfigurationException, IOException, InterruptedException { Resource configFile = configDir.get("geowebcache-diskquota-jdbc.xml"); if ("JDBC".equals(config.getQuotaStore())) { JDBCConfiguration encrypted = passwordHelper.encryptPassword(jdbcConfig); OutputStream os = configFile.out(); try { JDBCConfiguration.store(encrypted, os); } finally { os.close(); } } else { if (Resources.exists(configFile) && !configFile.delete()) { LOGGER.log(Level.SEVERE, "Failed to delete " + configFile + ", this might cause misbehavior on GeoServer restart"); } } }

Target:
public synchronized void saveDiskQuotaConfig(DiskQuotaConfig config, JDBCConfiguration jdbcConfig) throws ConfigurationException, IOException, InterruptedException { Resource configFile = configDir.get("geowebcache-diskquota-jdbc.xml"); if ("JDBC".equals(config.getQuotaStore())) { JDBCConfiguration encrypted = passwordHelper.encryptPassword(jdbcConfig); try (OutputStream os = configFile.out()) { JDBCConfiguration.store(encrypted, os); } } else { if (Resources.exists(configFile) && !configFile.delete()) { LOGGER.log(Level.SEVERE, "Failed to delete " + configFile + ", this might cause misbehavior on GeoServer restart"); } } }
Source:
public void testGetLocalPathForWriteForLessSpace() throws Exception { String dir0 = buildBufferDir(ROOT, 0); String dir1 = buildBufferDir(ROOT, 1); conf.set(CONTEXT, dir0 + "," + dir1); LambdaTestUtils.intercept(DiskErrorException.class, "as the max capacity" + " in any directory is", "Expect a DiskErrorException.", () -> dirAllocator.getLocalPathForWrite("p1/x", Long.MAX_VALUE-1, conf)); }

Target:
public void testGetLocalPathForWriteForLessSpace() throws Exception { String dir0 = buildBufferDir(ROOT, 0); String dir1 = buildBufferDir(ROOT, 1); conf.set(CONTEXT, dir0 + "," + dir1); LambdaTestUtils.intercept(DiskErrorException.class, "as the max capacity in any directory is", "Expect a DiskErrorException.", () -> dirAllocator.getLocalPathForWrite("p1/x", Long.MAX_VALUE-1, conf)); }
Source:
public Result<SearchResultValue> apply(Result<SearchResultValue> arg1, Result<SearchResultValue> arg2) { if (arg1 == null) { return arg2; } if (arg2 == null) { return arg1; } final int limit = gran instanceof AllGranularity ? this.limit : -1; SearchResultValue arg1Vals = arg1.getValue(); SearchResultValue arg2Vals = arg2.getValue(); Iterable<SearchHit> merged = Iterables.mergeSorted( Arrays.asList(arg1Vals, arg2Vals), searchSortSpec.getComparator() ); List<SearchHit> results = Lists.newArrayList(); SearchHit prev = null; for (SearchHit searchHit : merged) { if (prev == null) { prev = searchHit; continue; } if (prev.equals(searchHit)) { if (prev.getCount() != null) { prev = new SearchHit( prev.getDimension(), prev.getValue(), prev.getCount() + searchHit.getCount() ); } } else { results.add(prev); prev = searchHit; if (limit > 0 && results.size() >= limit) { break; } } } if (prev != null && (limit < 0 || results.size() < limit)) { results.add(prev); } final DateTime timestamp = gran instanceof AllGranularity ? arg1.getTimestamp() : gran.toDateTime(gran.truncate(arg1.getTimestamp().getMillis())); return new Result<SearchResultValue>(timestamp, new SearchResultValue(results)); }

Target:
public Result<SearchResultValue> apply(Result<SearchResultValue> arg1, Result<SearchResultValue> arg2) { if (arg1 == null) { return arg2; } if (arg2 == null) { return arg1; } final int limit = gran instanceof AllGranularity ? this.limit : -1; SearchResultValue arg1Vals = arg1.getValue(); SearchResultValue arg2Vals = arg2.getValue(); Iterable<SearchHit> merged = Iterables.mergeSorted( Arrays.asList(arg1Vals, arg2Vals), searchSortSpec.getComparator() ); int maxSize = arg1Vals.getValue().size() + arg2Vals.getValue().size(); if (limit > 0) { maxSize = Math.min(limit, maxSize); } List<SearchHit> results = Lists.newArrayListWithExpectedSize(maxSize); SearchHit prev = null; for (SearchHit searchHit : merged) { if (prev == null) { prev = searchHit; continue; } if (prev.equals(searchHit)) { if (prev.getCount() != null) { prev = new SearchHit( prev.getDimension(), prev.getValue(), prev.getCount() + searchHit.getCount() ); } } else { results.add(prev); prev = searchHit; if (limit > 0 && results.size() >= limit) { break; } } } if (prev != null && (limit < 0 || results.size() < limit)) { results.add(prev); } final DateTime timestamp = gran instanceof AllGranularity ? arg1.getTimestamp() : gran.toDateTime(gran.truncate(arg1.getTimestamp().getMillis())); return new Result<SearchResultValue>(timestamp, new SearchResultValue(results)); }
Source:
public Map<TopicPartition, OffsetAndMetadata> preCommit( Map<TopicPartition, OffsetAndMetadata> currentOffsets ) { Map<TopicPartition, OffsetAndMetadata> result = new HashMap<>(); hdfsWriter.getCommittedOffsets() .forEach((tp, offset) -> result.put(tp, new OffsetAndMetadata(offset))); log.debug("Returning committed offsets {}", result); return result; }

Target:
public Map<TopicPartition, OffsetAndMetadata> preCommit( Map<TopicPartition, OffsetAndMetadata> currentOffsets ) { Map<TopicPartition, OffsetAndMetadata> result = new HashMap<>(); for (Map.Entry<TopicPartition, Long> entry : hdfsWriter.getCommittedOffsets().entrySet()) { log.debug( "Found last committed offset for topic partition {}", entry.getValue(), entry.getKey() ); result.put(entry.getKey(), new OffsetAndMetadata(entry.getValue())); } log.debug("Returning committed offsets {}", result); return result; }
Source:
public void verifyToken(String token, String targetSubject, Map<String, String> claimMap) { JwtConsumer jwtConsumer = new JwtConsumerBuilder() .setRequireSubject() .setVerificationKey(key) .setRelaxVerificationKeyValidation() .build(); JwtClaims jwtClaims; String subject; try { jwtClaims = jwtConsumer.processToClaims(token); subject = jwtClaims.getSubject(); } catch (InvalidJwtException | MalformedClaimException e) { throw new SecurityTokenException(String.format("Invalid JWT: value-[%s]", token), e); } if (!targetSubject.equals(subject)) { throw new SecurityTokenException(String.format("Invalid JWT: value-[%s]", token)); } boolean claimMatch = claimMap.entrySet().stream().allMatch((e) -> { return e.getValue().equals(jwtClaims.getClaimValue(e.getKey())); }); if (!claimMatch) { throw new SecurityTokenException(String.format("Invalid JWT: value-[%s]", token)); } }

Target:
public void verifyToken(String token, String targetSubject, Map<String, String> claimMap) { JwtConsumer jwtConsumer = new JwtConsumerBuilder().setRequireSubject() .setVerificationKey(key) .setRelaxVerificationKeyValidation() .build(); JwtClaims jwtClaims; String subject; try { jwtClaims = jwtConsumer.processToClaims(token); subject = jwtClaims.getSubject(); } catch (InvalidJwtException | MalformedClaimException e) { throw new SecurityTokenException(String.format(MESSAGE_INVALID_JWT, token), e); } if (!targetSubject.equals(subject)) { throw new SecurityTokenException(String.format(MESSAGE_INVALID_JWT, token)); } boolean claimMatch = claimMap.entrySet().stream().allMatch((e) -> { return e.getValue().equals(jwtClaims.getClaimValue(e.getKey())); }); if (!claimMatch) { throw new SecurityTokenException(String.format(MESSAGE_INVALID_JWT, token)); } }
Source:
public ModelMergeToolAction() { super(EMFCompareEGitUIMessages.getString("ModelMergeToolCommandID"), new ModelMergeToolActionHandler()); }

Target:
public ModelMergeToolAction() { super(MERGE_TOOL_BUTTON_ID, new ModelMergeToolActionHandler()); }
Source:
boolean isPowerManagementLegal() { return IsPowerManagementLegal(getParameters().getVdsStaticData(), getVdsGroup() .getcompatibility_version().toString()); }

Target:
protected boolean isPowerManagementLegal() { return IsPowerManagementLegal(getParameters().getVdsStaticData(), getVdsGroup() .getcompatibility_version().toString()); }
Source:
public void tearDown() throws Exception { GrillServices.get().setServiceMode(GrillServices.SERVICE_MODE.OPEN); super.tearDown(); }

Target:
public void tearDown() throws Exception { super.tearDown(); }
Source:
@Test public void givenMultipleRequestsWhenResponseThenLog() throws InterruptedException { AtomicInteger completedReqs = new AtomicInteger(0); OptionalInt optHttpsPort = testServer.getRunningHttpsPort(); String url; int port; if (optHttpsPort.isPresent()) { port = optHttpsPort.getAsInt(); url = "https://localhost:" + port; } else { port = testServer.getRunningHttpPort().getAsInt(); url = "http://localhost:" + port; } WSClient ws = play.test.WSTestClient.newClient(port); IntStream.range(0, 100).parallel().forEach(num -> ws.url(url) .setRequestFilter(new AhcCurlRequestLogger()) .addHeader("key", "value") .addQueryParameter("num", "" + num) .get() .thenAccept(r -> { log.debug("Thread#" + num + " Request complete: Response code = " + r.getStatus() + " | Response: " + r.getBody() + " | Current Time:" + System.currentTimeMillis()); completedReqs.incrementAndGet(); }) ); log.debug("Waiting for requests to be completed. Current Time: " + System.currentTimeMillis()); while (completedReqs.get() != 100) { Thread.sleep(100); } log.debug("All requests have been completed. Exiting test."); }

Target:
public void givenMultipleRequestsWhenResponseThenLog() throws Exception { CountDownLatch latch = new CountDownLatch(100); WSClient ws = play.test.WSTestClient.newClient(port); IntStream.range(0, 100) .parallel() .forEach(num -> ws.url(url) .setRequestFilter(new AhcCurlRequestLogger()) .addHeader("key", "value") .addQueryParameter("num", "" + num) .get() .thenAccept(r -> { log.debug( "Thread#" + num + " Request complete: Response code = " + r.getStatus() + " | Response: " + r.getBody() + " | Current Time:" + System.currentTimeMillis()); latch.countDown(); }) ); log.debug( "Waiting for requests to be completed. Current Time: " + System.currentTimeMillis()); latch.await(5, TimeUnit.SECONDS ); assertEquals(0, latch.getCount()); log.debug("All requests have been completed. Exiting test."); }
Source:
public void handle(Request request, Response response) throws Exception { try (DbSession dbSession = dbClient.openSession(false)) { String componentKey = request.mandatoryParam(PARAM_KEY); ComponentDto component = componentFinder.getByKey(dbSession, componentKey); userSession.checkComponentPermission(USER, component); Map<String, String> keysByUUid = keysByUUid(dbSession, component); ScannerInput.ServerIssue.Builder responseBuilder = ScannerInput.ServerIssue.newBuilder(); response.stream().setMediaType(MediaTypes.PROTOBUF); OutputStream output = response.stream().output(); ResultHandler<IssueDto> handler = resultContext -> { IssueDto issue = resultContext.getResultObject(); handleIssue(issue, responseBuilder, keysByUUid, output); }; switch (component.scope()) { case Scopes.PROJECT: dbClient.issueDao().scrollNonClosedByModuleOrProject(dbSession, component, handler); break; case Scopes.FILE: dbClient.issueDao().scrollNonClosedByComponentUuid(dbSession, component.uuid(), handler); break; default: throw new IllegalStateException(format("Component of scope '%s' is not allowed", component.scope())); } } }

Target:
public void handle(Request request, Response response) throws Exception { try (DbSession dbSession = dbClient.openSession(false)) { String componentKey = request.mandatoryParam(PARAM_KEY); ComponentDto component = componentFinder.getByKey(dbSession, componentKey); userSession.checkComponentPermission(USER, component); Map<String, String> keysByUUid = keysByUUid(dbSession, component); ScannerInput.ServerIssue.Builder responseBuilder = ScannerInput.ServerIssue.newBuilder(); response.stream().setMediaType(MediaTypes.PROTOBUF); OutputStream output = response.stream().output(); ResultHandler<IssueDto> handler = resultContext -> { IssueDto issue = resultContext.getResultObject(); handleIssue(issue, responseBuilder, keysByUUid, output); }; switch (component.scope()) { case Scopes.PROJECT: dbClient.issueDao().scrollNonClosedByModuleOrProject(dbSession, component, handler); break; case Scopes.FILE: dbClient.issueDao().scrollNonClosedByComponentUuid(dbSession, component.uuid(), handler); break; default: throw new IllegalArgumentException(format("Component of scope '%s' is not allowed", component.scope())); } } }
Source:
private byte[] getHeaderValue(Object value) { if (value instanceof String) { return ((String) value).getBytes(); } else if (value instanceof Long) { ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); buffer.putLong((Long) value); return buffer.array(); } else if (value instanceof Integer) { ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES); buffer.putInt((Integer) value); return buffer.array(); } else if (value instanceof byte[]) { return (byte[]) value; } return null; }

Target:
private byte[] getHeaderValue(Object value) { if (value instanceof String) { return ((String) value).getBytes(); } else if (value instanceof Long) { ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES); buffer.putLong((Long) value); return buffer.array(); } else if (value instanceof Integer) { ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES); buffer.putInt((Integer) value); return buffer.array(); } else if (value instanceof Double) { ByteBuffer buffer = ByteBuffer.allocate(Double.BYTES); buffer.putDouble((Double) value); return buffer.array(); } else if (value instanceof byte[]) { return (byte[]) value; } log.debug("Cannot propagate header value of type[{}], skipping... " + "Supported types: String, Integer, Long, Double, byte[].", value != null ? value.getClass() : "null"); return null; }
Source:
public void set(double x) { for (;;) { Cell[] as; if ((as = cells) != null) { if (busy == 0 && casBusy()) { try { if (cells == as) { int n = as.length; Cell[] rs = new Cell[n]; for (int i = 0; i < n; ++i) { Cell a = as[i]; if (a != null) rs[i] = new Cell(0L); } cells = rs; base = Double.doubleToLongBits(x); break; } } finally { busy = 0; } } } else { base = Double.doubleToLongBits(x); break; } } }

Target:
public void set(double x) { for (;;) { Cell[] as; if ((as = cells) != null) { if (busy == 0 && casBusy()) { try { if (cells == as) { cells = null; base = Double.doubleToLongBits(x); break; } } finally { busy = 0; } } } else { base = Double.doubleToLongBits(x); break; } } }
Source:
private Collection<Cell> getSubCellsByLabel(Cell<?> cell, String label) { Object content = cell.getContent(); if (content instanceof CellCollection) { return ((CellCollection) content).cellMap().get(label); } else if (content instanceof Cell) { return Collections.singleton((Cell) content); } else { assert false; return null; } }

Target:
private Collection<Cell> getSubCellsByLabel(Cell<?> cell, String label) { Object content = cell.getContent(); if (content instanceof CellCollection) { return ((CellCollection) content).cellMap().get(label); } else if (content instanceof Cell) { return cell.getLabel().equals(label) ? Collections.singletonList((Cell) content) : Collections.<Cell>emptyList(); } else { assert false : "Wrong instruction!"; return null; } }
Source:
protected boolean validate() { if (getVds().isPmEnabled()) { List<FenceAgent> fenceAgents = fenceAgentDao.getFenceAgentsForHost(getVdsId()); if (fenceAgents.size() == 1) { return failValidation(EngineMessage.VDS_REMOVE_LAST_FENCE_AGENT_PM_ENABLED); } } if (getParameters() == null || getParameters().getAgent() == null || getParameters().getAgent().getId() == null) { return failValidation(EngineMessage.VDS_REMOVE_FENCE_AGENT_ID_REQUIRED); } return super.validate(); }

Target:
protected boolean validate() { if (getParameters() == null || getParameters().getAgent() == null || getParameters().getAgent().getId() == null) { return failValidation(EngineMessage.VDS_REMOVE_FENCE_AGENT_ID_REQUIRED); } if (getVds().isPmEnabled()) { List<FenceAgent> fenceAgents = fenceAgentDao.getFenceAgentsForHost(getVdsId()); if (fenceAgents.size() == 1) { return failValidation(EngineMessage.VDS_REMOVE_LAST_FENCE_AGENT_PM_ENABLED); } } return super.validate(); }
Source:
public List<Alert> getExampleAlerts() { List<Alert> alerts = new ArrayList<Alert>(); Alert alert = newAlert() .setRisk(Alert.RISK_LOW) .setConfidence(Alert.CONFIDENCE_MEDIUM) .setDescription(getDescription()) .setSolution(getSolution()) .setReference(getReference()) .setCweId(getCweId()) .setWascId(getWascId()) .build(); alerts.add(alert); return alerts; }

Target:
public List<Alert> getExampleAlerts() { List<Alert> alerts = new ArrayList<Alert>(); alerts.add(buildAlert(new HttpMessage(), "").build()); return alerts; }
Source:
@Override public void setPickupStatus(PickupStatus pickupStatus) { customPickupStatus = pickupStatus; }

Target:
public void setPickupStatus(PickupStatus pickupStatus) { customPickupStatus = pickupStatus; }
Source:
public void membershipChanged(List<Node> previousMembers, List<Node> members, final boolean merged) { if (this.getGroup().isCoordinator()) { Set<Node> deadNodes = new HashSet<>(previousMembers); deadNodes.removeAll(members); Set<Node> newNodes = new HashSet<>(members); newNodes.removeAll(previousMembers); if (!deadNodes.isEmpty()) { try (Batch batch = this.batcher.createBatch()) { try (CloseableIterator<Map.Entry<T, Set<Node>>> entries = this.cache.entrySet().iterator()) { while (entries.hasNext()) { Map.Entry<T, Set<Node>> entry = entries.next(); Set<Node> nodes = entry.getValue(); if (nodes.removeAll(deadNodes)) { entry.setValue(nodes); } } } } } if (merged) { try (Batch batch = this.batcher.createBatch()) { for (Node node: newNodes) { this.getServices(node).forEach(service -> this.register(node, service)); } } } } }

Target:
public void membershipChanged(List<Node> previousMembers, List<Node> members, final boolean merged) { if (this.getGroup().isCoordinator()) { Set<Node> deadNodes = new HashSet<>(previousMembers); deadNodes.removeAll(members); Set<Node> newNodes = new HashSet<>(members); newNodes.removeAll(previousMembers); if (!deadNodes.isEmpty()) { try (Batch batch = this.batcher.createBatch()) { try (CloseableIterator<Map.Entry<T, Set<Node>>> entries = this.cache.entrySet().iterator()) { while (entries.hasNext()) { Map.Entry<T, Set<Node>> entry = entries.next(); Set<Node> nodes = entry.getValue(); if (nodes.removeAll(deadNodes)) { entry.setValue(nodes); } } } } } if (merged) { for (Node node: newNodes) { try { Collection<T> services = this.dispatcher.executeOnNode(new GetLocalServicesCommand<>(), node).get(); try (Batch batch = this.batcher.createBatch()) { services.forEach(service -> this.register(node, service)); } } catch (Exception e) { ClusteringServerLogger.ROOT_LOGGER.warn(e.getLocalizedMessage(), e); } } } } }
Source:
private void process() { final IncomingMessageEnvelope envelope = state.fetchEnvelope(); log.trace("Process ssp offset {}", envelope.getSystemStreamPartition(), envelope.getOffset()); Runnable processWorker = () -> { final ReadableCoordinator coordinator = new ReadableCoordinator(task.taskName()); TaskCallbackFactory callbackFactory = new TaskCallbackFactory() { @Override public TaskCallback createCallback() { state.startProcess(); containerMetrics.processes().inc(); return callbackManager.createCallback(task.taskName(), envelope, coordinator); } }; task.process(envelope, coordinator, callbackFactory); }; if (threadPool != null) { threadPool.submit(processWorker); } else { processWorker.run(); } }

Target:
private void process() { final IncomingMessageEnvelope envelope = state.fetchEnvelope(); log.trace("Process ssp offset {}", envelope.getSystemStreamPartition(), envelope.getOffset()); final ReadableCoordinator coordinator = new ReadableCoordinator(task.taskName()); TaskCallbackFactory callbackFactory = new TaskCallbackFactory() { @Override public TaskCallback createCallback() { state.startProcess(); containerMetrics.processes().inc(); return callbackManager.createCallback(task.taskName(), envelope, coordinator); } }; task.process(envelope, coordinator, callbackFactory); }
Source:
private SkipRevFilter(int skip) { this.count = 0; this.skip = skip; }

Target:
private SkipRevFilter(int skip) { this.skip = skip; }
Source:
private String buildUrl(final CreateCategoryContext context) { return DiscussionsOperations.service(String.format(GET_CATEGORIES_URL_SUFFIX, context.getSiteId())); }

Target:
private String buildUrl(final CreateCategoryContext context) { return DiscussionsClient.service(String.format(GET_CATEGORIES_URL_SUFFIX, context.getSiteId())); }
Source:
private static <T> QueryWeigher<T> writeWeigher(long numRows, Supplier<Long> bytesWritten) { Supplier<Long> weight = Suppliers.memoize(() -> safeGetNumBytesOrDefault(bytesWritten)); return new QueryWeigher<T>() { @Override public QueryWeight weighSuccess(T result, long timeTakenNanos) { return ImmutableQueryWeight.builder() .from(DEFAULT_ESTIMATED_WEIGHT) .numBytes(weight.get()) .numDistinctRows(numRows) .timeTakenNanos(timeTakenNanos) .build(); } @Override public QueryWeight weighFailure(Exception error, long timeTakenNanos) { return weighSuccess(null, timeTakenNanos); } }; }

Target:
private static <T> QueryWeigher<T> writeWeigher(long numRows, Supplier<Long> bytesWritten) { Supplier<Long> weight = Suppliers.memoize(() -> safeGetNumBytesOrDefault(bytesWritten)); return new QueryWeigher<T>() { @Override public QueryWeight weighSuccess(T result, long timeTakenNanos) { return ImmutableQueryWeight.builder() .numBytes(weight.get()) .numDistinctRows(numRows) .timeTakenNanos(timeTakenNanos) .build(); } @Override public QueryWeight weighFailure(Exception error, long timeTakenNanos) { return weighSuccess(null, timeTakenNanos); } }; }
Source:
private synchronized void updateProperties() { if (connectorFile.lastModified() == cacheTimestamp) { return; } Properties props = new Properties(); try { FileReader reader = new FileReader(connectorFile); props.load(reader); reader.close(); } catch (IOException e) { throw new IllegalStateException(e); } this.propertiesMap = Maps.fromProperties(props); cacheTimestamp = connectorFile.lastModified(); }

Target:
private synchronized void updateProperties() { if (connectorFile.lastModified() == cacheTimestamp) { return; } Properties props = new Properties(); FileReader reader; try { reader = new FileReader(connectorFile); } catch (FileNotFoundException e) { throw new IllegalStateException(e); } try { props.load(reader); } catch (IOException e) { throw new IllegalStateException(e); } finally { IOUtils.closeQuietly(reader); } this.propertiesMap = Maps.fromProperties(props); cacheTimestamp = connectorFile.lastModified(); }
Source:
public static Node createInvalidType(Node node, NodeType type) { StringBuilder message = new StringBuilder("Invalid type " + node.getType() + ", expected " + type); if (node.getParent() != null && node.getParent() instanceof KeyValueNode) { message.append(" (key: \"" + ((KeyValueNode) node.getParent()).getKey() + "\")"); } return new ErrorNode(message.toString()); }

Target:
public static Node createInvalidType(Node node, NodeType type) { return new ErrorNode("Invalid type " + node.getType() + ", expected " + type); }
Source:
public void doGenerateBundle(@QueryParameter("components") String components, StaplerResponse rsp) throws IOException { if (components == null) { rsp.sendError(HttpServletResponse.SC_BAD_REQUEST, "components parameter is mandatory"); return; } List<String> componentNames = Arrays.asList(components.split(",")); logger.fine("Selecting components..."); prepareBundle(rsp, getComponents().stream().filter(c -> componentNames.contains(c.getId())).collect(Collectors.toList())); }

Target:
public void doGenerateBundle(@QueryParameter("components") String components, StaplerResponse rsp) throws IOException { if (components == null) { rsp.sendError(HttpServletResponse.SC_BAD_REQUEST, "components parameter is mandatory"); return; } List<String> componentNames = Arrays.asList(components.split(",")); logger.fine("Selecting components..."); List<Component> selectedComponents = getComponents().stream().filter(c -> componentNames.contains(c.getId())).collect(Collectors.toList()); if (selectedComponents.isEmpty()) { rsp.sendError(HttpServletResponse.SC_BAD_REQUEST, "selected component list is empty"); return; } prepareBundle(rsp, selectedComponents); }
Source:
private ChannelPool newPool(SocketAddress address) { log.debugf("Creating new channel pool for %s", address); Bootstrap bootstrap = new Bootstrap() .group(eventLoopGroup) .channel(NioSocketChannel.class) .remoteAddress(address) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.connectionTimeout()) .option(ChannelOption.SO_KEEPALIVE, configuration.tcpKeepAlive()) .option(ChannelOption.TCP_NODELAY, configuration.tcpNoDelay()) .option(ChannelOption.SO_RCVBUF, 1024576); int maxConnections = configuration.connectionPool().maxActive(); if (maxConnections < 0) { maxConnections = Integer.MAX_VALUE; } ChannelInitializer channelInitializer = new ChannelInitializer(bootstrap, address, operationsFactory, configuration); bootstrap.handler(channelInitializer); ChannelPool pool = new ChannelPool(bootstrap.config().group().next(), address, channelInitializer, configuration.connectionPool().exhaustedAction(), configuration.connectionPool().maxWait(), maxConnections); channelInitializer.setChannelPool(pool); return pool; }

Target:
private ChannelPool newPool(SocketAddress address) { log.debugf("Creating new channel pool for %s", address); Bootstrap bootstrap = new Bootstrap() .group(eventLoopGroup) .channel(TransportHelper.socketChannel()) .remoteAddress(address) .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, configuration.connectionTimeout()) .option(ChannelOption.SO_KEEPALIVE, configuration.tcpKeepAlive()) .option(ChannelOption.TCP_NODELAY, configuration.tcpNoDelay()) .option(ChannelOption.SO_RCVBUF, 1024576); int maxConnections = configuration.connectionPool().maxActive(); if (maxConnections < 0) { maxConnections = Integer.MAX_VALUE; } ChannelInitializer channelInitializer = new ChannelInitializer(bootstrap, address, operationsFactory, configuration); bootstrap.handler(channelInitializer); ChannelPool pool = new ChannelPool(bootstrap.config().group().next(), address, channelInitializer, configuration.connectionPool().exhaustedAction(), configuration.connectionPool().maxWait(), maxConnections); channelInitializer.setChannelPool(pool); return pool; }
Source:
public String getDeleteDescription() { return getName() + (getAlias() == null ? "" : " (" + getAlias() + ")"); }

Target:
public String getDeleteDescription() { return getName() + " (" + getAlias() + ")"; }
Source:
private Qualifier convertMilestoneAliasQualifier(List<TurboMilestone> allMilestones, int currentIndex) { if (!content.isPresent()) { return Qualifier.EMPTY; } String contents = content.get(); String alias = contents; Pattern aliasPattern = Pattern.compile("(curr(?:ent)?)(?:(\\+|-)(\\d+))?$"); Matcher aliasMatcher = aliasPattern.matcher(alias); int offset = 0; if (!aliasMatcher.find()) { return this; } if (aliasMatcher.group(2) != null && aliasMatcher.group(3) != null) { offset = Integer.parseInt(aliasMatcher.group(3)); if (aliasMatcher.group(2).equals("+")) { currentIndex += offset; } else { currentIndex -= offset; } } if (currentIndex >= allMilestones.size() || currentIndex < 0) { return this; } contents = allMilestones.get(currentIndex).getTitle().toLowerCase(); return new Qualifier(name, contents); }

Target:
private Qualifier convertMilestoneAliasQualifier(List<TurboMilestone> allMilestones, int currentIndex) { if (!content.isPresent()) { return Qualifier.EMPTY; } String contents = content.get(); String alias = contents; Pattern aliasPattern = Pattern.compile("(curr(?:ent)?)(?:(\\+|-)(\\d+))?$"); Matcher aliasMatcher = aliasPattern.matcher(alias); int offset = 0; if (!aliasMatcher.find()) { return this; } if (aliasMatcher.group(2) != null && aliasMatcher.group(3) != null) { offset = Integer.parseInt(aliasMatcher.group(3)); if (aliasMatcher.group(2).equals("+")) { currentIndex += offset; } else { currentIndex -= offset; } } if (currentIndex >= allMilestones.size() || currentIndex < 0) { return Qualifier.FALSE; } contents = allMilestones.get(currentIndex).getTitle().toLowerCase(); return new Qualifier(name, contents); }
Source:
private UserSession getSessionFromAccount(Study study, CriteriaContext context, Account account) { StudyParticipant participant = participantService.getParticipant(study, account, false); if (participant.getLanguages().isEmpty() && !context.getLanguages().isEmpty()) { participant = new StudyParticipant.Builder().copyOf(participant) .withLanguages(context.getLanguages()).build(); account.setLanguages(context.getLanguages()); accountDao.updateAccount(account, false); } UserSession session = new UserSession(participant); UserSession existingSession = cacheProvider.getUserSessionByUserId(account.getId()); if (existingSession != null) { session.setSessionToken(existingSession.getSessionToken()); session.setInternalSessionToken(existingSession.getInternalSessionToken()); } else { session.setSessionToken(BridgeUtils.generateGuid()); session.setInternalSessionToken(BridgeUtils.generateGuid()); } session.setAuthenticated(true); session.setEnvironment(config.getEnvironment()); session.setStudyIdentifier(study.getStudyIdentifier()); session.setReauthToken(account.getReauthToken()); CriteriaContext newContext = new CriteriaContext.Builder() .withContext(context) .withHealthCode(session.getHealthCode()) .withUserId(session.getId()) .withLanguages(session.getParticipant().getLanguages()) .withUserDataGroups(session.getParticipant().getDataGroups()) .build(); session.setConsentStatuses(consentService.getConsentStatuses(newContext, account)); return session; }

Target:
private UserSession getSessionFromAccount(Study study, CriteriaContext context, Account account) { StudyParticipant participant = participantService.getParticipant(study, account, false); if (participant.getLanguages().isEmpty() && !context.getLanguages().isEmpty()) { participant = new StudyParticipant.Builder().copyOf(participant) .withLanguages(context.getLanguages()).build(); accountDao.editAccount(study.getStudyIdentifier(), participant.getHealthCode(), accountToEdit -> accountToEdit.setLanguages(context.getLanguages())); } UserSession session = new UserSession(participant); UserSession existingSession = cacheProvider.getUserSessionByUserId(account.getId()); if (existingSession != null) { session.setSessionToken(existingSession.getSessionToken()); session.setInternalSessionToken(existingSession.getInternalSessionToken()); } else { session.setSessionToken(BridgeUtils.generateGuid()); session.setInternalSessionToken(BridgeUtils.generateGuid()); } session.setAuthenticated(true); session.setEnvironment(config.getEnvironment()); session.setStudyIdentifier(study.getStudyIdentifier()); session.setReauthToken(account.getReauthToken()); CriteriaContext newContext = new CriteriaContext.Builder() .withContext(context) .withHealthCode(session.getHealthCode()) .withUserId(session.getId()) .withLanguages(session.getParticipant().getLanguages()) .withUserDataGroups(session.getParticipant().getDataGroups()) .build(); session.setConsentStatuses(consentService.getConsentStatuses(newContext, account)); return session; }
Source:
protected boolean canDoAction() { if (getNic() == null) { return failCanDoAction(VdcBllMessages.HOST_NETWORK_INTERFACE_NOT_EXIST); } if (NetworkUtils.isLabeled(getNic()) && getNic().getLabels().contains(getLabel())) { return failCanDoAction(VdcBllMessages.INTERFACE_ALREADY_LABELED); } if (!ValidationUtils.validateInputs(getValidationGroups(), getNic()).isEmpty()) { return failCanDoAction(VdcBllMessages.IMPROPER_BOND_IS_LABELED); } if (Boolean.TRUE.equals(getNic().getBonded())) { int slavesCount = 0; for (VdsNetworkInterface nic : getHostInterfaces()) { if (StringUtils.equals(getNic().getName(), nic.getBondName())) { slavesCount++; if (slavesCount == 2) { break; } } } if (slavesCount < 2) { return failCanDoAction(VdcBllMessages.IMPROPER_INTERFACE_IS_LABELED); } } for (VdsNetworkInterface nic : getHostInterfaces()) { if (!StringUtils.equals(nic.getName(), getNicName()) && NetworkUtils.isLabeled(nic) && nic.getLabels().contains(getLabel())) { return failCanDoAction(VdcBllMessages.OTHER_INTERFACE_ALREADY_LABELED, "$LabeledNic " + nic.getName()); } } List<String> assignedNetworks = validateNetworksNotAssignedToIncorrectNics(); if (!assignedNetworks.isEmpty()) { return failCanDoAction(VdcBllMessages.LABELED_NETWORK_ATTACHED_TO_WRONG_INTERFACE, "$AssignedNetworks " + StringUtils.join(assignedNetworks, ", ")); } return true; }

Target:
protected boolean canDoAction() { if (getNic() == null) { return failCanDoAction(VdcBllMessages.HOST_NETWORK_INTERFACE_NOT_EXIST); } if (NetworkUtils.isLabeled(getNic()) && getNic().getLabels().contains(getLabel())) { return failCanDoAction(VdcBllMessages.INTERFACE_ALREADY_LABELED); } if (!ValidationUtils.validateInputs(getValidationGroups(), getNic()).isEmpty()) { return failCanDoAction(VdcBllMessages.IMPROPER_INTERFACE_IS_LABELED); } if (Boolean.TRUE.equals(getNic().getBonded())) { int slavesCount = 0; for (VdsNetworkInterface nic : getHostInterfaces()) { if (StringUtils.equals(getNic().getName(), nic.getBondName())) { slavesCount++; if (slavesCount == 2) { break; } } } if (slavesCount < 2) { return failCanDoAction(VdcBllMessages.IMPROPER_BOND_IS_LABELED); } } for (VdsNetworkInterface nic : getHostInterfaces()) { if (!StringUtils.equals(nic.getName(), getNicName()) && NetworkUtils.isLabeled(nic) && nic.getLabels().contains(getLabel())) { return failCanDoAction(VdcBllMessages.OTHER_INTERFACE_ALREADY_LABELED, "$LabeledNic " + nic.getName()); } } List<String> assignedNetworks = validateNetworksNotAssignedToIncorrectNics(); if (!assignedNetworks.isEmpty()) { return failCanDoAction(VdcBllMessages.LABELED_NETWORK_ATTACHED_TO_WRONG_INTERFACE, "$AssignedNetworks " + StringUtils.join(assignedNetworks, ", ")); } return true; }
Source:
private PartitionMetadata findLeader(List<String> a_seedBrokers, int a_port, String a_topic, int a_partition) { PartitionMetadata returnMetaData = null; for (String seed : a_seedBrokers) { SimpleConsumer consumer = null; try { consumer = new SimpleConsumer(seed, a_port, 100000, 64 * 1024, "leaderLookup"); List<String> topics = new ArrayList<String>(); topics.add(a_topic); TopicMetadataRequest req = new TopicMetadataRequest(topics); kafka.javaapi.TopicMetadataResponse resp = consumer.send(req); List<TopicMetadata> metaData = resp.topicsMetadata(); for (TopicMetadata item : metaData) { for (PartitionMetadata part : item.partitionsMetadata()) { if (part.partitionId() == a_partition) { returnMetaData = part; break; } } } } catch (Exception e) { System.out.println("Error communicating with Broker [" + seed + "] to find Leader for [" + a_topic + ", " + a_partition + "] Reason: " + e); } finally { if (consumer != null) consumer.close(); } } if (returnMetaData != null) { m_replicaBrokers.clear(); for (kafka.cluster.Broker replica : returnMetaData.replicas()) { m_replicaBrokers.add(replica.host()); } } return returnMetaData; }

Target:
private PartitionMetadata findLeader(List<String> a_seedBrokers, int a_port, String a_topic, int a_partition) { PartitionMetadata returnMetaData = null; for (String seed : a_seedBrokers) { SimpleConsumer consumer = null; try { consumer = new SimpleConsumer(seed, a_port, kafkaConnectionTimeOut, kafkaBufferSize, leaderClientID); List<String> topics = new ArrayList<String>(); topics.add(a_topic); TopicMetadataRequest req = new TopicMetadataRequest(topics); kafka.javaapi.TopicMetadataResponse resp = consumer.send(req); List<TopicMetadata> metaData = resp.topicsMetadata(); for (TopicMetadata item : metaData) { for (PartitionMetadata part : item.partitionsMetadata()) { if (part.partitionId() == a_partition) { returnMetaData = part; break; } } } } catch (Exception e) { logger.error("Error communicating with Broker [" + seed + "] to find Leader for [" + a_topic + ", " + a_partition + "] Reason: " + e); } finally { if (consumer != null) consumer.close(); } } if (returnMetaData != null) { m_replicaBrokers.clear(); for (kafka.cluster.Broker replica : returnMetaData.replicas()) { m_replicaBrokers.add(replica.host()); } } return returnMetaData; }
Source:
public void testReferenceCounting() throws Exception { loadQueryable("test", "3", new Interval("2011-04-04/2011-04-05")); assertQueryable( QueryGranularity.DAY, "test", new Interval("2011-04-04/2011-04-06"), ImmutableList.<Pair<String, Interval>>of( new Pair<String, Interval>("3", new Interval("2011-04-04/2011-04-05")) ) ); Assert.assertFalse(closed); dropQueryable("test", "3", new Interval("2011-04-04/2011-04-05")); Assert.assertTrue(closed); }

Target:
public void testReferenceCounting() throws Exception { loadQueryable("test", "3", new Interval("2011-04-04/2011-04-05")); Future future = assertQueryable( QueryGranularity.DAY, "test", new Interval("2011-04-04/2011-04-06"), ImmutableList.<Pair<String, Interval>>of( new Pair<String, Interval>("3", new Interval("2011-04-04/2011-04-05")) ) ); queryNotifyLatch.await(); Assert.assertTrue(factory.getAdapters().size() == 1); for (SegmentForTesting segmentForTesting : factory.getAdapters()) { Assert.assertFalse(segmentForTesting.isClosed()); } queryWaitLatch.countDown(); future.get(); dropQueryable("test", "3", new Interval("2011-04-04/2011-04-05")); for (SegmentForTesting segmentForTesting : factory.getAdapters()) { Assert.assertTrue(segmentForTesting.isClosed()); } }
Source:
private void initTableColumns() { Column<EntityModel, String> nameColumn = new Column<EntityModel, String>(new TextInputCell()) { @Override public String getValue(EntityModel object) { return ((HostDetailModel) object.getEntity()).getName(); } }; hostsTable.addColumn(nameColumn, constants.nameHost(), "50px"); nameColumn.setFieldUpdater((index, object, value) -> ((HostDetailModel) object.getEntity()).setName(value)); Column<EntityModel, String> addressColumn = new Column<EntityModel, String>(new TextInputCell()) { @Override public String getValue(EntityModel object) { return ((HostDetailModel) object.getEntity()).getAddress(); } }; hostsTable.addColumn(addressColumn, constants.ipHost(), "100px"); addressColumn .setFieldUpdater((index, object, value) -> ((HostDetailModel) object.getEntity()).setAddress(value)); Column<EntityModel, String> passwordColumn = new Column<EntityModel, String>(new PasswordTextInputCell()) { @Override public String getValue(EntityModel object) { return ((HostDetailModel) object.getEntity()).getPassword(); } }; hostsTable.addColumn(passwordColumn, constants.hostPopupPasswordLabel(), "100px"); passwordColumn.setFieldUpdater((index, object, value) -> ((HostDetailModel) object.getEntity()).setPassword(value)); hostsTable.addColumn(new AbstractEntityModelTextColumn<HostDetailModel>() { @Override public String getText(HostDetailModel hostModel) { return hostModel.getFingerprint(); } }, constants.hostsPopupFingerprint(), "300px"); }

Target:
private void initTableColumns() { Column<EntityModel, String> nameColumn = new Column<EntityModel, String>(new TextInputCell()) { @Override public String getValue(EntityModel object) { return ((HostDetailModel) object.getEntity()).getName(); } }; hostsTable.addColumn(nameColumn, constants.nameHost(), "80px"); nameColumn.setFieldUpdater((index, object, value) -> ((HostDetailModel) object.getEntity()).setName(value)); Column<EntityModel, String> addressColumn = new Column<EntityModel, String>(new TextInputCell()) { @Override public String getValue(EntityModel object) { return ((HostDetailModel) object.getEntity()).getAddress(); } }; hostsTable.addColumn(addressColumn, constants.ipHostImportCluster(), "180px"); addressColumn .setFieldUpdater((index, object, value) -> ((HostDetailModel) object.getEntity()).setAddress(value)); Column<EntityModel, String> passwordColumn = new Column<EntityModel, String>(new PasswordTextInputCell()) { @Override public String getValue(EntityModel object) { return ((HostDetailModel) object.getEntity()).getPassword(); } }; hostsTable.addColumn(passwordColumn, constants.hostPopupPasswordLabel(), "100px"); passwordColumn.setFieldUpdater((index, object, value) -> ((HostDetailModel) object.getEntity()).setPassword(value)); hostsTable.addColumn(new AbstractEntityModelTextColumn<HostDetailModel>() { @Override public String getText(HostDetailModel hostModel) { return hostModel.getFingerprint(); } }, constants.hostsPopupFingerprint(), "300px"); }
Source:
public Object execute(ExecutionEvent aEvent) throws ExecutionException { GerritTask item = null; GerritTableView reviewTableView = GerritTableView .getActiveView(); TableViewer viewer = reviewTableView.getTableViewer(); ISelection tableSelection = viewer.getSelection(); if (tableSelection.isEmpty()) { GerritUi.Ftracer.traceInfo("Selected table selection is EMPTY " ); } else { if (tableSelection instanceof IStructuredSelection ) { Object obj = ((IStructuredSelection) tableSelection).getFirstElement(); if (obj instanceof GerritTask) { item = (GerritTask) obj; item.toggleStarred(GerritTask.IS_STARRED, Boolean.toString(!Boolean.valueOf(item.getAttribute(GerritTask.IS_STARRED)))); try { reviewTableView.setStarred(item.getTaskId(), item.getStarred(), new NullProgressMonitor() {}); } catch (CoreException e) { UIUtils.showErrorDialog(e.getMessage(), e.getStatus().getException().getMessage()); item.toggleStarred(GerritTask.IS_STARRED, Boolean.toString(!Boolean.valueOf(item.getAttribute(GerritTask.IS_STARRED)))); } viewer.update(item, null); } } } return item; }

Target:
public Object execute(ExecutionEvent aEvent) throws ExecutionException { GerritTask item = null; GerritTableView reviewTableView = GerritTableView .getActiveView(); TableViewer viewer = reviewTableView.getTableViewer(); ISelection tableSelection = viewer.getSelection(); if (tableSelection.isEmpty()) { GerritUi.Ftracer.traceInfo("Selected table selection is EMPTY " ); } else { if (tableSelection instanceof IStructuredSelection ) { Object obj = ((IStructuredSelection) tableSelection).getFirstElement(); if (obj instanceof GerritTask) { item = (GerritTask) obj; try { reviewTableView.setStarred(item.getTaskId(), !item.getStarred(), new NullProgressMonitor() {}); item.toggleStarred(GerritTask.IS_STARRED, Boolean.toString(!Boolean.valueOf(item.getAttribute(GerritTask.IS_STARRED)))); } catch (CoreException e) { UIUtils.showErrorDialog(e.getMessage(), e.getStatus().getException().getMessage()); } viewer.update(item, null); } } } return item; }
Source:
protected void checkRyaInstanceExists(final Map<String, String> taskConfig) throws IllegalStateException { requireNonNull(taskConfig); final MongoRyaSinkConfig config = new MongoRyaSinkConfig(taskConfig); @Nullable final String username = Strings.isNullOrEmpty(config.getUsername()) ? null : config.getUsername(); @Nullable final char[] password = Strings.isNullOrEmpty(config.getPassword()) ? null : config.getPassword().toCharArray(); final ServerAddress serverAddr = new ServerAddress(config.getHostname(), config.getPort()); final boolean hasCredentials = username != null && password != null; try(MongoClient mongoClient = hasCredentials ? new MongoClient(serverAddr, Arrays.asList(MongoCredential.createCredential(username, config.getRyaInstanceName(), password))) : new MongoClient(serverAddr)) { final MongoConnectionDetails connectionDetails = new MongoConnectionDetails( config.getHostname(), config.getPort(), Optional.ofNullable(username), Optional.ofNullable(password)); final RyaClient client = MongoRyaClientFactory.build(connectionDetails, mongoClient); if(!client.getInstanceExists().exists( config.getRyaInstanceName() )) { throw new ConnectException("The Rya Instance named " + config.getRyaInstanceName() + " has not been installed."); } } catch(final RyaClientException e) { throw new ConnectException("Unable to determine if the Rya Instance named " + config.getRyaInstanceName() + " has been installed.", e); } }

Target:
protected void checkRyaInstanceExists(final Map<String, String> taskConfig) throws IllegalStateException { requireNonNull(taskConfig); final MongoRyaSinkConfig config = new MongoRyaSinkConfig(taskConfig); @Nullable final String username = Strings.isNullOrEmpty(config.getUsername()) ? null : config.getUsername(); @Nullable final char[] password = Strings.isNullOrEmpty(config.getPassword()) ? null : config.getPassword().toCharArray(); final ServerAddress serverAddr = new ServerAddress(config.getHostname(), config.getPort()); final boolean hasCredentials = username != null && password != null; try(MongoClient mongoClient = hasCredentials ? new MongoClient(serverAddr, Arrays.asList(MongoCredential.createCredential(username, config.getRyaInstanceName(), password))) : new MongoClient(serverAddr)) { final MongoConnectionDetails connectionDetails = new MongoConnectionDetails( config.getHostname(), config.getPort(), Optional.ofNullable(username), Optional.ofNullable(password)); final RyaClient client = MongoRyaClientFactory.build(connectionDetails, mongoClient); if(!client.getInstanceExists().exists( config.getRyaInstanceName() )) { throw new ConnectException("The Rya Instance named " + LogUtils.clean(config.getRyaInstanceName()) + " has not been installed."); } } catch(final RyaClientException e) { throw new ConnectException("Unable to determine if the Rya Instance named " + LogUtils.clean(config.getRyaInstanceName()) + " has been installed.", e); } }
Source:
public <REQ extends BasicMessage, RESP extends BasicMessage> Command<REQ> getCommand(Class<REQ> requestClass) throws NoCommandForMessageException { if (ResourcePathDestination.class.isAssignableFrom(requestClass)) { return (Command<REQ>) resourcePathDestinationWsCommand; } else if (UiSessionDestination.class.isAssignableFrom(requestClass)) { return (Command<REQ>) uiSessionDestinationWsCommand; } else if (EchoRequest.class.isAssignableFrom(requestClass)) { return (Command<REQ>) echoCommand; } throw new NoCommandForMessageException("No command found for requestClass [" + requestClass.getName() + "]"); }

Target:
public <REQ extends BasicMessage> WsCommand<REQ> getCommand(Class<REQ> requestClass) throws NoCommandForMessageException { if (ResourcePathDestination.class.isAssignableFrom(requestClass)) { return (WsCommand<REQ>) resourcePathDestinationWsCommand; } else if (UiSessionDestination.class.isAssignableFrom(requestClass)) { return (WsCommand<REQ>) uiSessionDestinationWsCommand; } else if (EchoRequest.class.isAssignableFrom(requestClass)) { return (WsCommand<REQ>) echoCommand; } throw new NoCommandForMessageException("No command found for requestClass [" + requestClass.getName() + "]"); }
Source:
private void enableAutoGenerationOfSwaggerSpecification() { final io.swagger.jaxrs.config.BeanConfig beanConfig = new BeanConfig(); beanConfig.setResourcePackage("com.clicktravel.services,com.clicktravel.services.*"); beanConfig.setSchemes(new String[] { "https" }); beanConfig.setBasePath("/"); final Info info = new Info(); info.setVersion("1.0.0"); beanConfig.setInfo(info); beanConfig.setTitle("Swagger Specification"); beanConfig.setVersion("1.0.0"); final Swagger swaggerConfiguration = beanConfig.getSwagger(); final OAuth2Definition oauth2ImplicitDefinition = new OAuth2Definition(); final String applicationGatewayEndpiont = "<LINK_0>"; final String authorizationUrl = String.format("%s/authorize", applicationGatewayEndpiont); oauth2ImplicitDefinition.implicit(authorizationUrl); oauth2ImplicitDefinition.addScope("Default", "The default scope for Oauth authentication"); swaggerConfiguration.addSecurityDefinition("implicit", oauth2ImplicitDefinition); beanConfig.configure(swaggerConfiguration); beanConfig.setScan(true); }

Target:
private void enableAutoGenerationOfSwaggerSpecification() { final BeanConfig beanConfig = new BeanConfig(); beanConfig.setResourcePackage("com.clicktravel.services,com.clicktravel.services.*"); beanConfig.setSchemes(new String[] { "https" }); beanConfig.setBasePath("/"); final Info info = new Info(); info.setVersion("2.0.0"); beanConfig.setInfo(info); beanConfig.setTitle("Swagger Specification"); beanConfig.setVersion("0.0.0"); beanConfig.setScan(true); }