ClassCastException When Trying to Make JAXRS Call in Errai 4 - gwt

I am using Errai 4.0.0.Beta1, and I am trying to make a simple JAX RS call.
Here is the code I am using:
final RemoteCallback<List<Company>> remoteCallback = new RemoteCallback<List<Company>>() {
#Override
public void callback(List<Company> companies) {
Window.alert("rpcServiceCaller - Callback");
Window.alert("Number of companies returned: " + companies.size());
}
};
final RestErrorCallback errorCallback = new RestErrorCallback() {
#Override
public boolean error(Request message, Throwable throwable) {
Window.alert(throwable.getMessage());
logger.error(throwable.getMessage(), throwable);
return false;
}
};
RestClient.create(ErraiJAXRSService.class,
remoteCallback,
errorCallback,
200).getCompaniesJSON();
I am seeing the following exception in Super Dev Mode:
Error caused by: ClassCastException: undefined
at f9b_g$ [as collect_0_g$] (StackTraceCreator.java:198)
at H8b_g$ (StackTraceCreator.java:343)
at Iz_g$ [as fillInStackTrace_0_g$] (Throwable.java:114)
at Bz_g$ (Throwable.java:53)
at Xz_g$ (Exception.java:25)
at cA_g$ (RuntimeException.java:25)
at Ymb_g$ (ClassCastException.java:23)
at Mzg_g$ (InternalPreconditions.java:45)
at Xzg_g$ (InternalPreconditions.java:33)
at n1d_g$ (Cast.java:75)
at rrh_g$ (RestClient.java:192)
at srh_g$ (RestClient.java:158)
at wrh_g$ (RestClient.java:113)
at ynf_g$ [as erraiJSON_0_g$] (JAXRSPage.java:94)
at gKh_g$ [as onClick_0_g$] (Type_factory__c_i_e_c_j_JAXRSPage__quals__j_e_i_Any_j_e_i_Default.java:76)
at Exd_g$ [as dispatch_4_g$] (ClickEvent.java:56)
at Fxd_g$ [as dispatch_1_g$] (ClickEvent.java:55)
at Awd_g$ [as dispatch_0_g$] (GwtEvent.java:76)
at ZGd_g$ (EventBus.java:40)
at iHd_g$ [as doFire_0_g$] (SimpleEventBus.java:193)
at oHd_g$ [as fireEvent_2_g$] (SimpleEventBus.java:88)
at RGd_g$ [as fireEvent_1_g$] (HandlerManager.java:127)
at Lve_g$ [as fireEvent_1_g$] (Widget.java:129)
at Lwd_g$ (DomEvent.java:125)
at Tve_g$ [as onBrowserEvent_0_g$] (Widget.java:177)
at gne_g$ (DOM.java:1480)
at fne_g$ (DOM.java:1419)
at HTMLButtonElement.xte_g$ (DOMImplStandard.java:317)
at k6b_g$ (Impl.java:233)
at n6b_g$ (Impl.java:285)
at HTMLButtonElement.<anonymous> (Impl.java:71)
The proxy is returned, but any line that attempts to cast it to an AbstractJaxrsProxy fails with the above exception.
The JaxrsProxyLoaderImpl.java has been created, and my JAX RS Service is there:
package org.jboss.errai.enterprise.client.jaxrs;
import com.google.gwt.http.client.RequestBuilder;
import com.insclix.erraiPOC.shared.domain.Company;
import com.insclix.erraiPOC.shared.service.jaxrs.ErraiJAXRSService;
import java.util.List;
import org.jboss.errai.common.client.api.ErrorCallback;
import org.jboss.errai.common.client.api.RemoteCallback;
import org.jboss.errai.common.client.framework.ProxyProvider;
import org.jboss.errai.common.client.framework.RemoteServiceProxyFactory;
import org.jboss.errai.security.client.local.interceptors.SecurityExceptionMapper;
public class JaxrsProxyLoaderImpl implements JaxrsProxyLoader { public void loadProxies() {
class com_insclix_erraiPOC_shared_service_jaxrs_ErraiJAXRSServiceImpl extends AbstractJaxrsProxy implements ErraiJAXRSService {
private RemoteCallback remoteCallback;
private ErrorCallback errorCallback;
public com_insclix_erraiPOC_shared_service_jaxrs_ErraiJAXRSServiceImpl() {
setExceptionMapper(new SecurityExceptionMapper());
}
public RemoteCallback getRemoteCallback() {
return remoteCallback;
}
public void setRemoteCallback(RemoteCallback callback) {
remoteCallback = callback;
}
public ErrorCallback getErrorCallback() {
return errorCallback;
}
public void setErrorCallback(ErrorCallback callback) {
errorCallback = callback;
}
public List getCompaniesJSON() {
StringBuilder url = new StringBuilder(getBaseUrl());
url.append("company/jaxrs");
RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, url.toString());
requestBuilder.setHeader("Accept", "application/json");
sendRequest(requestBuilder, null, new ResponseDemarshallingCallback() {
public Object demarshallResponse(String response) {
return MarshallingWrapper.fromJSON(response, List.class, Company.class);
}
});
return null;
}
public List getCompaniesXML() {
StringBuilder url = new StringBuilder(getBaseUrl());
url.append("company/jaxrs");
RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.GET, url.toString());
requestBuilder.setHeader("Accept", "application/xml");
sendRequest(requestBuilder, null, new ResponseDemarshallingCallback() {
public Object demarshallResponse(String response) {
return MarshallingWrapper.fromJSON(response, List.class, Company.class);
}
});
return null;
}
public Long createCompanyJSON(final Company a0) {
StringBuilder url = new StringBuilder(getBaseUrl());
url.append("company/jaxrs");
RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, url.toString());
requestBuilder.setHeader("Content-Type", "application/json");
sendRequest(requestBuilder, MarshallingWrapper.toJSON(a0), new ResponseDemarshallingCallback() {
public Object demarshallResponse(String response) {
return MarshallingWrapper.fromJSON(response, Long.class, null);
}
});
return 0L;
}
public Long createCompanyXML(final Company a0) {
StringBuilder url = new StringBuilder(getBaseUrl());
url.append("company/jaxrs");
RequestBuilder requestBuilder = new RequestBuilder(RequestBuilder.POST, url.toString());
requestBuilder.setHeader("Content-Type", "application/xml");
sendRequest(requestBuilder, MarshallingWrapper.toJSON(a0), new ResponseDemarshallingCallback() {
public Object demarshallResponse(String response) {
return MarshallingWrapper.fromJSON(response, Long.class, null);
}
});
return 0L;
}
}
RemoteServiceProxyFactory.addRemoteProxy(ErraiJAXRSService.class, new ProxyProvider() {
public Object getProxy() {
return new com_insclix_erraiPOC_shared_service_jaxrs_ErraiJAXRSServiceImpl();
}
});
}
}

