Removing namespace prefix in the output of Spring WS web service - web-services

I have created web service using Spring-WS. When I send a request to the web service, this is the response I get in soap-ui:
enter code here
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<ns2:SendResponse xmlns:ns2="http://mycompany.com/schema/">
<ns2:SendResult>
<ns2:Token>A00179-02</ns2:Token>
</ns2:SendResult>
</ns2:SendResponse>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
Is there any way to get rid of the "ns2" namespace prefix from the response? I tried a couple of options:
1) Manually updated package-info.java to set the prefix to "":
#XmlSchema(namespace = "http://mycompany.com/schema/",
xmlns = {
#XmlNs(namespaceURI = "http://mycompany.com/schema/", prefix = "")
},
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package com.example.foo.jaxb;
2) Set the prefix to "" in the QName object in the endpoint class:
return new JAXBElement<SendAndCommitResponse>(new QName("http://mycompany.com/schema/",
"SendResponse",""), SendResponse.class, response);
Both didn't work. How to get rid off the "ns2" namespace prefix?

I eventually found a solution for this.
My problem was caused by JDK 6 not shipping a full version of rt.jar (http://www.oracle.com/technetwork/java/javase/compatibility-137541.html).
I added the following to my maven config
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.2.6</version>
</dependency>
And then added
#XmlSchema(namespace = "http://mycompany.com/schema/",
elementFormDefault = javax.xml.bind.annotation.XmlNsForm.UNQUALIFIED).
In the package-info.java (like suggested by #acdcjunior above)

I tried a few of the approaches discussed here, but nothing worked...
Below Class from the link - https://zhuanlan.zhihu.com/p/35298171 fixed my issue
Added the below interceptor to remove the namespaces -
public class PayloadPrefixInterceptor extends TransformerHelper implements EndpointInterceptor {
public static final String NAMESPACE = ObjectFactory.class.getPackage().getAnnotation(XmlSchema.class).namespace();
public static final String XMLNS = "xmlns:";
#Override
public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception {
return true;
}
#Override
public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception {
WebServiceMessage response = messageContext.getResponse();
Source payloadSource = response.getPayloadSource();
DOMResult result = new DOMResult();
transform(payloadSource, result);
removePrefix(result.getNode());
transform(new DOMSource(result.getNode()), response.getPayloadResult());
return true;
}
private void removePrefix(Node node) {
if (node == null) {
return;
}
if (node.getNodeType() == Node.ELEMENT_NODE) {
removeNamespaceDeclaration(node);
}
if (node.getPrefix() != null) {
node.setPrefix(null);
}
NodeList childNodes = node.getChildNodes();
if (childNodes != null) {
IntStream.of(0, childNodes.getLength()).forEach(index -> removePrefix(childNodes.item(index)));
}
Node nextSibling = node.getNextSibling();
if (nextSibling != null) {
removePrefix(nextSibling);
}
}
private void removeNamespaceDeclaration(Node node) {
NamedNodeMap attributes = node.getAttributes();
IntStream.range(0, attributes.getLength()).forEach(index -> {
Node attribute = attributes.item(index);
if (StringUtils.startsWith(attribute.getNodeName(), XMLNS) &&
StringUtils.equals(attribute.getNodeValue(), NAMESPACE)) {
attributes.removeNamedItemNS(attribute.getNamespaceURI(), attribute.getLocalName());
}
});
}
#Override
public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception {
return true;
}
#Override
public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) throws Exception {
}
}
Registered the interceptor using below -
#EnableWs
#Configuration
public class Config extends WsConfigurerAdapter {
#Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
interceptors.add(new PayloadPrefixInterceptor());
super.addInterceptors(interceptors);
}
}

