Spring Fox (Swagger-UI) 2.9.2 How to disable the 'Try it out' button - firefox

I am trying to disable the 'Try it out' button from the UI.
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
In my Java class, I am doing something like below in an attempt to disable the button, and none of the properties I am trying seem to work. How can I disable the 'Try it out' button?
#GetMapping(path = "/swagger-resources/configuration/ui", produces = APPLICATION_JSON_VALUE)
public Object uiConfig() {
HashMap<String, Object> map = new HashMap<>();
...
1. map.put("supportedSubmitMethods", new String[0]);
2. map.put("x-explorer-enabled", Boolean.FALSE);
3. map.put("x-samples-enabled", Boolean.FALSE);
...
return map;
}

Below code worked for me
#Bean
UiConfiguration uiConfig()
{
return new UiConfiguration( null, UiConfiguration.Constants.NO_SUBMIT_METHODS );
}
Thanks

Related

Spring boot webflux TEXT_EVENT_STREAM_VALUE is not working

I'm using spring-boot with the dependency spring-boot-starter-webflux,
i want to get one data per second with browser,
when i use spring-boot version 2.1.4,the code is working,
but 2.1.5 or greater version not working,
i will get all of the data at 10 sesonds later,not one data per second
I want to get the reason,or others i should do
I find spring-boot update the dependency of netty in 2.1.5,
so if i add the dependency in my pom.xml with
<dependency>
<groupId>io.projectreactor.netty</groupId>
<artifactId>reactor-netty</artifactId>
<version>0.8.8.RELEASE</version>
</dependency>
it working
#RestController
#RequestMapping("/demo")
public class DemoController {
// just get a string per second
#GetMapping(value = "",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> getMsg(){
return Flux.fromStream(new Random().ints(10).mapToObj(intStream ->
{
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "this is data "+intStream;
}));
}
}
I believe this will achieve what it is you are going for.
#GetMapping(value = "",produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<String> getMsg(){
return Flux.fromStream(new Random()
.ints(10)
.mapToObj(value -> "this is data " + value))
.delayElements(Duration.ofSeconds(1));
}

How to use resilience4j on calling method?

I tried to use spring retry for Circuit breaking and retry as below and it is working as expected but issue is unable to configure "maxAttempts/openTimeout/resetTimeout" as env variables (error is should be constants). My question is how use resilience4j to achieve the below requirement?
also please suggest there is a way to pass env variables to "maxAttempts/openTimeout/resetTimeout".
#CircuitBreaker(value = {
MongoServerException.class,
MongoSocketException.class,
MongoTimeoutException.class
MongoSocketOpenException.class},
maxAttempts = 2,
openTimeout = 20000L ,
resetTimeout = 30000L)
public void insertDocument(ConsumerRecord<Long, GenericRecord> consumerRecord){
retryTemplate.execute(args0 -> {
LOGGER.info(String.format("Inserting record with key -----> %s", consumerRecord.key().toString()));
BasicDBObject dbObject = BasicDBObject.parse(consumerRecord.value().toString());
dbObject.put("_id", consumerRecord.key());
mongoCollection.replaceOne(<<BasicDBObject with id>>, getReplaceOptions());
return null;
});
}
#Recover
public void recover(RuntimeException t) {
LOGGER.info(" Recovering from Circuit Breaker ");
}
dependencies used are
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.retry</groupId>
<artifactId>spring-retry</artifactId>
</dependency>
You are not using resilience4j, but spring-retry.
You should adapt the title of your question.
CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom()
.waitDurationInOpenState(Duration.ofMillis(20000))
.build();
CircuitBreakerRegistry circuitBreakerRegistry = CircuitBreakerRegistry.of(circuitBreakerConfig);
CircuitBreaker circuitBreaker = circuitBreakerRegistry.circuitBreaker("mongoDB");
RetryConfig retryConfig = RetryConfig.custom().maxAttempts(3)
.retryExceptions(MongoServerException.class,
MongoSocketException.class,
MongoTimeoutException.class
MongoSocketOpenException.class)
.ignoreExceptions(CircuitBreakerOpenException.class).build();
Retry retry = Retry.of("helloBackend", retryConfig);
Runnable decoratedRunnable = Decorators.ofRunnable(() -> insertDocument(ConsumerRecord<Long, GenericRecord> consumerRecord))
.withCircuitBreaker(circuitBreaker)
.withRetry(retry)
.decorate();
String result = Try.runRunnable(decoratedRunnable )
.recover(exception -> ...).get();

