HttpInvoker get choked when trying to return a list with 1000 elements - hessian

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 ?

Related

Spring Dataflow not display properties

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.

could not autowire no beans of type found, for service in hybris

<!-- 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

How to integrate swaggerUI with spring secure Rest services?

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

Spring.net IoC - Vary injected class by state

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" />

Lazy loading exception when using JSF Converter (refering to a collection)

This is my first post after many research on this problem.
This example is running under Jboss 7.1 with seam 3.1 (solder + persistence + faces) with seam managed persistence context
I'm facing a problem, the classical failed to lazily initialize a collection, no session or session was closed: org.hibernate.LazyInitializationException: failed to lazily initialize a collection, no session or session was closed when using a converter on Entity beans. The aim is to stay 100% Object oriented, by reusing the JPA model.
in beans.xml, org.jboss.seam.transaction.TransactionInterceptor is activated
Entity beans :
#Entity
public class Member implements Serializable {
#Id
#GeneratedValue
private Long id;
private String name;
private String email;
#Column(name = "phone_number")
private String phoneNumber;
#ManyToMany
private List<Statut> listeStatut = new ArrayList<Statut>();
// getters, setters, hashcode, equals
}
#Entity
public class Statut implements Serializable {
#Id
#GeneratedValue
private Long id;
private String name;
#ManyToMany(mappedBy="listeStatut")
private List<Member> members = new ArrayList<Member>();
// getters, setters, hashcode, equals
}
The JSF page :
<h:form>
<h:selectManyCheckbox id="stat" value="#{memberModif.member.listeStatut}">
<f:converter converterId="statutConverter"/>
<f:selectItems value="#{memberModif.statutsPossibles}" var="statut" itemValue="#{statut}" itemLabel="#{statut.name}" />
</h:selectManyCheckbox>
<h:commandLink id="register" action="#{memberModif.modifier()}" value="Modifier">
<f:param name="cid" value="#{javax.enterprise.context.conversation.id}"/>
</h:commandLink>
</h:form>
The backing bean (I tried with ConversationScoped after SessionScoped --> same problem)
#ConversationScoped
#Named
public class MemberModif implements Serializable {
private static final long serialVersionUID = -291355942822086126L;
#Inject
private Logger log;
#Inject
private EntityManager em;
#Inject Conversation conversation;
private Member member;
#SuppressWarnings("unused")
#PostConstruct
private void init() {
if (conversation.isTransient()) {
conversation.begin();
}
}
public String modifier() {
em.merge(member);
}
public Member getMember() {
if (member == null) {
member = em.createQuery("from Member m where m.id=:id",Member.class).setParameter("id", new Long(0)).getSingleResult();
}
return member;
}
public List<Statut> getStatutsPossibles() {
return em.createQuery("from Statut", Statut.class).getResultList();
}
}
And the converter (strongly inspired by seam ObjectConverter) :
#FacesConverter("statutConverter")
public class StatutConverter implements Converter, Serializable {
final private Map<String, Statut> converterMap = new HashMap<String, Statut>();
final private Map<Statut, String> reverseConverterMap = new HashMap<Statut, String>();
#Inject
private transient Conversation conversation;
private final transient Logger log = Logger.getLogger(StatutConverter.class);
private int incrementor = 1;
#Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
if (this.conversation.isTransient()) {
log.warn("Conversion attempted without a long running conversation");
}
return this.converterMap.get(value);
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (this.conversation.isTransient()) {
log.warn("Conversion attempted without a long running conversation");
}
if (this.reverseConverterMap.containsKey(value)) {
return this.reverseConverterMap.get(value);
} else {
final String incrementorStringValue = String.valueOf(this.incrementor++);
this.converterMap.put(incrementorStringValue, (Statut)value);
this.reverseConverterMap.put( (Statut)value, incrementorStringValue);
return incrementorStringValue;
}
}
}
Please note that I put this converter here to avoid you searching over the net for the seam implementation, but it is the same as using <s:objectConverter/> tag instead of <f:converter converterId="statutConverter"/>
Any help would be greetly appreciated.
You should access the objects in the same transaction. If you are sure you are doing that already, you could try getting the entitymanager by looking it up in the context instead of injecting it. Ive had a simular problem which was resolved that way. You can also initialize the collection in the transaction when you first got your reference to it.
Hibernate.initialize(yourCollection);
Take a look at this: selectManyCheckbox LazyInitializationException on process validation
Try:
<f:attribute name="collectionType" value="java.util.ArrayList" />;
on your <h:selectManyCheckbox>

Resources