it was hard
first: create a class that intercepts soap request and responses:
package examples.webservices.handler;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.Set;
import javax.xml.namespace.QName;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPMessage;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
public class CorrigirConteudoRequisicaoSOAP implements SOAPHandler<SOAPMessageContext> {
public Set<QName> getHeaders() {
return Collections.emptySet();
}
public boolean handleMessage(SOAPMessageContext messageContext) {
this.corrigirConteudoRequisicaoSOAP(messageContext);
return true;
}
private void corrigirConteudoRequisicaoSOAP(SOAPMessageContext messageContext){
SOAPMessage msg = messageContext.getMessage();
try {
NodeList childNodes = msg.getSOAPBody().getChildNodes();
for(int k = 0; k < childNodes.getLength(); k++){
Node item = childNodes.item(k);
String localName = item.getLocalName();
{
item.setPrefix("");
Method m = SOAPElement.class.getDeclaredMethod("setElementQName", QName.class);
//I was forced to use reflection because the method setElementQname is not //visible, neither the class that implements it
m.invoke(item, new QName("", item.getLocalName()));
msg.saveChanges();
}
}
} catch (Exception e) {
try {
msg.writeTo(System.out);
} catch (Exception e1) {
e1.printStackTrace();
}
System.out.println();
}
}
public boolean handleFault(SOAPMessageContext messageContext) {
return true;
}
public void close(MessageContext messageContext) {
}
public static void main(String[] args)throws Exception {
}
}
second: associate the service to soap handle
public class PortalFornecedor {
public Usuario getUsuario(){
XIF367Afae09A3344Fbf2E1De819D6EcbaService classeComNomeFeio = new XIF367Afae09A3344Fbf2E1De819D6EcbaService();
Usuario service = classeComNomeFeio.getHTTPPort();
BindingProvider bp = (BindingProvider)service;
Map<String, Object> requestContext = bp.getRequestContext();
requestContext.put(BindingProvider.USERNAME_PROPERTY, "user");
requestContext.put(BindingProvider.PASSWORD_PROPERTY, "pass");
this.handle(service);
return service;
}
public Object getDashboard(){
return "";
}
// here we associate the service to soap handle
private BindingProvider handle(Usuario service) {
BindingProvider bp = (BindingProvider)service;
#SuppressWarnings("rawtypes")
List<Handler> chain = new ArrayList<Handler>();
chain.add(new CorrigirConteudoRequisicaoSOAP());
bp.getBinding().setHandlerChain(chain);
return bp;
}
public static void main(String[] args) {
PortalFornecedor pf = new PortalFornecedor();
Usuario usuario = pf.getUsuario();
LoginExecutarIN in = new LoginExecutarIN();
generated.Usuario user = new generated.Usuario();
user.setLogin("onias");
user.setSenha("12345");
user.setCodigoUsuario(0);
in.setParametroEntrada(user);
try {
LoginExecutarOUT out = usuario.loginExecutar(in);
// SOAPMessageContext.getMessage();
System.out.println(out.getRegistroSelecionado().getNome());
} catch (Exception e) {
e.printStackTrace();
}
}
}

Here is the simple and easiest solution for that problem. Create Package-Info.Java file in your model package and add the below script to that.
#javax.xml.bind.annotation.XmlSchema(namespace = "http://mycompany.com/schema", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED, xmlns = { #javax.xml.bind.annotation.XmlNs(namespaceURI = "http://mycompany.com/schema", prefix = "") })
package my.com.scicom.stars.model;
And add elementFormDefault as "qualified" in your xsd or wsdl file.
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns="http://mycompany.com/schema"
targetNamespace="http://mycompany.com/schema"
elementFormDefault="qualified">

Related

How to mock a private method called inside another private method