Websocket with ActiveMQ support multi session?

I have spring boot application use websocket and embeded ActiveMQ, when user (TestUser) subscribe /user/TestUser/reply in two different browser at the same time ,then send message to him one browser received the another not , send again new one the second receive but first one not and so on…… .
What I expected when send message to /user/TestUser/reply , if he is open two browsers as the same time should receive the message in two browser at the same time.
POM.xml
<!-- WebSocket libraries -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-activemq</artifactId>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-stomp</artifactId>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-kahadb-store</artifactId>
<scope>runtime</scope>
</dependency>
WebSocketConfig
#Configuration
#EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
#Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.setApplicationDestinationPrefixes("/app")
.setUserDestinationPrefix("/user")
.enableStompBrokerRelay("/user");
}
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/websocket").addInterceptors(new HttpHandshakeInterceptor()).withSockJS();
}
#Override
public void configureClientInboundChannel(ChannelRegistration registration) {
registration.setInterceptors(new TopicSubscriptionInterceptor());
}
#Bean
public BrokerService broker() throws Exception {
BrokerService broker = new BrokerService();
broker.setSchedulePeriodForDestinationPurge(10000);
broker.addConnector("stomp://localhost:61613");
PolicyMap policyMap = new PolicyMap();
PolicyEntry policyEntry = new PolicyEntry();
policyEntry.setGcInactiveDestinations(true);
policyEntry.setInactiveTimeoutBeforeGC(30000);
policyEntry.setQueue(">");
List<PolicyEntry> entries = new ArrayList<PolicyEntry>();
entries.add(policyEntry);
policyMap.setPolicyEntries(entries);
broker.setDestinationPolicy(policyMap);
return broker;
}
UI
function connect() {
var socket = new SockJS('/websocket');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
setConnected(true);
console.log('Connected: ' + frame);
stompClient.subscribe('/user/TestUser/reply', function (greeting) {
message = greeting;
showGreeting(greeting);
}, {'ack': 'client-individual'});
});
}
If you change your UI code to use topic, like this:
stompClient.subscribe('/topic/reply/'+ frame.headers['user-name'], function (greeting) { ...
and configure relay to /topic
config.setApplicationDestinationPrefixes("/app")
.enableStompBrokerRelay("/topic");
and send messages like :
simpMessageTemplate.convertAndSend("/topic/reply/" + principal, payload, headers);
than every connected client will recieve his message copy.
frame.headers['user-name'] some spring magic header with current logged in principal, returned on connect. don't know who adds it, maybe spring-security.
If you want to do it with anon user, you have to generate user-id on client side, store it somewhere ( localstorage or cookie ) and pass to server side to use as principal name.
EDIT:
If you want to restict connection to topic to only one user, you can do this like this (in TopicSubscriptionInterceptor):
#Override
public Message<?> preSend(Message<?> message, MessageChannel channel) {
StompHeaderAccessor sha = StompHeaderAccessor.wrap(message);
switch (sha.getCommand()) {
case SUBSCRIBE:
case SEND:
if(!sha.getDestination().equals("/topic/reply/" + sha.getUser().getName()) return null;
break;
}
...
return message;
}

Spring-Boot Elasticseach EntityMapper can not be autowired

Based on this answer and the comments I implemented the code to receive the scores of an elastic search query.
public class CustomizedHotelRepositoryImpl implements CustomizedHotelRepository {
private final ElasticsearchTemplate elasticsearchTemplate;
#Autowired
public CustomizedHotelRepositoryImpl(ElasticsearchTemplate elasticsearchTemplate) {
super();
this.elasticsearchTemplate = elasticsearchTemplate;
}
#Override
public Page<Hotel> findHotelsAndScoreByName(String name) {
QueryBuilder queryBuilder = QueryBuilders.boolQuery()
.should(QueryBuilders.queryStringQuery(name).lenient(true).defaultOperator(Operator.OR).field("name"));
NativeSearchQuery nativeSearchQuery = new NativeSearchQueryBuilder().withQuery(queryBuilder)
.withPageable(PageRequest.of(0, 100)).build();
DefaultEntityMapper mapper = new DefaultEntityMapper();
ResultsExtractor<Page<Hotel>> rs = new ResultsExtractor<Page<Hotel>>() {
#Override
public Page<Hotel> extract(SearchResponse response) {
ArrayList<Hotel> hotels = new ArrayList<>();
SearchHit[] hits = response.getHits().getHits();
for (SearchHit hit : hits) {
try {
Hotel hotel = mapper.mapToObject(hit.getSourceAsString(), Hotel.class);
hotel.setScore(hit.getScore());
hotels.add(hotel);
} catch (IOException e) {
e.printStackTrace();
}
}
return new PageImpl<>(hotels, PageRequest.of(0, 100), response.getHits().getTotalHits());
}
};
return elasticsearchTemplate.query(nativeSearchQuery, rs);
}
}
As you can see I needed to create a new instance of DefaultEntityMapper mapper = new DefaultEntityMapper(); which should not be the case because it should be possible to #Autowire EntityMapper. If I do so, I get the exception that there is no bean.
Description:
Field entityMapper in com.example.elasticsearch5.es.cluster.repository.impl.CustomizedCluserRepositoryImpl required a bean of type 'org.springframework.data.elasticsearch.core.EntityMapper' that could not be found.
Action:
Consider defining a bean of type 'org.springframework.data.elasticsearch.core.EntityMapper' in your configuration.
So does anybody know if its possible to autowire EntityMapper directly or does it needs to create the bean manually using #Bean annotation.
I use spring-data-elasticsearch-3.0.2.RELEASE.jar where the core package is inside.
My pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
</dependency>
I checked out the source code of spring-data-elasticsearch. There is no bean/comoponent definition for EntityMapper. It seems this answer is wrong. I test it on my project and get the same error.
Consider defining a bean of type 'org.springframework.data.elasticsearch.core.EntityMapper' in your configuration.
I couldn't find any other option by except defining a #Bean

Spring Social ProviderSignInUtils.getConnection is returning "error: cannot find symbol"

I'm creating a controller to register an user that has logged in using oauth2 but whenever I try to get the connection using ProviderSignInUtils.getConnection(request) it says the function does not exist.
This is my controller:
import org.springframework.social.connect.web.ProviderSignInUtils;
#RequestMapping(value = "/register", method = RequestMethod.GET)
public String showRegistrationForm(WebRequest request, Model model) {
Connection<?> connection = ProviderSignInUtils.getConnection(request);
RegistrationForm registration = createRegistrationDTO(connection);
model.addAttribute("user", registration);
return "user/registrationForm";
}
Those are the maven dependencies:
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-config</artifactId>
<version>1.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-core</artifactId>
<version>1.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-security</artifactId>
<version>1.1.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.social</groupId>
<artifactId>spring-social-web</artifactId>
<version>1.1.2.RELEASE</version>
</dependency>
ProviderSignInUtils.getConnection was removed in Spring Social 1.1.2, however the documentation wasn't updated to reflect this. The example code at github shows this instead
#Inject
public SignupController(AccountRepository accountRepository,
ConnectionFactoryLocator connectionFactoryLocator,
UsersConnectionRepository connectionRepository) {
this.accountRepository = accountRepository;
this.providerSignInUtils = new ProviderSignInUtils(connectionFactoryLocator, connectionRepository);
}
#RequestMapping(value="/signup", method=RequestMethod.GET)
public SignupForm signupForm(WebRequest request) {
Connection<?> connection = providerSignInUtils.getConnectionFromSession(request);
if (connection != null) {
request.setAttribute("message", new Message(MessageType.INFO, "Your " + StringUtils.capitalize(connection.getKey().getProviderId()) + " account is not associated with a Spring Social Showcase account. If you're new, please sign up."), WebRequest.SCOPE_REQUEST);
return SignupForm.fromProviderUser(connection.fetchUserProfile());
} else {
return new SignupForm();
}
}
You need to create your own local providerSignInUtils so it has access to the connectionFactoryLocator and connectionRepository.

Resources