I have my spring project war which contains Secure REST services.I need to integrate these Rest Services with swagger UI but everytime I am getting an exception like:-"HTTP-401 Full Authenticatuion required to access the resource" for my below snippet code:
This is the configuration class which load REst APIS of my project war file
#Configuration
#EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurerAdapter {
#Bean
public Docket petApi() {
This is docket class which creates swagger documentation.
return new Docket(DocumentationType.SWAGGER_2).select().apis(RequestHandlerSelectors.any()).paths(PathSelectors.any()).build()
.pathMapping("/").directModelSubstitute(LocalDate.class, String.class).genericModelSubstitutes(ResponseEntity.class);
}
}
This is the controller class which has customized method getdocumentation method which will internally invoke the spring controllers and get the documentation provided I am using springfox-swagger-ui 2.0 maven dependency.
#Controller
public class Swagger2Controller {
public static final String DEFAULT_URL = "/v2/api-docs";
#Value("${springfox.documentation.swagger.v2.host:DEFAULT}")
private String hostNameOverride;
#Autowired
private DocumentationCache documentationCache;
#Autowired
private ServiceModelToSwagger2Mapper mapper;
#Autowired
private JsonSerializer jsonSerializer;
#RequestMapping(value = { "/Vijay" }, method = { org.springframework.web.bind.annotation.RequestMethod.GET })
#ResponseBody
public ResponseEntity<Json> getDocumentation(#RequestParam(value = "group", required = false) String swaggerGroup) {
String groupName = Optional.fromNullable(swaggerGroup).or("default");
Documentation documentation = this.documentationCache.documentationByGroup(groupName);
if (documentation == null) {
return new ResponseEntity(HttpStatus.NOT_FOUND);
}
Swagger swagger = this.mapper.mapDocumentation(documentation);
swagger.host(hostName());
return new ResponseEntity(this.jsonSerializer.toJson(swagger), HttpStatus.OK);
}
private String hostName() {
if ("DEFAULT".equals(this.hostNameOverride)) {
URI uri = ControllerLinkBuilder.linkTo(Swagger2Controller.class).toUri();
String host = uri.getHost();
int port = uri.getPort();
if (port > -1) {
return String.format("%s:%d", new Object[] { host, Integer.valueOf(port) });
}
return host;
}
return this.hostNameOverride;
}
}
Any Help or suggestion will be highly appreciated. provided I have already written security as non in context.xml file of respective spring project like
<mvc:default-servlet-handler />
<mvc:resources mapping="/webjars/*" location="classpath:/META-INF/resources/webjars" />
<mvc:resources mapping="/swagger-resources/*" location="classpath:/META-INF/resources/" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />
<bean class="com.swagger.config.SwaggerConfig" />
<bean class="com.swagger.controller.Swagger2Controller" />
But still getting exception as mentioned above
Related
When I create Task in Spring Cloud Dataflow and edit properties in Spring Cloud Dataflow Dashboard I only see standard properties label despite being configured
ConfigurationProperties. And I do not know what I've set up wrongly. Below the code.
JobProps:
#Component
#ConfigurationProperties("job")
public class JobProps {
private String ux;
//getter and setter
}
JobDoing:
#Component
public class JobDoing {
public JobDoing() {
doing();
}
#Value("${job.ux:}")
private String test;
private static final Log logger = LogFactory.getLog(JobConfiguration.class);
public void doing(){
logger.info("Props: " + test);
}
}
DemoApplication:
#EnableConfigurationProperties({JobProps.class })
#EnableTask
#SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
You need to whitelist your application's custom configuration properties so that they get picked up by the Spring Cloud Data Flow server when extracting and displaying the application configuration properties.
To whitelist the configuration properties, you can refer this documentation.
<!-- Total Customer service dao facade-->
<bean id="totalCustomersDao"
class="de.hybris.training.core.dao.impl.TotalCustomersDaoImpl">
<property name="flexibleSearchService" ref="flexibleSearchService"/>
</bean>
<bean id="totalCustomerService" class=" de.hybris.training.core.impl.TotalCustomerServiceImpl">
<property name="totalCustomersDao" ref="totalCustomersDao"/>
</bean>
<bean id="totalCustomerFacade" class="de.hybris.training.core.facade.impl.TotalCustomerFacadeImpl">
<property name="totalCustomerService" ref="totalCustomerService"/>
</bean>
<bean id="usersFindJob" class=" de.hybris.training.core.job.UsersFindJob"
parent="abstractJobPerformable" >
</bean>
this is xml.
This is facade class
public class TotalCustomerFacadeImpl implements TotalCustomerFacade {
//TODO autowired or resoucre not work
private TotalCustomerService totalCustomerService ;
private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(UsersFindJob.class);
public TotalCustomerService getTotalCustomerService() {
return totalCustomerService;
}
public void setTotalCustomerService(TotalCustomerService totalCustomerService) {
this.totalCustomerService = totalCustomerService;
}
here for
private TotalCustomerService totalCustomerService ;
when i put autorwired, it says
could not autowire no beans of type found
WHen i write resource or resource(name=totalCustomerService)
it gives null pointer.
this is serviceimpl
public class TotalCustomerServiceImpl implements TotalCustomerService {
private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(UsersFindJob.class);
#Autowired
private TotalCustomersDao totalCustomersDao;
public TotalCustomersDao getTotalCustomersDao() {
return totalCustomersDao;
}
public void setTotalCustomersDao(TotalCustomersDao totalCustomersDao) {
this.totalCustomersDao = totalCustomersDao;
} public List<CustomerModel> getAllCustomersNames (String name) { LOG.info("***********************************");
LOG.info("***********************************");
LOG.info("*************************getAllCustomersNames::");
LOG.info("***********************************");
LOG.info("***********************************");
List<CustomerModel> customerModels = totalCustomersDao.findAllCustomersFromDao( name);
return customerModels;
}
those are interfaces
public interface TotalCustomerService {
List<CustomerModel> getAllCustomersNames (String name);
}
public interface TotalCustomerFacade {
List<String> findCustomerContainingName(String firstName);
}
how can i solve this?
the paths are they are all in
de.hybris.training.core
divided like
dao
facade
service
what can i do? I need to go for that service. I tried lots of times. added autowired. removed , let it without any annotations but still same.
Also this did not work
#Autowired
#Qualifier("totalCustomerService")
private TotalCustomerService totalCustomerService ;
remove whitespace! class=" de.hybris.training
Change
<bean id="totalCustomerService" class=" de.hybris.training.core.impl.TotalCustomerServiceImpl">
to
<bean id="totalCustomerService" class="de.hybris.training.core.impl.TotalCustomerServiceImpl">
it is because of whitespace
class=" de.
here
I have a web service with a property that I would like injected by Spring Framework .NET. There is no error message, and yet no injecting. What am I doing wrong?
Here is what I have for the xml file:
<object type="MyCompany.MyProject.Business.MyClass">
<property name="PaymentService" ref="PaymentService" />
</object>
Here is what I have for the code:
namespace MyCompany.MyProject.Web
{
public class MyService : WebService
{
public IPaymentService PaymentService { get; set; }
}
}
Here is what I ended up doing. We had to have an application context:
IPaymentService paymentService = (IPaymentService) SecurityHelper.GetAppContext().GetObject("PaymentService");
public static IApplicationContext GetAppContext()
{
if (WebApplicationContext.Current == null) throw new Exception("Spring not initialized");
IApplicationContext context = WebApplicationContext.Current;
if (context == null) throw new Exception("Spring context not initialized");
return context;
}
I'm attempting to inject a dependency that varies by the state passed in. For example, if the state is Wisconsin, I want to inject one class, but if it's Illinois, I want another. It's not 1-for-1, but 7 states for one and 3 for another.
Is there a way in Spring.net to have a list of values to check against in the config xml?
This is the subject of chapter 6.1 "Mapping runtime values to abstractions" of the book Dependency Injection in .NET. The solution suggested there is to use an Abstract Factory. Your abstract factory might look like:
public interface IStateAlgorithmFactory
{
IStateAlgorithm Create(string state);
}
And inject this factory on your consumer that knows which state to process. To get an IStateAlgorithm his consumer then calls y
alg = _factory.Create("Illnois");
Optionally, you could create a simple factory that maps state names to instances managed by your spring container if you want full configuration control.
Simple example
I imagine you have several classes that implement a certain IStateAlgorithm:
public interface IStateAlgorithm
{
string ProcessState(string stateName);
}
public class EchoingStateAlgorithm : IStateAlgorithm
{
public string ProcessState(string stateName)
{
return stateName;
}
}
public class ReverseEchoingStateAlgorithm : IStateAlgorithm
{
public string ProcessState(string stateName)
{
return new string(stateName.Reverse().ToArray());
}
}
And that there is a certain Consumer that needs to pick an algorithm based on a runtime value. The consumer can be injected with a factory, from which it can retrieve the algorithm it needs:
public class Consumer
{
private readonly IStateAlgorithmFactory _factory;
public Consumer(IStateAlgorithmFactory factory)
{
_factory = factory;
}
public string Process(string state)
{
var alg = _factory.Create(state);
return alg.ProcessState(state);
}
}
A simple factory implementation would simply switch on the state value, use an if, or look in internal list:
public interface IStateAlgorithmFactory
{
IStateAlgorithm Create(string state);
}
public class StateAlgorithmFactory : IStateAlgorithmFactory
{
private string[] _reverseStates = new[] {"Wisconsin", "Alaska"};
public IStateAlgorithm Create(string state)
{
if(_reverseStates.Contains(state))
return new ReverseEchoingStateAlgorithm();
return new EchoingStateAlgorithm();
}
}
Spring.Net Configurable example
If you would like to be able to configure your IStateAlgorithm in your spring configuration, you can introduce a LookupStateAlgorithmFactory. This example assumes that your IStateAlgorithms are stateless and can be shared among consumers:
public class LookupStateAlgorithmFactory : IStateAlgorithmFactory
{
private readonly IDictionary<string, IStateAlgorithm> _stateToAlgorithmMap;
private readonly IStateAlgorithm _defaultAlgorithm;
public LookupStateAlgorithmFactory(IDictionary<string, IStateAlgorithm> stateToAlgorithmMap,
IStateAlgorithm defaultAlgorithm)
{
_stateToAlgorithmMap = stateToAlgorithmMap;
_defaultAlgorithm = defaultAlgorithm;
}
public IStateAlgorithm Create(string state)
{
IStateAlgorithm alg;
if (!_stateToAlgorithmMap.TryGetValue(state, out alg))
alg = _defaultAlgorithm;
return alg;
}
}
The xml config could be:
<object id="lookupFactory"
type="LookupStateAlgorithmFactory, MyAssembly">
<constructor-arg ref="echo" />
<constructor-arg>
<dictionary key-type="string" value-type="IStateAlgorithm, MyAssembly">
<entry key="Alaska" value-ref="reverseEcho"/>
<entry key="Wisconsin" value-ref="reverseEcho"/>
</dictionary>
</constructor-arg>
</object>
<object id="echo" type="EchoingStateAlgorithm, MyAssembly" />
<object id="reverseEcho" type="ReverseEchoingStateAlgorithm, MyAssembly" />
I wrote a small service class which return a list with 1000 strings.
I am using Spring Httpinvoker to get the service and read the list. If the number of the elements in the list is 100 all is going well when
I try 1000 it freeze utill there is a connection reset
The client side is JUnit 4 class with Spring runner on the same machine
by the way the same is happening with Hessian protocol using the Spring Remoting classes.
They are both HTML based but this is the only connection I can see RMI and JMS RMI (thorugh Spring remoting) is working fine with the same service
The service code
public class DateServiceImpl implements DateService {
/* (non-Javadoc)
* #see com.successcharging.rmiexample.DateService#getDate()
*/
#Override
public Date getDate() {
return new Date();
}
#Override
public List<String> getBigList() {
List<String> listData = new ArrayList<String>();
for (int i = 0 ; i < 100;i++) {
listData.add(Math.random()+"");
}
return listData;
}
}
The mapping server side
<!-- The service to use this is the server side -->
<bean id="dateServiceServer" class="com.successcharging.rmiexample.server.DateServiceImpl" />
<!-- the http invoker protocol -->
<bean name="/DateServiceHttpInvoker"
class="org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter">
<property name="service" ref="dateServiceServer" />
<property name="serviceInterface"
value="com.successcharging.rmiexample.server.DateService" />
</bean>
The client mapping
The junit code
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration
public class DateServiceTest extends BaseTest {
#Resource
private DateService dateServiceHttpInvokerClient;
#Test
public void testDateServiceHttpInvoker() {
List<String> data = dateServiceHttpInvokerClient.getBigList(); //Here it is get stuck
data.add("My test");
System.out.println("HttpInvoker:"
+ data.size());
}
public DateService getDateServiceHttpInvokerClient() {
return dateServiceHttpInvokerClient;
}
public void setDateServiceHttpInvokerClient(
DateService dateServiceHttpInvoker) {
this.dateServiceHttpInvokerClient = dateServiceHttpInvoker;
}
}
Any ideas ?