I was trying to mock a private method's output which is being called inside another private method, I have no choice but to test the later private method, so I have added sample test code which I can represent here,
This Sample Class
package com.testableClass;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class TestableClass {
private int initialMockMethod(Object obj)
{
System.out.println(" ++++ Came Here ++++ ");
String str = getRestString("");
System.out.println("str ="+str);
return str.length();
}
private String getRestString(String abc)
{
String output="";
try {
URL url = new URL("https://gorest.co.in/public-api/users");//your url i.e fetch data from .
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP Error code : "
+ conn.getResponseCode());
}
InputStreamReader in = new InputStreamReader(conn.getInputStream());
BufferedReader br = new BufferedReader(in);
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
return output;
} catch (Exception e) {
System.out.println("Exception in NetClientGet:- " + e);
}
return abc;
}
}
Now This PowerMock Class
package com.testableClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.reflect.Whitebox;
import junit.framework.Assert;
#RunWith(PowerMockRunner.class)
#PrepareForTest(fullyQualifiedNames = "com.testableClass.TestableClass")
public class PowerMockTest {
#Test
public void testPrivateMethod() throws Exception
{
String message = "Hello PowerMockito";
String expectation = "Expectation";
TestableClass mock = PowerMockito.spy(new TestableClass());
// PowerMockito.doReturn(expectation).when(mock, "getRestString", message);
PowerMockito.when(mock, "getRestString", message).thenReturn(expectation);
int count = Whitebox.invokeMethod(mock, "initialMockMethod", new Object());
System.out.println(" +++ Count : "+count+" ++++ ");
Assert.assertTrue(true);
}
}
my issue is when I am running my test case then
PowerMockito.when(mock, "getRestString", message).thenReturn(expectation);
executes original method and returns original output while my requirement is that,
when my test case is actually calling private method initialMockMethod it should not call getRestString instead of that it should return my mocked expected output which is "Expectation"
Instead of using reflection and PowerMock, I'd say that do not try to mock a private method. It is a hidden detail of the class.
What I suggest is that, if your method makes an HTTP request, then let it do that. But you can use a mock server to mock the response. But to do that, you need to make your endpoint external, so that it can be injected.
I changed your class a little bit; still the same purpose tho.
public class TestableClass {
private final String resourceUrl;
public TestableClass(String resourceUrl) {
this.resourceUrl = resourceUrl;
}
public int publicMethod() {
return initialMockMethod(null);
}
private int initialMockMethod(Object obj) {
var str = getRestString("");
return str.length();
}
private String getRestString(String abc) {
try {
var url = new URL(resourceUrl);
var conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP Error code : "
+ conn.getResponseCode());
}
var in = new InputStreamReader(conn.getInputStream());
var br = new BufferedReader(in);
var result = br.lines().collect(Collectors.joining("\n"));
conn.disconnect();
return result;
} catch (Exception e) {
System.out.println("Exception in NetClientGet:- " + e);
}
return abc;
}
}
and here's the test
public class TestingTestableClass {
#Test
#SneakyThrows
public void test() {
final var server = new MockWebServer();
server.start(9999);
var instance = new TestableClass("http://127.0.0.1:9999");
server.enqueue(
new MockResponse()
.setResponseCode(200)
.setBody("this is the response")
);
final int result = instance.publicMethod();
Assertions.assertEquals(
"this is the response".length(),
result
);
final var record = server.takeRequest();
final var method = record.getMethod();
Assertions.assertEquals("GET", method);
server.shutdown();
}
}
Check out MockWebServer here

Testing an API endpoint with Lambda + API Gateway