This turned out to be an issue with the way JAX-RS / Errai class and interface were configured. According to the JAX-RS specification, the #Path annotation needs to be on the implementation, but Errai needs it on the interface.
So, the solution was to have the #Path annotation on BOTH the interface (for Errai), and the class that implements it (for JAX-RS).
Note that if the annotation is on the interface, Wildfly allows for this, Jersey ignores the interface, and Resteasy fails (if running through the ResteasyServletInitializer.

Related

Retrofit with soap api

I am trying to create Retrofit instance with the soap API. But I don't have an idea how to create. I have checked all the websites. I have got the code for creating the Retrofit instance with Rest API.
Also, I am having WSDL file. I am able to create required POJO class with that but I don't know how to use for a service call.
Kindly anyone please suggest some code or how to use that.
For Rest call, I am creating Retrofit instance like
#GET("users/{user}/repos")
Call<List<User>> listUsers(#Path("user") String user);
You should first make ApiClient class as follow:
public class ApiClient {
public static final String BASE_URL = "http://54.255.249.65/socialcommerce/rest/V1/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
In the controller class you should use the above class as follow:
ApiInterface apiInterface = ApiClientInstagram.getClient().create(ApiInterface.class);
Call<InstagramDetail> call = apiInterface.getInstagramDetail(token);
Log.d("tag", call.request().url().toString());
call.enqueue(new Callback<InstagramDetail>() {
#Override
public void onResponse(Call<InstagramDetail> call, Response<InstagramDetail> response) {
String code = String.valueOf(response.code());
if (code.equals("200")) {
response.body();
} else {
Toast.makeText(getApplicationContext(), "Backend Error", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<InstagramDetail> call, Throwable t) {
Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
}
});

CSRF token validation failed in Odata4j

I'm trying to post the entry to Odata service Url which is created in SAP ABAP backend. When i'm trying to send the data from java code to SAP ABAP system via Odata service, I'm getting CSRF Token validation error. Below is the code snippet for Odata Post service
ODataConsumer.Builder builder = ODataConsumers.newBuilder(URL_ODATASERVICE);
// LOGGER.info(TAG+"Authentication values are been set");
builder.setClientBehaviors(new BasicAuthenticationBehavior(USERNAME, PASSWORD), new SAPCSRFBehavior());
ODataConsumer consumer = builder.build();
OCreateRequest<OEntity> createRequest = consumer.createEntity("LogSet")
.properties(OProperties.string("TestplanId", "111")).properties(OProperties.string("ProcessId", "222"))
.properties(OProperties.string("Seqno", "33"));
// Execute the OData post
OEntity newMaterial = createRequest.execute();
And the SAPSCRBehaviour class will be
public class SAPCSRFBehaviour implements JerseyClientBehavior {
private static final String CSRF_HEADER = "X-CSRF-Token";
private static final String SAP_COOKIES = "SAP_SESSIONID";
private String xsrfCookieName;
private String xsrfCookieValue;
private String xsrfTokenValue;
#Override
public ODataClientRequest transform(ODataClientRequest request) {
if (request.getMethod().equals("GET")) {
request = request.header(CSRF_HEADER, "Fetch");
return request;
} else {
return request.header(CSRF_HEADER, xsrfTokenValue).header("Cookie", xsrfCookieName + "=" + xsrfCookieValue);
}
}
#Override
public void modifyWebResourceFilters(final Filterable arg0) {
}
#Override
public void modifyClientFilters(final Filterable client) {
client.addFilter(new ClientFilter() {
#Override
public ClientResponse handle(final ClientRequest clientRequest) throws ClientHandlerException {
ClientResponse response = getNext().handle(clientRequest);
List<NewCookie> cookies = response.getCookies();
for (NewCookie cookie : cookies) {
if (cookie.getName().startsWith(SAP_COOKIES)) {
xsrfCookieName = cookie.getName();
xsrfCookieValue = cookie.getValue();
break;
}
}
MultivaluedMap<String, String> responseHeaders = response.getHeaders();
xsrfTokenValue = responseHeaders.getFirst(CSRF_HEADER);
return response;
}
});
}
#Override
public void modify(final ClientConfig arg0) {
}}
Please suggest me the solution to avoid this issue
Best Regards,
Naveen

Could Not autowire an object in Mule component

I am trying to autowire an object of a service class in mule flow. The code is:
public class SignatureValidator implements Callable
{
#Autowired
private TriggerHostServiceImpl triggerHostServiceImpl;
#Override
public Object onCall(MuleEventContext eventContext) throws Exception
{
MuleMessage message = eventContext.getMessage();
message = fetchPropertiesAndValidateMessageSignature(message);
return message.getPayload();
}
private MuleMessage fetchPropertiesAndValidateMessageSignature(MuleMessage message) throws GeneralSecurityException, IOException
{
String muleWSTriggerLabel = message.getInboundProperty("triggerLabel");
String muleWSSignature = message.getInboundProperty("signature");
String muleWSExpiresOn = message.getInboundProperty("expiresOn");
String xmlData = message.getInboundProperty("xmlData");
String appHostName = InitConfigurationLoader.getConfigSetting("applicationHostingName");
Trigger triggerJaxbObject = (Trigger) message.getPayload();
String applicationIdentifier = triggerJaxbObject.getApplicationIdentifier();
TriggerMapper triggerMapper = FetchConfigurationEntities.getTriggerMapper(applicationIdentifier, muleWSTriggerLabel);
String reportEmail = FetchConfigurationEntities.getReportEmail(triggerMapper);
ImportDetails importInstance = FetchConfigurationEntities.getImport(triggerMapper);
String importInstanceURL = importInstance.getWebserviceURL();
message.setInvocationProperty("triggerJaxbObject", triggerJaxbObject);
message.setInvocationProperty("importInstance", importInstance);
message.setInvocationProperty("reportEmail", reportEmail);
message.setInvocationProperty("appIdentifier", applicationIdentifier);
message.setInvocationProperty("importHost", importInstanceURL.substring(importInstanceURL.lastIndexOf('/')+1, importInstanceURL.length()));
setPayloadAfterValidation(message, muleWSTriggerLabel, xmlData, muleWSSignature, appHostName, muleWSExpiresOn);
return message;
}
My service class is:
package com.catalystone.csi.service;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.catalystone.csi.core.cache.UpdateCacheable;
import com.catalystone.csi.dao.TriggerHostDao;
import com.catalystone.csi.model.TriggerHost;
#Service
public class TriggerHostServiceImpl implements TriggerHostService
{
#Autowired
private TriggerHostDao triggerHostDao;
#Autowired
private UpdateCacheable updateCacheable;
/**
* Method to save mule configurations i.e. TriggerHosts
*/
#Override
#Transactional
public boolean saveTriggerHost(TriggerHost triggerHost)
{
if(triggerHostDao.saveTriggerHost(triggerHost))
{
Map<String, TriggerHost> allTriggerHosts = getAllTriggerHosts();
allTriggerHosts.put(triggerHost.getTriggerIdentifier(), triggerHost);
updateCacheable.updateAllTriggerHostCache(allTriggerHosts);
return true;
}
else
return false;
}
/**
* Method to fetch all the configurations
*/
#Override
#Transactional//this annotation is used to maintain transaction
public Map<String, TriggerHost> getAllTriggerHosts()
{
return triggerHostDao.getAllTriggerHosts();
}
/**
* Method to delete mule configuration for triggerHost
* #return - true if delete configuration is successfully done
*/
#Override
#Transactional//this annotation is used to maintain transaction
public Boolean deleteConfiguration(TriggerHost triggerHost, boolean isMultipleImportOccurrence)
{
Boolean isDeleteSuccessful = triggerHostDao.deleteConfiguration(triggerHost, isMultipleImportOccurrence);
//Getting all the configurations from cache
Map<String, TriggerHost> allTriggerHosts = getAllTriggerHosts();
//check if delete configuration successful then remove that configuration from cache
if(isDeleteSuccessful)
{
for(Entry<String, TriggerHost> triggerHostEntry : allTriggerHosts.entrySet())
{
if(triggerHostEntry.getValue().getTriggerIdentifier().equals(triggerHost.getTriggerIdentifier()))
{
allTriggerHosts.remove(triggerHostEntry.getKey());
break;
}
}
//update cache
updateCacheable.updateAllTriggerHostCache(allTriggerHosts);
return true;
}
return false;
}
#Override
#Transactional
public Boolean updateConfiguration(TriggerHost triggerHost)
{
if(triggerHostDao.updateConfiguration(triggerHost))
{
Map<String, TriggerHost> allTriggerHosts = getAllTriggerHosts();
allTriggerHosts.put(triggerHost.getTriggerIdentifier(), triggerHost);
updateCacheable.updateAllTriggerHostCache(allTriggerHosts);
return true;
}
return false;
}
#Override
#Transactional
public Boolean deleteConfiguration(String existingImportIdentifier)
{
return triggerHostDao.deleteConfiguration(existingImportIdentifier);
}
}
when I run this code then value of triggerHostServiceImpl is always null. How to autowire? I have also tried a link Dependency Injection is working at Mule application startup. Objects are getting null, when a request received and Failing by throwing NullEx
and
Spring3 Dependency Injection not working with mule
but then it is giving me so many exception that I couldn't get.
you have to Autowire the Interface not the Implementation
#Autowired
private TriggerHostService triggerHostService;
and add the setter and getter of triggerHostService

spring data mongodb converter

I am using spring data mongo-db 1.4.1.RELEASE.
My entity 'Event' has a getter method which is calculated based on other properties:
public int getStatus() {
return (getMainEventId() == null) ? (elapseTimeInMin() < MINIMUM_TIME ? CANDIDATE :
VALID) : POINTER;
}
I wanted the property 'status' to be persisted only through the getter ,so I wrote converters:
#WritingConverter
public class EventWriteConverter implements Converter<Event ,BasicDBObject > {
static final Logger logger = LoggerFactory.getLogger(EventWriteConverter.class.getCanonicalName());
public BasicDBObject convert(Event event) {
logger.info("converting " +event );
if (event.getMainEventId() != null)
return new BasicDBObject("mainEventId", event.getMainEventId() );
BasicDBObject doc = new BasicDBObject("status",event.getStatus()).
append("updated_date",new Date()).
append("start",event.getS0()).
append("end",event.getS1()).
append("location",event.getLocation()).
;
BasicDBList list = new BasicDBList();
doc.append("access_points",event.getHotPoints());
return doc;
}
#ReadingConverter
public class EventReadConverter implements Converter<BasicDBObject, Event> {
#Inject
HotPointRepositry hotRepositry;
static final Logger logger = LoggerFactory.getLogger(EventReadConverter.class.getCanonicalName());
public Event convert(BasicDBObject doc) {
logger.info(" converting ");
Event event = new Event();
event.setId(doc.getObjectId("_id"));
event.setS0(doc.getDate("start"));
event.setS1(doc.getDate("end"));
BasicDBList dblist = (BasicDBList) doc.get("hot_points");
if (dblist != null) {
for (Object obj : dblist) {
ObjectId hotspotId = ((BasicDBObject) obj).getObjectId("_id");
event.addHot(hotRepositry.findOne(hotId));
}
}
dblist = (BasicDBList) doc.get("devices");
if (dblist != null) {
for (Object obj : dblist)
event.addDevice(obj.toString());
}
event.setMainEventId(doc.getObjectId("mainEventId"));
return event;
}
}
My test mongo configuration is
#Profile("test")
#Configuration
#EnableMongoRepositories(basePackages = "com.echo.spring.data.mongo")
#ComponentScan(basePackages = "com.echo.spring.data.mongo" )
public class MongoDbTestConfig extends AbstractMongoConfiguration {
static final Logger logger = LoggerFactory.getLogger(MongoDbTestConfig.class.getCanonicalName());
#Override
protected String getDatabaseName() {
return "echo";
}
#Override
public Mongo mongo() {
return new Fongo("echo-test").getMongo();
}
#Override
protected String getMappingBasePackage() {
return "com.echo.spring.data.mongo";
}
#Bean
#Override
public CustomConversions customConversions() {
logger.info("loading custom converters");
List<Converter<?, ?>> converterList = new ArrayList<Converter<?, ?>>();
converterList.add(new EventReadConverter());
converterList.add(new EventWriteConverter());
CustomConversions cus = new CustomConversions(converterList);
return new CustomConversions(converterList);
}
}
And my test (using fongo) is
ActiveProfiles("test")
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = MongoDbTestConfig.class )
public class SampleMongoApplicationTests {
#Test
#ShouldMatchDataSet(location = "/MongoJsonData/events.json")
public void shouldSaveEvent() throws IOException {
URL url = Resources.getResource("MongoJsonData/events.json");
List<String> lines = Resources.readLines(url,Charsets.UTF_8);
for (String line : lines) {
Event event = objectMapper.readValue(line.getBytes(),Event.class);
eventRepository.save(event);
}
}
I can see the converters are loaded when the configuration customConversions() is called
I added logging and breakpoints in the convert methods but they do not seems to be
called when I run or debug, though they are loaded .
What am I doing wrong ?
I had a similar situation, I followed Spring -Mongodb storing/retrieving enums as int not string
and I need both the converter AND converterFactory wired to get it working.

ServletRequestListener - Getting the userprincipal returns null

I'm having a web-application that is secured with HTTP-Basic auth.
I also implemented a filter using the ServletRequestListener interface. Now when the filter calls the requestInitialized method, the getUserPrincipal-Method of the request returns null. But when I check the request headers, the authorization-header is set with the encrypted value. Here's the code:
#Override
public void requestInitialized(ServletRequestEvent e) {
HttpServletRequest request = (HttpServletRequest) e.getServletRequest();
//p is null
Principal p = request.getUserPrincipal();
Enumeration<String> enH = request.getHeaders("Authorization");
while (enH.hasMoreElements()) {
String s = enH.nextElement();
System.out.println(s);
//prints.
//Basic c3RhY2tvdmVyZmxvdzpteXBhc3N3b3Jk
}
}
Why is the userprincipal not initialized?
You are likely not setting up the needed security layers for embedded-jetty.
Here's an example found in the Jetty embedded examples source tree.
package org.eclipse.jetty.embedded;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.jetty.security.ConstraintMapping;
import org.eclipse.jetty.security.ConstraintSecurityHandler;
import org.eclipse.jetty.security.HashLoginService;
import org.eclipse.jetty.security.LoginService;
import org.eclipse.jetty.security.authentication.BasicAuthenticator;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.util.security.Constraint;
public class SecuredHelloHandler
{
public static void main(String[] args) throws Exception
{
Server server = new Server(8080);
LoginService loginService = new HashLoginService("MyRealm","src/test/resources/realm.properties");
server.addBean(loginService);
ConstraintSecurityHandler security = new ConstraintSecurityHandler();
server.setHandler(security);
Constraint constraint = new Constraint();
constraint.setName("auth");
constraint.setAuthenticate( true );
constraint.setRoles(new String[]{"user", "admin"});
ConstraintMapping mapping = new ConstraintMapping();
mapping.setPathSpec( "/*" );
mapping.setConstraint( constraint );
Set<String> knownRoles = new HashSet<String>();
knownRoles.add("user");
knownRoles.add("admin");
security.setConstraintMappings(Collections.singletonList(mapping), knownRoles);
security.setAuthenticator(new BasicAuthenticator());
security.setLoginService(loginService);
security.setStrict(false);
// Your Handler (or Servlet) that should be secured
HelloHandler hh = new HelloHandler();
security.setHandler(hh);
server.start();
server.join();
}
}
I solved it by using a Filter instead of a Listener..
#WebFilter(urlPatterns = { "/*" })
public class RequestFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse res,
FilterChain fChain) throws IOException, ServletException {
HttpServletRequest hReq = (HttpServletRequest) req;
//p is not null anymore
Principal p = hReq.getUserPrincipal();
fChain.doFilter(hReq, res);
}
#Override
public void destroy() {
}
#Override
public void init(FilterConfig config) throws ServletException {
}
}