We have overwritten AbstractDestinationFacade with our implementation of DestinationFacade and Destination. When we try to connect over this destination we get a runtime Exception from Guava cache
Our use case:: We are trying to connect to remote systems from NonCF platforms.
Our Local Implementations are as shown below
LocalDestinationFacade
public class LocalDestinationFacade extends AbstractDestinationFacade {
#Override
public Class<? extends GenericDestination> getGenericDestinationClass() {
// TODO Auto-generated method stub
return null;
}
#Override
public Class<? extends Destination> getDestinationClass() {
// TODO Auto-generated method stub
return LocalDestination.class;
}
#Override
public Class<? extends RfcDestination> getRfcDestinationClass() {
// TODO Auto-generated method stub
return null;
}
#Override
public Map<String, GenericDestination> getGenericDestinationsByName() throws DestinationAccessException {
Destination localDestination=new LocalDestination("AniPremise", "https://custom-backend-corp/",AuthenticationType.BASIC_AUTHENTICATION,new BasicCredentials("adas", "adas"));
Map<String, GenericDestination> destinations=new HashMap<>();
destinations.put("AniPremise", localDestination);
return destinations;
}
}
LocalDestination
public class LocalDestination extends AbstractDestination {
public LocalDestination(String name, String description, String uri, AuthenticationType authenticationType,
BasicCredentials basicCredentials, ProxyType proxyType, ProxyConfiguration proxyConfiguration,
boolean isTrustingAllCertificates, String trustStoreLocation, String trustStorePassword,
String keyStoreLocation, String keyStorePassword, Map<String, String> propertiesByName) {
super(name, description, uri, authenticationType, basicCredentials, proxyType, proxyConfiguration,
isTrustingAllCertificates, trustStoreLocation, trustStorePassword, keyStoreLocation, keyStorePassword,
propertiesByName);
}
public LocalDestination(String name,String uri) {
this(name, null, uri, null, null, null, null, true, null, null, null, null, Collections.emptyMap());
}
public LocalDestination(String name,String uri,AuthenticationType authenticationType,BasicCredentials basicCredentials) {
this(name, null, uri, authenticationType, basicCredentials,ProxyType.INTERNET , null, false, null, null, null, null, Collections.emptyMap());
}
#Override
public Optional<KeyStore> getTrustStore() throws DestinationAccessException {
return null;
}
#Override
public Optional<KeyStore> getKeyStore() throws DestinationAccessException {
return null;
}
}
The following stacktrace is produced when we query against the destination.
com.google.common.util.concurrent.UncheckedExecutionException: java.lang.NullPointerException
at com.google.common.cache.LocalCache$Segment.get(LocalCache.java:2051)
at com.google.common.cache.LocalCache.get(LocalCache.java:3953)
at com.google.common.cache.LocalCache$LocalManualCache.get(LocalCache.java:4873)
at com.sap.cloud.sdk.cloudplatform.connectivity.HttpClientCache.getHttpClient(HttpClientCache.java:51)
at com.sap.cloud.sdk.cloudplatform.connectivity.HttpClientAccessor.getHttpClient(HttpClientAccessor.java:148)
at com.sap.cloud.sdk.cloudplatform.connectivity.HttpClientAccessor.getHttpClient(HttpClientAccessor.java:128)
at com.sap.cloud.sdk.odatav2.connectivity.ODataQuery.internalExecute(ODataQuery.java:242)
at com.sap.cloud.sdk.odatav2.connectivity.ODataQuery.execute(ODataQuery.java:178)
at com.sap.cloud.sdk.odatav2.connectivity.ODataQuery.execute(ODataQuery.java:227)
at com.sap.cloud.sdk.odatav2.connectivity.ODataQuery.execute(ODataQuery.java:201)
at com.sap.cloud.sdk.s4hana.datamodel.odata.helper.FluentHelperRead.execute(FluentHelperRead.java:244)
at com.sap.gb.s4backend.dataprovider.S4HanaDataProviderImpl.getPurchaseRequisitionWorkList(S4HanaDataProviderImpl.java:473)
at com.sap.gb.odata.provisioning.GBOdataRequestProcessor.readEntitySet(GBOdataRequestProcessor.java:102)
Related
how can i solve null object while sending post request
error says
to invoke interface method 'retrofit2.Call com.itgrepnet.foodbundle.remote.UserService.addUser(com.itgrepnet.foodbundle.model.User)' on a null object reference
in AddUserActivity
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addNewUser();
}
private void addNewUser() {
User u = new User();
u.setFirstname(first_name.getText().toString());
u.setLastname(last_name.getText().toString());
u.setEmail(email.getText().toString());
u.setPassword(password.getText().toString());
Call<User> call = userService.addUser(u);
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Call<User> call, Response<User> response) {
if (response.isSuccessful()) {
Toast.makeText(getApplicationContext(), "User Created Successfully!", Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<User> call, Throwable t) {
Log.e("Error: ", t.getMessage());
}
});
}
});
UserService.java
#POST("user/")
Call<User> addUser(#Body User user);
RetrofitClient.java
public class RetrofitClient {
private static Retrofit retrofit = null;
public static Retrofit getClient(String url) {
if (retrofit == null) {
retrofit = new Retrofit.Builder().baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
I do not why my private variable values are getting to null after the Volley request
When i am printing the values in onResponse, i am getting required values, but after volley request is completed, I am getting null.
ListView userListView;
StringRequest stringRequest=null;
ProgressDialog progressDialog;
private String[] strUsername;
private String[] strUserItems;
private String[] strUserImagePaths;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_listing);
userListView=findViewById(R.id.userListView);
progressDialog=new ProgressDialog(this);
StrictMode.setThreadPolicy((new StrictMode.ThreadPolicy.Builder().permitNetwork().build()));
displayUserListing();
UserListCustomViewAdapter viewAdapter=new UserListCustomViewAdapter(this,strUsername,strUserImagePaths,strUserItems);
userListView.setAdapter(viewAdapter);
}
private void displayUserListing()
{
progressDialog.setMessage("Getting User List...");
progressDialog.show();
stringRequest=new StringRequest(
Request.Method.GET, Constants.URL_GetUserList, new Response.Listener<String>()
{
#Override
public void onResponse(String response)
{
progressDialog.dismiss();
try {
Log.d("first","before");
JSONArray jsonObj=new JSONArray(response);
strUsername=new String[jsonObj.length()];
strUserItems=new String[jsonObj.length()];
strUserImagePaths=new String[jsonObj.length()];
String str=null;
for(int i=0;i<jsonObj.length();i++)
{
JSONObject jsonObject=jsonObj.getJSONObject(i);
strUsername[i]=jsonObject.getString("user_name");
strUserItems[i]=jsonObject.getString("user_item");
strUserImagePaths[i]=jsonObject.getString("user_image_path");
str+=strUsername[i];
}
Log.d("first","after"+str);
}catch (Exception e)
{
e.printStackTrace();
}
}
}, new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error)
{
progressDialog.hide();
Log.d("myerror","I got some error");
NetworkResponse networkResponse = error.networkResponse;
Log.d("myerror1",error.getMessage());
// Toast.makeText(getApplicationContext(),error.getMessage().toString(),Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String,String> params=new HashMap<String,String>();
params.put("struserid","1");
//params.put("serviceid","1");
return params;
}
};
RequestHandler.getInstance(this).addToRequestQueue(stringRequest);
}
I think you are using your variables before initializing it. Call the adapter after you parsing value.
I am trying to hit the api : www.xyz.com/abc_cc/cc/userregister/newuser
This is my Code :
public class MainActivity extends AppCompatActivity {
public static final String BASE_URL = "abc.com/abc_cc/cc/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(getUnsafeOkHttpClient())
.addConverterFactory(GsonConverterFactory.create())
.build();
Endpoints endpoints= retrofit.create(Endpoints.class);
endpoints.newuser("{\"full_name\":\"sss\",\"states_id\":\"20\",\"mobile\":\"9876543210\",\"password\":\"******\",\"accept_terms\":true,\"Userid\":\"0\",\"refer\":\"\",\"ip-address\":\"1.2.3.4\",\"device_type\":\"samsung J5\",\"os-version\":\"5.0.1\",\"client\":\"app\",\"secret_key\":\"44\"}")
.enqueue(new retrofit2.Callback<Items>() {
#Override
public void onResponse(retrofit2.Call<Items> call, retrofit2.Response<Items> response) {
System.out.println("onResponse : "+response.message());
System.out.println("onResponse : "+response.body());
System.out.println("onResponse : "+response.code());
System.out.println("onResponse : "+response.errorBody());
System.out.println("onResponse : "+response.isSuccessful());
System.out.println("onResponse : "+response.raw());
System.out.println("onResponse : "+response);
}
#Override
public void onFailure(retrofit2.Call<Items> call, Throwable t) {
System.out.println("onFailure"+call);
}
});
}
public static OkHttpClient getUnsafeOkHttpClient() {
try {
// Create a trust manager that does not validate certificate chains
final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
#Override
public void checkClientTrusted(
java.security.cert.X509Certificate[] chain,
String authType) throws CertificateException {
}
#Override
public void checkServerTrusted(
java.security.cert.X509Certificate[] chain,
String authType) throws CertificateException {
}
#Override
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new java.security.cert.X509Certificate[0];
}
} };
// Install the all-trusting trust manager
final SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustAllCerts,
new java.security.SecureRandom());
// Create an ssl socket factory with our all-trusting manager
final SSLSocketFactory sslSocketFactory = sslContext
.getSocketFactory();
OkHttpClient okHttpClient = new OkHttpClient();
okHttpClient = okHttpClient.newBuilder()
.sslSocketFactory(sslSocketFactory)
.hostnameVerifier(org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER).build();
return okHttpClient;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Interface :
public interface Endpoints {
#POST("/userregister/newuser")
#FormUrlEncoded
Call<Items> newuser(#Field("Data") String Data);
}
POJO class :
public class Items {
#SerializedName("Response-Status")
#Expose
private Boolean responseStatus;
#SerializedName("Response-Validate")
#Expose
private Boolean responseValidate;
#SerializedName("Response-Message")
#Expose
private String responseMessage;
#SerializedName("Response-Data")
#Expose
private ResponseData responseData;
public Boolean getResponseStatus() {
return responseStatus;
}
public void setResponseStatus(Boolean responseStatus) {
this.responseStatus = responseStatus;
}
public Boolean getResponseValidate() {
return responseValidate;
}
public void setResponseValidate(Boolean responseValidate) {
this.responseValidate = responseValidate;
}
public String getResponseMessage() {
return responseMessage;
}
public void setResponseMessage(String responseMessage) {
this.responseMessage = responseMessage;
}
public ResponseData getResponseData() {
return responseData;
}
public void setResponseData(ResponseData responseData) {
this.responseData = responseData;
}
}
I am getting this response :
{protocol=http/1.1, code=404, message=Not Found, url=www.xyz.com/userregister/newuser}
I have given the proper url then why is it taking only half of it?
I have tried the example from https://code.tutsplus.com/tutorials/sending-data-with-retrofit-2-http-client-for-android--cms-27845. This example and the link given in the example are working fine, but if I do the same with my url then I get the above error
I Hope kindly check your parsing issues may occurred.
#Override
public void onFailure(retrofit2.Call<Items> call, Throwable t) {
System.out.println("onFailure"+call);
//add this lije you got exceptions.
t.printStackTrace();
}
Change your Endpoints interface for this:
public interface Endpoints {
#POST("userregister/newuser")
#FormUrlEncoded
Call<Items> newuser(#Field("Data") String Data);
}
Note that I removed the trailing slash /. This way Retrofit appends the path you defined to the BASE_URL.
refer to the docs for Retrofit.Builder for a more detailed explanation, but pay particular attention to these bits:
Base URLs should always end in /.
A trailing / ensures that endpoints values which are relative paths
will correctly append themselves to a base which has path components.
...
Endpoint values which contain a leading / are absolute.
Absolute values retain only the host from baseUrl and ignore any
specified path components.
as presently written, the path referenced in your call to Endpoints.newuser() is absolute, and therefore the path segments after the host in your base URL are dropped (as this is the documented behavior).
therefore, you should change your Endpoints interface to use relative paths instead, like so:
public interface Endpoints {
#POST("userregister/newuser")
#FormUrlEncoded
Call<Items> newuser(#Field("Data") String Data);
}
I have XML as follows
<request type="1">
<request-header/>
<request-details>
<!-- Some more tags -->
</request-details>
</request>
For mapping this XML I have class structure as follows :
public class Request1
{
private RequestDetail_1;
//other members
}
public class Request2
{
private RequestDetail_2;
//other members
}
public class RequestDetail_1
{
//members
}
public class RequestDetail_2
{
//Members
}
What I want to do is ... If attribute type is 1 then I need to create object of type Request_1 , if type is 2 then object type will be Request_2 and so on.
I have gone through this link for reference but still couldn't figure out a way to do this. I want to use pure JAXB and not MOXY or any other such frame works... :( .
Partial code :
#XmlJavaTypeAdapter(RequestAdaptor.class)
#XmlRootElement(name="request")
public class AuthRequest extends Request
{
private AuthRequestDetails requestDetails;
public RequestDetails getRequestDetails()
{
return requestDetails;
}
#Override
public void setRequestDetails(RequestDetails requestDetails)
{
this.requestDetails = (AuthRequestDetails)requestDetails;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
public class AuthRequestDetails extends RequestDetails
{
#XmlElement(name="user-name")
private String userName;
#XmlElement(name="password")
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlJavaTypeAdapter(RequestAdaptor.class)
public abstract class Request
{
#XmlAttribute
protected String type;
#XmlElement(name="request-header")
protected RequestHeader requestHeader;
public RequestHeader getRequestHeader()
{
return requestHeader;
}
public void setRequestHeader(RequestHeader requestHeader)
{
this.requestHeader = requestHeader;
}
public String getType()
{
return type;
}
public void setType(String type)
{
this.type = type;
}
public abstract void setRequestDetails(RequestDetails requestDetails);
public abstract RequestDetails getRequestDetails();
}
public class RequestAdaptor extends XmlAdapter<RequestDTO, Request>
{
#Override
public RequestDTO marshal(Request v) throws Exception
{
System.out.println("marshal");
RequestDTO lRequestDTO= new RequestDTO();
lRequestDTO.setRequestHeader(v.getRequestHeader());
lRequestDTO.setType(v.getType());
if(v.getType().equals("5"))
{
AuthRequest lRequest = (AuthRequest)v;
}
else
{
PingRequest lRequest = (PingRequest)v;
}
return lRequestDTO;
}
#Override
public Request unmarshal(RequestDTO v) throws Exception
{
System.out.println("unmarshal");
if(v.getType().equals("5"))
{
AuthRequest lRequest = new AuthRequest();
lRequest.setRequestHeader(v.getRequestHeader());
lRequest.setType(v.getType());
return lRequest;
}
else
{
PingRequest lRequest = new PingRequest();
lRequest.setRequestHeader(v.getRequestHeader());
lRequest.setType(v.getType());
return lRequest;
}
}
}
#XmlAccessorType(XmlAccessType.FIELD)
public class RequestDTO
{
#XmlAttribute
protected String type;
#XmlElement(name="request-header")
private RequestHeader requestHeader;
#XmlElement(name="request-details")
private RequestDetails requestDetails;
public RequestHeader getRequestHeader()
{
return requestHeader;
}
public void setRequestHeader(RequestHeader requestHeader)
{
this.requestHeader = requestHeader;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public RequestDetails getRequestDetails() {
return requestDetails;
}
public void setRequestDetails(RequestDetails requestDetails) {
this.requestDetails = requestDetails;
}
}
#XmlAccessorType(XmlAccessType.FIELD)
public class RequestHeader
{
#XmlElement(name="name")
String Name;
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
First thing is : Marshal and Unmarshal of Adaptor is not getting called. I am stuck at this point.
You can use a StAX XmlStreamReader to parse the XML. Then advance it to the root element. When it's at the root element event check the value of the type attribute. Use this value to determine which Class you should pass to the unmarshal method that takes a Class and XmlStreamReader to get the result you are looking for.
How can I pass an injected http session attribute (see below), along with other values (informe by the user) and save them using JPA?
The session attribute is correctly displayed and injected, but I need to pass it using the selected to be stored in the database (actually, it passess null).
The JSF:
<p:outputLabel value="UserID (the sessionAttribute):" for="userID" />
<p:inputText id="userID" value="#{userBean.myUser.xChave}" title="userID" />
<p:outputLabel value="Type the Reason:" for="reason" />
<p:inputText id="reason" value="#{viagensController.selected.reason}" />
<!-- updated (just the call to the action method: -->
<p:commandButton actionListener="#{viagensController.saveNew}" value="#{viagensBundle.Save}" update="display,:ViagensListForm:datalist,:growl" oncomplete="handleSubmit(xhr,status,args,ViagensCreateDialog);" />
The bean:
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.FacesContext;
import javax.inject.Named;
#Named(value = "userBean")
#SessionScoped
public class UserBean implements Serializable {
private bean_login myUser;
public bean_login getMyUser() {
return myUser;
}
public void setMyUser(bean_login myUser) {
this.myUser = myUser;
}
#PostConstruct
public void init() {
String uid = FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("xChave").toString();
myUser = new bean_login();
myUser.setxChave(uid);
System.out.print("from init:" + myUser.toString());
}
}
The AbstractFacade:
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {{ /*impl. ommited*/ }
public List<T> findAll() {{ /*impl. ommited*/ }
public List<T> findRange(int[] range) { /*impl. ommited*/ }
public int count() { /*impl. ommited*/ }
}
The AbstractController (for the selected in JSF above and other methods):
public abstract class AbstractController<T> {
#Inject
private AbstractFacade<T> ejbFacade;
private Class<T> itemClass;
private T selected;
private Collection<T> items;
private enum PersistAction {
CREATE,
DELETE,
UPDATE
}
public AbstractController() {
}
public AbstractController(Class<T> itemClass) {
this.itemClass = itemClass;
}
public T getSelected() {
return selected;
}
// Pass in the currently selected item
public void setSelected(T selected) {
this.selected = selected;
}
protected void setEmbeddableKeys() {
}
protected void initializeEmbeddableKey() {
}
public Collection<T> getItems() {
if (items == null) {
items = this.ejbFacade.findAll();
}
return items;
}
// Pass in collection of items
public void setItems(Collection<T> items) {
this.items = items;
}
// Apply changes to an existing item to the data layer.
public void save(ActionEvent event) {
String msg = ResourceBundle.getBundle("/viagensBundle").getString(itemClass.getSimpleName() + "Updated");
persist(PersistAction.UPDATE, msg);
}
// Store a new item in the data layer.
public void saveNew(ActionEvent event) {
String msg = ResourceBundle.getBundle("/viagensBundle").getString(itemClass.getSimpleName() + "Created");
persist(PersistAction.CREATE, msg);
if (!isValidationFailed()) {
items = null; // Invalidate list of items to trigger re-query.
}
}
public void delete(ActionEvent event) {/*implementations ommited*/ }
private void persist(PersistAction persistAction, String successMessage) {
if (selected != null) {
this.setEmbeddableKeys();
try {
if (persistAction != PersistAction.DELETE) {
this.ejbFacade.edit(selected);
} else {
this.ejbFacade.remove(selected);
}
JsfUtil.addSuccessMessage(successMessage);
} catch (EJBException ex) {
String msg = "";
Throwable cause = JsfUtil.getRootCause(ex.getCause());
if (cause != null) {
if (cause instanceof ConstraintViolationException) {
ConstraintViolationException excp = (ConstraintViolationException) cause;
for (ConstraintViolation s : excp.getConstraintViolations()) {
JsfUtil.addErrorMessage(s.getMessage());
}
} else {
msg = cause.getLocalizedMessage();
if (msg.length() > 0) {
JsfUtil.addErrorMessage(msg);
} else {
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
}
} catch (Exception ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
JsfUtil.addErrorMessage(ex, ResourceBundle.getBundle("/viagensBundle").getString("PersistenceErrorOccured"));
}
}
}
// Creates a new instance of an underlying entity and assigns it to Selected property.
public T prepareCreate(ActionEvent event) {
T newItem;
try {
newItem = itemClass.newInstance();
this.selected = newItem;
initializeEmbeddableKey();
return newItem;
} catch (InstantiationException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
}
return null;
}
// Inform the user interface whether any validation error exist on a page.
public boolean isValidationFailed() {
return JsfUtil.isValidationFailed();
}
// Retrieve all messages as a String to be displayed on the page.
public String getComponentMessages(String clientComponent, String defaultMessage) {
return JsfUtil.getComponentMessages(clientComponent, defaultMessage);
}
}
Thanks in advance.
updated:
The ViagensController:
#Named(value = "viagensController")
#ViewScoped
public class ViagensController extends AbstractController<Viagens> implements Serializable {
//generics:passing JPA Entity class, where the 'reason' in JSF is defined
public ViagensController() {
super(Viagens.class);
}
}
Need to override the save method passing the injected http session value :
#ManagedBean(name = "riscosController")
#ViewScoped
public class RiscosController extends AbstractController<Riscos> {
#EJB
private RiscosFacade ejbFacade;
#Inject
#SessionChave
private String iSessionChave;
private String sessionChave;
private UorPosController matriculaController;
private UorPosController informanteController;
public String getSessionChave(String chave) {
if (sessionChave.isEmpty()) {
sessionChave = iSessionChave;
}
return sessionChave;
}
public void setSessionChave(String sessionChave) {
this.sessionChave = sessionChave;
}
#PostConstruct
#Override
public void init() {
super.setFacade(ejbFacade);
FacesContext context = FacesContext.getCurrentInstance();
matriculaController = context.getApplication().evaluateExpressionGet(context, "#{uorPosController}", UorPosController.class);
informanteController = context.getApplication().evaluateExpressionGet(context, "#{uorPosController}", UorPosController.class);
sessionChave = "";
}
#Override
public void saveNew(ActionEvent event) {
this.getSelected().setObs(this.getSessionChave(sessionChave));
super.saveNew(event);
}
}