I'm trying to create and test an API endpoint using AWS Lambda and API Gateway. I can test my function successfully using Lambda Test, but when I try to test my endpoint it gives:
{
"message": "Internal server error"
}
This is my handler class:
package com.amazonaws.lambda.gandhi.conversion.api;
import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.RandomStringUtils;
import com.amazonaws.lambda.gandhi.conversion.api.Response.AuthClientCredentialResponse;
import com.amazonaws.services.lambda.runtime.Context;
import com.amazonaws.services.lambda.runtime.RequestHandler;
import com.amazonaws.lambda.gandhi.conversion.api.utils.ClientAuthPOJO;
public class AuthClientCredentialServiceHandler implements RequestHandler<ClientAuthPOJO, Object> {
private AuthClientCredentialResponse authClientCredentialResponse;
private static final SecureRandom RANDOM = new SecureRandom();
public static int MAX_CLIENT_KEY = 10;
public static int CLIENT_SECRET_LENGTH = 69;
#Override
public AuthClientCredentialResponse handleRequest(ClientAuthPOJO clientIdSecret, Context context) {
String clientSecret;
try {
context.getLogger().log("Input: "
+ clientIdSecret);
String clientId = clientIdSecret.getClientId();
clientSecret = generateClientSecretKey();
Map<String, String> clientCredsMap = getClientCredentials();
if (clientCredsMap.size() > MAX_CLIENT_KEY) {
throw new RuntimeException(String.format("Max limit is %d, Please delete some keys", MAX_CLIENT_KEY));
}
clientCredsMap.forEach((k, v) -> {
if (clientId.equals(k)) {
throw new RuntimeException("Client Already exists");
}
});
storeClientCredentials(clientId, clientSecret);
AuthClientCredentialResponse authClientCredentialResponse = AuthClientCredentialResponse.builder().success(
true).clientId(clientId).clientSecret(clientSecret).build();
this.authClientCredentialResponse = authClientCredentialResponse;
} catch (Exception e) {
throw new RuntimeException(
"Failed to generate client secret: "
+ e.getMessage());
}
return authClientCredentialResponse;
}
private String generateClientSecretKey() throws NoSuchAlgorithmException, InvalidKeySpecException {
String clientSecret = RandomStringUtils.randomAlphanumeric(CLIENT_SECRET_LENGTH);
System.out.printf("clientSecret: %s%n", clientSecret);
return clientSecret;
}
private void storeClientCredentials(String clientId, String clientSecret) throws IOException {
/*
* TODO:
* Some logic to store clientCredentials to a file or DB. Decide later.
*/
System.out.println("temp ClientCredentials stored");
}
public Map<String, String> getClientCredentials() throws IOException {
/*
* TODO:
* Some logic to fetch clientCredentials from file or DB. Decide later.
*/
Map<String, String> clientCredMap = new HashMap<String, String>();
clientCredMap.put("1", "secretKey1");
clientCredMap.put("2", "secretKey2");
clientCredMap.put("3", "secretKey3");
clientCredMap.put("4", "secretKey4");
return clientCredMap;
}
}
My input class:
package com.amazonaws.lambda.gandhi.conversion.api.utils;
public class ClientAuthPOJO {
String clientId;
String clientSecret;
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getClientSecret() {
return clientSecret;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public ClientAuthPOJO(String clientId, String clientSecret) {
super();
this.clientId = clientId;
this.clientSecret = clientSecret;
}
public ClientAuthPOJO() {
}
}
My test object in lambda:
My test for endpoint in API Gateway:
Can someone please help me figure out the problem in creating the function or API Gateway?
Edit:
When I check the logs, I found that the parameters to the functions (clientId and clientSecret) are null. So there seems to be some problem in the way I'm sending my request body.

How to forward service?wsdl to service.wsdl in Spring WS

At the first sorry for my awful English. I have following piece of Spring WS configuration:
#Configuration
class WSConfig {
...
#Bean
Wsdl11Definition wsdlSchema() {
SimpleWsdl11Definition wsdl11Definition = new SimpleWsdl11Definition();
wsdl11Definition.setWsdl(new ClassPathResource("service.wsdl"));
return wsdl11Definition;
}
}
So I can get WSDL file using URL */service.wsdl.
Is it possible to add URL forwarding */service?wsdl --> */service.wsdl cause of some WS clients use URL */service?wsdl.
Possible solution is extending MessageDispatcherServlet
class CustomMessageDispatcherServlet extends MessageDispatcherServlet {
private static final String WSDL_SUFFIX_NAME = ".wsdl";
private Map<String, WsdlDefinition> wsdlDefinitions;
CustomMessageDispatcherServlet(ApplicationContext applicationContext) {
super();
setApplicationContext(applicationContext);
setTransformWsdlLocations(true);
setTransformSchemaLocations(false);
}
#Override
protected void initStrategies(ApplicationContext context) {
super.initStrategies(context);
initWsdlDefinitions(context);
}
private void initWsdlDefinitions(ApplicationContext context) {
wsdlDefinitions = BeanFactoryUtils
.beansOfTypeIncludingAncestors(
context, WsdlDefinition.class, true, false);
}
// here with dealing with "wsdl" parameter in HTTP GET request
#Override
protected WsdlDefinition getWsdlDefinition(HttpServletRequest request) {
if (HttpTransportConstants.METHOD_GET.equals(request.getMethod()) &&
(request.getRequestURI().endsWith(WSDL_SUFFIX_NAME) || request.getParameter("wsdl") != null)) {
String fileName = WebUtils.extractFilenameFromUrlPath(request.getRequestURI());
return wsdlDefinitions.get(fileName);
} else {
return null;
}
}
}

CognitoCachingCredentialsProvider getCachedIdentityId is null after app close and re-open

I might be misunderstanding the intended behavior of this method, but this is what I am trying to use it for:
-User logs in successfully
-User closes app completely (closes in background as well)
-User opens app again and doesn't have to log in again because CognitoCachingCredentialsProvider can check locally on the device to see she's still logged in
The way I tried to accomplish this is to check, before being prompted to log in, what getCachedIdentityId() returns. If it returns not null, then that means that she's still logged in, because there was nothing that cleared her credentials from the device. Here's what my framework looks like. I'm using developer authenticated method:
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.util.Log;
import com.amazonaws.auth.AWSAbstractCognitoIdentityProvider;
import com.amazonaws.auth.CognitoCachingCredentialsProvider;
import com.amazonaws.mobileconnectors.cognito.*;
import com.amazonaws.regions.Regions;
public class Util {
private final static String TAG = "Util";
private static final String AWS_ACCOUNT_ID = {acct id};
private static final String COGNITO_POOL_ID = {pool id};
private static final String COGNITO_ROLE_AUTH = {auth arn};
private static final String COGNITO_ROLE_UNAUTH = {unauth arn}
private static CognitoCachingCredentialsProvider sCredProvider;
private static UserIdentityProvider sIdProvider;
private static CognitoSyncManager sSyncManager;
private Util() {
}
public static CognitoCachingCredentialsProvider getCredProvider(
Context context) {
if (sCredProvider == null) {
if (sIdProvider == null) {
CognitoCachingCredentialsProvider tmpProvider = new CognitoCachingCredentialsProvider(
context.getApplicationContext(), AWS_ACCOUNT_ID,
COGNITO_POOL_ID, COGNITO_ROLE_UNAUTH,
COGNITO_ROLE_AUTH, Regions.US_EAST_1);
if (tmpProvider.getCachedIdentityId() != null) {
sCredProvider = tmpProvider;
} else {
sCredProvider = null;
}
} else {
sCredProvider = new CognitoCachingCredentialsProvider(
context.getApplicationContext(), sIdProvider,
COGNITO_ROLE_UNAUTH, COGNITO_ROLE_AUTH);
Map logins = new HashMap();
logins.put({Developer Provider Name}, sIdProvider.getToken());
sCredProvider.setLogins(logins);
}
}
return sCredProvider;
}
public static UserIdentityProvider getIdentityProvider(Context context,
String email, String pwd) {
if (sIdProvider == null) {
sIdProvider = new UserIdentityProvider(AWS_ACCOUNT_ID,
COGNITO_POOL_ID, context.getApplicationContext());
}
return sIdProvider;
}
public static boolean isLoggedIn(Context context) {
if (getCredProvider(context) == null) {
return false;
}
return true;
}
protected static class UserIdentityProvider extends
AWSAbstractCognitoIdentityProvider {
private Context context;
private String email;
private String password;
public UserIdentityProvider(String accountId, String identityPoolId,
Context c) {
super(accountId, identityPoolId);
context = c;
email = em;
password = pwd;
}
#Override
public String refresh() {
try {
ServerCommunicator server = new ServerCommunicator(context);
if (email != null && password != null) {
//this is a server call, which makes the call GetOpenIdTokenForDeveloperIdentityRequest after I authenticate the user and send AWS my user's token
String response = server.initUserLoginAsyncTask()
.execute(email, password).get();
prefs.setAllUserSharedPrefs(response);
JSONObject responseJSON = new JSONObject(response);
String identityId = responseJSON.getString("id");
String token = responseJSON.getString("token");
if (token != null && identityId != null) {
this.setToken(token);
this.setIdentityId(identityId);
update(identityId, token);
return token;
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
public String getProviderName() {
return {Developer Provider Name};
}
}
}
I simply call the isLoggedIn method from this class to see if there's an IdentityId stored locally. However, this isn't working as expected. I can see from debugging that getCachedIdentityId is always null (even directly after initializing CognitoCachingCredentialsProvider and adding the token to the logins map) and I am always prompted to log in again whenever I open the app after it has been closed. When does the IdentityId actually get stored locally and is my logic correct in general?
Additional Code
import java.util.concurrent.ExecutionException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class LoginActivity extends Activity {
private final String TAG = "LoginActivity";
private EditText etEmail, etPwd;
private Button bLogin, bGoToRegister;
private ServerCommunicator server;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i(TAG, "onCreate");
server = new ServerCommunicator(this);
if (Util.isLoggedIn(this)) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
return;
}
this.setContentView(R.layout.activity_login);
etEmail = (EditText) findViewById(R.id.etEmail);
etPwd = (EditText) findViewById(R.id.etPassword);
bLogin = (Button) findViewById(R.id.bLogin);
bGoToRegister = (Button) findViewById(R.id.bGoToRegister);
bLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String email = etEmail.getText().toString();
String pwd = etPwd.getText().toString();
Util.getIdentityProvider(v.getContext()).setEmail(email);
Util.getIdentityProvider(v.getContext()).setPassword(pwd);
String token = Util.getIdentityProvider(v.getContext()).refresh();
if (token != null) {
Intent intent = new Intent(v.getContext(), MainActivity.class);
startActivity(intent);
} else {
Toast.makeText(v.getContext(), "Invalid username/password",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
The above is my LoginActivity. When the app starts the MainActivity, I have the following snippet at the beginning of my onCreate method:
if (!Util.isLoggedIn(this)) {
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
}
This call initializes the CognitoCachingCredentialsProvider. I assumed that this would be when the IdentityId gets cached, but my debugging has revealed that even directly after this block, getCachedIdentityId() still returns null. Am I way off base with how I'm trying to use this class?
I have one suggestion. The CognitoCachingCredentialsProvider is what saves the identityId as it's changed. It doesn't start listening, though, until it's been initialized, and the change occurs on refresh call to your identity provider.
Can you try moving the initialization of the CognitoCachingCredentialsProvider to before the refresh call (but after your identity provider initialization)?
Edit:
Update will set the identityId and token, however explicit calls made just beforehand may cause it to think no change is being made. Can you try eliminating the setter calls as well?

Subresource for target class has no jax-rs annotations

I am trying to call a webservice method via a proxy but I have got an error message that says: "Subresource for target class has no jax-rs annotations.: org.jboss.resteasy.core.ServerResponse"
Here is my server class
#Path("/authorizationCheck")
public class AuthorizationRestService implements AuthorizationService {
#Override
#Path("/webserviceTest")
public Response webserviceTest(){
TestDTO x = new TestDTO();
x.setFieldOne("ffff");
x.setFieldTwo("gggg");
Response res = Response.ok(x).build();
return res;
}
}
with a an interface like this
#Path("/authorizationCheck")
public interface AuthorizationService {
#POST
#Path("/webserviceTest")
public Response webserviceTest();
}
and my return object wrapped in response
#XmlRootElement
#XmlAccessorType(XmlAccessType.FIELD)
public class TestDTO {
private String fieldOne;
private String fieldTwo;
public String getFieldOne() {
return fieldOne;
}
public void setFieldOne(String fieldOne) {
this.fieldOne = fieldOne;
}
public String getFieldTwo() {
return fieldTwo;
}
public void setFieldTwo(String fieldTwo) {
this.fieldTwo = fieldTwo;
}
}
and finally my client class
#Stateful
#Scope(ScopeType.CONVERSATION)
#Name("authorizationCheckService")
public class AuthorizationCheckService {
public void testWebservice(){
RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
AuthorizationService proxy =
ProxyFactory.create(AuthorizationService.class,
ApplicationConfig.WORKFLOWSERVER_URL + "services/authorizationCheck/webserviceTest");
Response response = proxy.webserviceTest();
return;
}
}
what I am doing wrong here , any help will be appreciated.
You have two annotations with webserviceTest() which are #POST and #Path.
Repeat BOTH the annotations in over ridden method in implemented class. That means add the #POST annotation to webserviceTest() method.
It should work then !
And here is the reason why it din't work.. without proper annotations in implementing class.
Why java classes do not inherit annotations from implemented interfaces?
You can remove the #Path annotations on the implementation class and concrete method, and only annotate your interfaces, like this:
public class AuthorizationRestService implements AuthorizationService {
#Override
public Response webserviceTest(){
TestDTO x = new TestDTO();
x.setFieldOne("ffff");
x.setFieldTwo("gggg");
Response res = Response.ok(x).build();
return res;
}
}
Note: don't forget #Produces on your interface method to define your MIME type, such as MediaType.APPLICATION_XML
#Path("/authorizationCheck")
public interface AuthorizationService {
#POST
#Path("/webserviceTest")
#Produces(MediaType.APPLICATION_XML)
public Response webserviceTest();
}
See an example here: http://pic.dhe.ibm.com/infocenter/initiate/v9r5/index.jsp?topic=%2Fcom.ibm.composer.doc%2Ftopics%2Fr_composer_extending_services_creating_rest_service_rest_interface.html
and here: http://pic.dhe.ibm.com/infocenter/initiate/v9r5/index.jsp?topic=%2Fcom.ibm.composer.doc%2Ftopics%2Fr_composer_extending_services_creating_rest_service_rest_interface.html
I changed like this
#Path("/authorizationCheck")
public class AuthorizationRestService implements AuthorizationService {
#Override
#Path("/webserviceTest")
#POST
#Produces(MediaType.APPLICATION_XML)
public Response webserviceTest(){
TestDTO x = new TestDTO();
x.setFieldOne("ffff");
x.setFieldTwo("gggg");
Response res = Response.ok(x).build();
return res;
}
}
My Test Client is different
public class CustomerResourceTest
{
#Test
public void testCustomerResource() throws Exception
{
URL postUrl = new URL("http://localhost:9095/authorizationCheck/webserviceTest");
HttpURLConnection connection = (HttpURLConnection) postUrl.openConnection();
connection.setRequestMethod("POST");
System.out.println("Content-Type: " + connection.getContentType());
BufferedReader reader = new BufferedReader(new
InputStreamReader(connection.getInputStream()));
String line = reader.readLine();
while (line != null)
{
System.out.println(line);
line = reader.readLine();
}
Assert.assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode());
connection.disconnect();
return;
}
}
It produced output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><testDTO><fieldOne>ffff</fieldOne><fieldTwo>gggg</fieldTwo></testDTO>
Had to add following dependency also
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.2.11</version>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jaxb-provider</artifactId>
<version>2.2.0.GA</version>
</dependency>
Tried your code.
public void testCustomerResource() throws Exception
{
RegisterBuiltin.register(ResteasyProviderFactory.getInstance());
AuthorizationService proxy =
ProxyFactory.create(AuthorizationService.class,"http://localhost:9095/");
ClientResponse response = (ClientResponse) proxy.webserviceTest();
String str = (String)response.getEntity(String.class);
System.out.println(str);
return;
}
Produced same output
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><testDTO><fieldOne>ffff</fieldOne><fieldTwo>gggg</fieldTwo></testDTO>
Note how I created proxy. I had only base url **http://localhost:9095/**. I did not mention resources authorizationCheck/webserviceTest in that. This is different from how you coded.