Getting java.lang.IllegalStateException while mocking java.util.Properties using easymock - unit-testing

I am using easymock framework to write UT's. I have one class which uses java.util.Properties in public function. Below is sample code:
public URI generateSASURI() throws CloudStorageException, DataProcessingException {
final String token = "token";
try {
return new URI(URIUtils.getAssetURI(azureStorageProperties.getProperty(StorageConstant.STORAGE_ACCOUNT_NAME)
, cloudBlob).toString() + "?" + token);
} catch (URISyntaxException e) {
throw new DataProcessingException("Error while creating SAS URL " + e.getMessage(), e);
}
}
where azureStorageProperties is instance of java.util.Properties, which is created as bean and injected in class.
Now while writing unit test case , i am trying to mock Properties azureStorageProperties, i am getting below error:
Unable to evaluate the expression Method threw 'java.lang.IllegalStateException' exception.
Below is ss:
Below is class to be tested:
package com.company.ops.azure.storage;
import com.company.ops.azure.storage.constants.StorageConstant;
import com.company.ops.azure.storage.dto.CloudBlob;
import com.company.ops.cloudopsfacade.dto.SignedUrlDTO;
import com.company.ops.cloudopsfacade.exception.storage.CloudStorageException;
import com.company.ops.cloudopsfacade.exception.storage.DataProcessingException;
import com.company.ops.azure.storage.util.URIUtils;
import com.company.ops.cloudopsfacade.storage.ICloudStorageClient;
import com.microsoft.azure.storage.blob.CloudBlobClient;
import com.microsoft.azure.storage.blob.SharedAccessBlobHeaders;
import com.microsoft.azure.storage.blob.SharedAccessBlobPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.EnumSet;
import java.util.Optional;
import java.util.Properties;
import java.util.Set;
public class StorageClient implements ICloudStorageClient {
private static final Logger LOG = LoggerFactory.getLogger(StorageClient.class);
#Inject
private CloudBlobClient cloudBlobClient;
#Inject
Properties azureStorageProperties;
#Inject
private SASTokenGenerator sasTokenGenerator;
private long sasUrlDuration;
private Optional<String> sasUrlDurationKey;
public StorageClient() {
sasUrlDurationKey = Optional.ofNullable(System.getenv(StorageConstant.SAS_URL_DURATION_KEY));
if (sasUrlDurationKey.isPresent()) {
try {
sasUrlDuration = Integer.parseInt(sasUrlDurationKey.get());
} catch(NumberFormatException ex) {
LOG.debug("sasURLDurationKey invalid" + ex.getMessage());
sasUrlDuration = StorageConstant.DEFAULT_SAS_URL_DURATION;
}
} else {
sasUrlDuration = StorageConstant.DEFAULT_SAS_URL_DURATION;
}
}
//NOTE: This constructor is just created for test case. As #Mock of final class is NOT supported in easymock
public StorageClient(long sasUrlDuration, CloudBlobClient cloudBlobClient) {
this.sasUrlDuration = sasUrlDuration;
this.cloudBlobClient = cloudBlobClient;
}
/**
*
* #param containerName
* #param blob
* #param expiryTime
* #return {#link URI}
* #throws CloudStorageException
* #throws DataProcessingException
*/
private URI generateSASURI(String containerName,
String blob, Long expiryTime) throws CloudStorageException, DataProcessingException {
CloudBlob cloudBlob = new CloudBlob(Optional.ofNullable(containerName)
.orElseThrow(() -> new CloudStorageException("container name is null")),
Optional.ofNullable(blob).orElseThrow(() -> new CloudStorageException("blob name is null")));
//#TODO: Need to check permissions: Currently create and write assigned
final Set<SharedAccessBlobPermissions> permissions = EnumSet.of(SharedAccessBlobPermissions.WRITE, SharedAccessBlobPermissions.CREATE);
final SharedAccessBlobHeaders contentHeaders = new SharedAccessBlobHeaders();
//in case if duration need to set manually via api
if (Optional.ofNullable(expiryTime).isPresent()) {
sasUrlDuration = expiryTime;
}
sasTokenGenerator.sasTokenGeneratorInitializer(
cloudBlobClient,
cloudBlob,
permissions,
sasUrlDuration,
contentHeaders);
final String token = sasTokenGenerator.getToken();
try {
return new URI(URIUtils.getAssetURI(azureStorageProperties.getProperty(StorageConstant.STORAGE_ACCOUNT_NAME)
, cloudBlob).toString() + "?" + token);
} catch (URISyntaxException e) {
throw new DataProcessingException("Error while creating SAS URL " + e.getMessage(), e);
}
}
/**
*
* #param containerName
* #param blob
* #param expiryTime
* #return {#link URI}
* #throws CloudStorageException
* #throws DataProcessingException
*/
#Override
public SignedUrlDTO generateSignedUrl(String containerName, String blob, Long expiryTime)
throws CloudStorageException, DataProcessingException, MalformedURLException {
try {
URI uri = generateSASURI(containerName, blob, expiryTime);
SignedUrlDTO signedUrlDTO = new SignedUrlDTO();
signedUrlDTO.setSignedURL(uri.toURL());
return signedUrlDTO;
} catch (DataProcessingException ex) {
LOG.error(ex.getMessage());
throw ex;
} catch (CloudStorageException ex) {
LOG.error(ex.getMessage());
throw ex;
} catch (MalformedURLException e) {
LOG.error("Unable to get URL");
throw e;
}
}
}
Below is complete code for UT
package com.company.ops.azure.storage;
import com.company.ops.azure.constants.AzureConstants;
import com.company.ops.azure.storage.constants.StorageConstant;
import com.company.ops.azure.storage.util.URIUtils;
import com.company.ops.cloudopsfacade.dto.SignedUrlDTO;
import com.company.ops.cloudopsfacade.exception.storage.CloudStorageException;
import com.company.ops.cloudopsfacade.exception.storage.DataProcessingException;
import com.microsoft.azure.storage.StorageCredentials;
import com.microsoft.azure.storage.StorageCredentialsAccountAndKey;
import com.microsoft.azure.storage.blob.CloudBlobClient;
import org.easymock.*;
import static org.easymock.EasyMock.*;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.inject.Inject;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.util.Properties;
#RunWith(EasyMockRunner.class)
public class StorageClientTest extends EasyMockSupport {
private CloudBlobClient cloudBlobClient;
#Mock
private SASTokenGenerator sasTokenGenerator;
#Mock
private Properties azureStorageProperties;
#Mock
private StorageClient storageClient; /*= /*new StorageClient(StorageConstant.DEFAULT_SAS_URL_DURATION,
cloudBlobClient, azureStorageProperties);*/
#Before
public void setup() throws URISyntaxException {
resetAll();
}
#After
public void tearDown() {
verifyAll();
}
#Test
public void testGenerateSASURI() throws MalformedURLException, CloudStorageException, DataProcessingException {
String containerName = "myprojectlocal";
String blob = "testfile";
Long expiryTime = 1000L;
/*Properties azureStorageProperties = EasyMock.createMockBuilder(Properties.class)
.addMockedMethod("getProperty", String.class).createMock();*/
//azureStorageProperties = new Properties();
// azureStorageProperties.setProperty(StorageConstant.STORAGE_ACCOUNT_NAME, "storage-account-name");
expect(azureStorageProperties.getProperty(StorageConstant.STORAGE_ACCOUNT_NAME)).andReturn("storage-account-name");
expect(sasTokenGenerator.getToken()).andReturn("token");
sasTokenGenerator.sasTokenGeneratorInitializer(anyObject(CloudBlobClient.class),
anyObject(),
anyObject(),
anyLong(),
anyObject());
expectLastCall();
//azureStorageProperties.getProperty(anyString()); //.andReturn("storage-account-name");
//expectLastCall();
//expect(azureStorageProperties.getProperty(StorageConstant.STORAGE_ACCOUNT_NAME)).andReturn("storage-account-name");
replayAll();
SignedUrlDTO signedUrlDTO = storageClient.generateSignedUrl(containerName, blob, expiryTime);
Assert.assertNotNull(signedUrlDTO);
}
private CloudBlobClient getCloudBlobClient() {
final StorageCredentials credentials = new StorageCredentialsAccountAndKey(TestConstants.STORAGE_ACCOUNT_NAME,
TestConstants.STORAGE_ACCOUNT_KEY);
try {
return new CloudBlobClient(URIUtils.getStorageAccountURI(TestConstants.STORAGE_ACCOUNT_NAME), credentials);
} catch (URISyntaxException e) {}
return null;
}
}

Related

PubSub with CustomAttributes - Receiver function is not invoked but a json parse exception is coming up

Google Cloud and to PubSub Service.
I have implemented a simple CustomAttributeReceiver in the lines of below sample code
https://github.com/googleapis/java-pubsub/blob/master/samples/snippets/src/main/java/pubsub/PublishWithCustomAttributesExample.java
How ever i am getting the below exception
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected STRING but was BEGIN_OBJECT at path $ at com.google.gson.Gson.fromJson(Gson.java:944) at
com.google.gson.Gson.fromJson(Gson.java:1003) at
com.google.cloud.functions.invoker.NewBackgroundFunctionExecutor$TypedFunctionExecutor.serviceLegacyEvent(NewBackgroundFunctionExecutor.java:257) at
com.google.cloud.functions.invoker.NewBackgroundFunctionExecutor.serviceLegacyEvent(NewBackgroundFunctionExecutor.java:343) at
Can someone throw light on what i am missing here?
Publisher side
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.api.core.ApiFuture;
import com.google.cloud.pubsub.v1.Publisher;
import com.google.protobuf.ByteString;
import com.google.pubsub.v1.PubsubMessage;
import com.google.pubsub.v1.TopicName;
import PubSubMessage;
TopicName topicName = TopicName.of(projectId, topicId);
System.out.println("informListenersAboutSucessfulRegisteration=" + topicName);
Publisher publisher = null;
try {
publisher = Publisher.newBuilder(topicName).build();
PubSubMessage newUserRegisterMsg = new PubSubMessage();
Map<String, String> attributes = new HashMap<String, String>();
attributes.put(PubSubMessage.newUserLanguage, newUserLanguage);
newUserRegisterMsg.setAttributes(attributes);
ByteString data = ByteString.copyFromUtf8("NewUserRegisteration");
PubsubMessage pubsubMessage = PubsubMessage.newBuilder().setData(data).putAllAttributes(attributes).build();
ApiFuture<String> messageIdFuture = publisher.publish(pubsubMessage);
String messageId = messageIdFuture.get();
System.out.println("Published message ID: " + messageId);
} catch (Exception e) {
Logger.getLogger(PubSubMessenger.name).log(Level.SEVERE, "Exception while publishing message", e);
} finally {
if (publisher != null) {
publisher.shutdown();
publisher.awaitTermination(1, TimeUnit.MINUTES);
}
}
Receiver side
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import com.google.cloud.functions.BackgroundFunction;
import com.google.cloud.functions.Context;
import PubSubMessage;
public class SendEmailFromSendGrid implements BackgroundFunction<PubSubMessage> {
public SendEmailFromSendGrid() {
}
public void accept(PubSubMessage message, Context context) throws Exception {
System.out.println("invoked accept");
String name = "World";
if (message != null && message.getData() != null) {
name = new String(Base64.getDecoder().decode(message.getData().getBytes(StandardCharsets.UTF_8)),
StandardCharsets.UTF_8);
}
System.out.println(String.format("Hello %s!", name));
return;
}
}
PubSubMessage Definition
import java.util.Map;
public class PubSubMessage {
public static final String newUserLanguage = "userLanguage";
private String data;
private Map<String, String> attributes;
private String messageId;
private String publishTime;
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
public String getMessageId() {
return messageId;
}
public void setMessageId(String messageId) {
this.messageId = messageId;
}
public String getPublishTime() {
return publishTime;
}
public void setPublishTime(String publishTime) {
this.publishTime = publishTime;
}
}
THANK YOU
This answer was provided by #user1241724 in the comment section:
Redid the whole exercise and it is working now. Only difference is
added default constructor in PubSubMessage.

How to apply Interceptor(Schema validation) to a specific endpoint among multiple services deployed on server

I have two soap end points(soap services) deployed in one server. When i override the following interceptor, it is applying to both services. How to enable/disable the interceptor specific to one service. Kindly help
The interceptor code as follows.
#Override
public void addInterceptors(List<EndpointInterceptor> interceptors) {
PayloadValidatingInterceptor validatingInterceptor = new PayloadValidatingInterceptor();
validatingInterceptor.setValidateRequest(true);
validatingInterceptor.setValidateResponse(true);
validatingInterceptor.setXsdSchemaCollection(LogAnalyzerFile());
interceptors.add(validatingInterceptor);
}
Note: Its an spring boot project, using annotations.
I
package com.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
import org.springframework.ws.WebServiceMessage;
import org.springframework.ws.config.annotation.EnableWs;
import org.springframework.ws.config.annotation.WsConfigurationSupport;
import org.springframework.ws.context.MessageContext;
import org.springframework.ws.server.SmartEndpointInterceptor;
import org.springframework.ws.server.endpoint.MethodEndpoint;
import org.springframework.ws.soap.SoapBody;
import org.springframework.ws.soap.SoapHeader;
import org.springframework.ws.soap.SoapMessage;
import org.springframework.ws.transport.http.MessageDispatcherServlet;
import org.springframework.ws.wsdl.wsdl11.SimpleWsdl11Definition;
import org.springframework.ws.wsdl.wsdl11.Wsdl11Definition;
import org.springframework.xml.xsd.SimpleXsdSchema;
import org.springframework.xml.xsd.XsdSchema;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMResult;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
#EnableWs
#Configuration
public class TestConfig extends WsConfigurationSupport implements SmartEndpointInterceptor {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
#Bean(name="testlog")
public ServletRegistrationBean testlog(ApplicationContext applicationContext) {
MessageDispatcherServlet servlet = new MessageDispatcherServlet();
servlet.setApplicationContext(applicationContext);
servlet.setTransformWsdlLocations(true);
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(servlet, "/File/*");
servletRegistrationBean.setName("Log");
return servletRegistrationBean;
}
#Bean(name = "testFile")
public Wsdl11Definition testFile()
{
SimpleWsdl11Definition wsdl11Definition = new SimpleWsdl11Definition();
wsdl11Definition.setWsdl(new ClassPathResource("test.wsdl"));
logger.info("test.wsdl:");
return wsdl11Definition;
}
#Bean(name = "UploadLogFile")
public XsdSchema UploadLogFile() {
return new SimpleXsdSchema(new ClassPathResource("1.xsd"));
}
#Bean(name = "ErrorInfo")
public XsdSchema ErrorInfo() {
return new SimpleXsdSchema(new ClassPathResource("2.xsd"));
}
public Resource[] getSchemas() {
List<Resource> schemaResources = new ArrayList<>();
schemaResources.add(new ClassPathResource("1.xsd"));
schemaResources.add(new ClassPathResource("2.xsd"));
return schemaResources.toArray(new Resource[schemaResources.size()]);
}
#Override
public boolean shouldIntercept(MessageContext messageContext, Object endpoint) {
if (endpoint instanceof MethodEndpoint) {
MethodEndpoint methodEndpoint = (MethodEndpoint)endpoint;
return methodEndpoint.getMethod().getDeclaringClass() == YourEndpoint.class;
}
return false;
}
private Boolean validateSchema(Source source_, MessageContext messageContext) throws Exception {
boolean errorFlag = true;
SchemaFactory _schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema _schema = _schemaFactory.newSchema(getSchemas()[0].getFile());
Validator _validator = _schema.newValidator();
DOMResult _result = new DOMResult();
try {
_validator.validate(source_, _result);
} catch (SAXException _exception) {
errorFlag = false;
SoapMessage response = (SoapMessage) messageContext.getResponse();
String faultString = StringUtils.hasLength(_exception.getMessage()) ? _exception.getMessage() : _exception.toString();
SoapBody body = response.getSoapBody();
body.addServerOrReceiverFault(faultString, Locale.US);
_exception.printStackTrace();
}
return errorFlag;
}
#Override
public boolean handleRequest(MessageContext messageContext, Object endpoint) throws Exception {
WebServiceMessage webServiceMessageRequest = messageContext.getRequest();
SoapMessage soapMessage = (SoapMessage) webServiceMessageRequest;
SoapHeader soapHeader = soapMessage.getSoapHeader();
Source bodySource = soapMessage.getSoapBody().getPayloadSource();
return validateSchema(bodySource,messageContext);
}
#Override
public boolean handleResponse(MessageContext messageContext, Object endpoint) throws Exception {
return true;
}
#Override
public boolean handleFault(MessageContext messageContext, Object endpoint) throws Exception {
return false;
}
#Override
public void afterCompletion(MessageContext messageContext, Object endpoint, Exception ex) throws Exception {
}
}

EnergyStar Portfolio Manager - Java Client to consume their REST API with Authentication

I am a straight up newbie. After 2 weeks of research, I've arrived at this point, still very lost and desperate.
My goal: Retrieve data from EnergyStar Portfolio Manager Restful web services / API and put that data into a SQL database or an excel worksheet.
Progress so far:
1) I found an example code that seems like it would fit what I need well, except for the authentication part. I am more successful at getting WSDL services to work than RESTful services. Particularly for EnergySTAR, requiring some kind of authentication, which I can't seem to get around to.
2) The retrieve GET protocol: http://portfoliomanager.energystar.gov/webservices/home/test/api/reporting/designMetrics/get
My source code:
package com;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import com.User;
#Path("/wstest/property/")
public class UserManagementModule
{
#GET
#Path("/{propertyId}/design/metrics?measurementSystem=METRIC")
#Produces("application/xml")
public Response getUserById(#PathParam("propertyId") Integer id)
{
User user = new User();
user.setId(id);
return Response.status(200).entity(user).build();
}
}
package com;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlAccessorType(XmlAccessType.NONE)
#XmlRootElement(name = "propertyMetrics")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#XmlAttribute(name = "propertyId")
private int propertyId;
#XmlElement(name="metric")
private double metric;
#XmlAttribute(name = "designEnergyCost")
private double designEnergyCost;
#XmlAttribute(name = "designScore")
private double designScore;
#XmlAttribute(name = "designSiteTotal")
private double designSiteTotal;
#XmlAttribute(name = "designSiteIntensity")
private double designSiteIntensity;
#XmlAttribute(name = "designTargetEnergyCost")
private double designTargetEnergyCost;
#XmlAttribute(name = "designTargetTotalGHGEmissions")
private double designTargetTotalGHGEmissions;
#XmlAttribute(name = "designTargetSiteTotal")
private double designTargetSiteTotal;
#XmlAttribute(name = "designTargetSiteIntensity")
private double designTargetSiteIntensity;
#XmlAttribute(name = "designTargetSourceTotal")
private double designTargetSourceTotal;
#XmlAttribute(name = "designTargetSourceIntensity")
private double designTargetSourceIntensity;
#XmlAttribute(name = "medianEnergyCost")
private double medianEnergyCost;
#XmlAttribute(name = "medianTotalGHGEmissions")
private double medianTotalGHGEmissions;
#XmlAttribute(name = "medianScore")
private double medianScore;
public int getId() {
return propertyId;
}
public void setId(int propertyId) {
this.propertyId = propertyId;
}
public double getmendianScore() {
return medianScore;
}
//
// public void setFirstName(String firstName) {
// this.firstName = firstName;
// }
// public String getLastName() {
// return lastName;
// }
// public void setLastName(String lastName) {
// this.lastName = lastName;
// }
}
package tests;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import com.User;
public class RestClientXML {
public static void main(String[] args)
{
try
{
URL url = new URL(" https://portfoliomanager.energystar.gov/wstest/");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/xml");
if (conn.getResponseCode() != 200)
{
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String apiOutput = br.readLine();
System.out.println(apiOutput);
conn.disconnect();
JAXBContext jaxbContext = JAXBContext.newInstance(User.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
User user = (User) jaxbUnmarshaller.unmarshal(new StringReader(apiOutput));
System.out.println(user.getId());
/* System.out.println(user.getFirstName());
System.out.println(user.getLastName());
*/
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JAXBException e) {
e.printStackTrace();
}
}
}
I'm know there is some authentication that needs username and pw,so I also tried this piece instead of the RestClient class, but neither works.
public static void main(String[] args) {
CloseableHttpClient httpClient = null;
HttpPost httpPost = null;
CloseableHttpResponse response = null;
try {
httpClient = HttpClients.createDefault();
httpPost = new HttpPost("https://portfoliomanager.energystar.gov/wstest/");
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("content-type", "application/xml"));
StringEntity input = new StringEntity("{\"username\": \"yungv1\",\"password\": \"dummypassword\"}");
input.setContentType("application/xml");
httpPost.setEntity(input);
for (NameValuePair h : nvps)
{
httpPost.addHeader(h.getName(), h.getValue());
}
response = httpClient.execute(httpPost);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(response.getEntity().getContent())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
response.close();
httpClient.close();
}catch(Exception ex) {
ex.printStackTrace();
}
}
I know it's very sloppy. Can you please point the direction on how I can achieve my goal?
I also tried to run this, and keep getting the 401 errors, which I imagined the authentication fails. I don't know how else to trouble shoot this part and whether there's more thing I need to look into.
conn.setRequestProperty("Authorization", "Basic " + Base64.encodeBase64String((getWebServicesUsername() + ":" + getWebServicesPassword()).getBytes()));
Where conn is HttpURLConnection.

getting an error with webservices

Im doing restfull webservices with soap using websphere and RAD. After generating my javaclient classes when I run the test class I get the following error. Ive been searching the web but not finding the correct solution. PLEASE HELP!
ERROR:
Check method call
org.w3c.dom.DOMException: HIERARCHY_REQUEST_ERR: An attempt was made to insert a node where it is not permitted.
at org.apache.xerces.dom.CoreDocumentImpl.insertBefore(Unknown Source)
at org.apache.xerces.dom.NodeImpl.appendChild(Unknown Source)
at com.ibm.ws.webservices.engine.xmlsoap.SOAPPart.appendChild(SOAPPart.java:282)
at com.sun.xml.internal.bind.marshaller.SAX2DOMEx.startElement(SAX2DOMEx.java:177)
at com.sun.xml.internal.ws.message.AbstractMessageImpl.writeTo(AbstractMessageImpl.java:159)
at com.sun.xml.internal.ws.message.AbstractMessageImpl.readAsSOAPMessage(AbstractMessageImpl.java:194)
at com.sun.xml.internal.ws.handler.SOAPMessageContextImpl.getMessage(SOAPMessageContextImpl.java:80)
at test.CustomSoapHandler.handleMessage(CustomSoapHandler.java:37)
at test.CustomSoapHandler.handleMessage(CustomSoapHandler.java:1)
at com.sun.xml.internal.ws.handler.HandlerProcessor.callHandleMessage(HandlerProcessor.java:293)
at com.sun.xml.internal.ws.handler.HandlerProcessor.callHandlersRequest(HandlerProcessor.java:134)
at com.sun.xml.internal.ws.handler.ClientSOAPHandlerTube.callHandlersOnRequest(ClientSOAPHandlerTube.java:139)
at com.sun.xml.internal.ws.handler.HandlerTube.processRequest(HandlerTube.java:117)
at com.sun.xml.internal.ws.api.pipe.Fiber.__doRun(Fiber.java:599)
at com.sun.xml.internal.ws.api.pipe.Fiber._doRun(Fiber.java:558)
at com.sun.xml.internal.ws.api.pipe.Fiber.doRun(Fiber.java:543)
at com.sun.xml.internal.ws.api.pipe.Fiber.runSync(Fiber.java:440)
at com.sun.xml.internal.ws.client.Stub.process(Stub.java:223)
at com.sun.xml.internal.ws.client.sei.SEIStub.doProcess(SEIStub.java:136)
at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:110)
at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:90)
at com.sun.xml.internal.ws.client.sei.SEIStub.invoke(SEIStub.java:119)
at $Proxy33.getHistory(Unknown Source)
at test.ServiceTest.historyTest(ServiceTest.java:64)
at test.ServiceTest.main(ServiceTest.java:100)
Exception in thread "main" java.lang.ExceptionInInitializerError
at java.lang.J9VMInternals.initialize(J9VMInternals.java:227)
at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:119)
at com.sun.xml.internal.ws.client.sei.SyncMethodHandler.invoke(SyncMethodHandler.java:90)
at com.sun.xml.internal.ws.client.sei.SEIStub.invoke(SEIStub.java:119)
at $Proxy33.getHistory(Unknown Source)
at test.ServiceTest.historyTest(ServiceTest.java:64)
at test.ServiceTest.main(ServiceTest.java:100)
Caused by: java.lang.ClassCastException: com.ibm.xml.xlxp2.jaxb.JAXBContextImpl incompatible with com.sun.xml.internal.bind.api.JAXBRIContext
at java.lang.ClassCastException.<init>(ClassCastException.java:58)
at com.sun.xml.internal.ws.fault.SOAPFaultBuilder.<clinit>(SOAPFaultBuilder.java:545)
at java.lang.J9VMInternals.initializeImpl(Native Method)
at java.lang.J9VMInternals.initialize(J9VMInternals.java:205)
... 6 more
Test Class:
package test;
import be.ipc.css.ws.GcssWebServiceService;
import be.ipc.css.ws.IGcssWebService;
import be.ipc.css.ws.InvalidItemIdStructureFault_Exception;
import be.ipc.css.ws.ProductNotAllowedFault_Exception;
import be.ipc.css.ws.common.Product;
import be.ipc.css.ws.history.GetHistoryInput;
import be.ipc.css.ws.history_output.GetHistoryOutput;
import be.ipc.css.ws.history_output.HistoryItem;
import be.ipc.css.ws.history_output.Type;
import javax.xml.namespace.QName;
import javax.xml.ws.BindingProvider;
import javax.xml.ws.Service;
import javax.xml.ws.handler.Handler;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* <strong>Project: TODO: project name</strong><br/>
* <b>Url:</b> TODO: url<br/>
* <b>Date:</b> 15.05.14<br/>
* <b>Time:</b> 23:42 <br/>
* Copyright(C) 2014 IT Service Plus <br/>
* <b>Description:</b><br/>
* TODO: description
*/
public class ServiceTest {
private static Service webService;
private static IGcssWebService servicePort;
public void initService() throws MalformedURLException {
URL url = new URL("http://cs-demo.ipc.be/CSS_UA2/services/gcssWebService/1.0");
QName qname = new QName("http://ws.css.ipc.be/", "GcssWebServiceService");
/*java.util.Properties props = System.getProperties();
props.setProperty("http.proxyHost", "proxy.test.com");
props.setProperty("http.proxyPort", "8080");*/
webService = GcssWebServiceService.create(url, qname);
servicePort = webService.getPort(IGcssWebService.class);
try {
CustomSoapHandler sh = new CustomSoapHandler("user_us", "*******");
List<Handler> new_handlerChain = new ArrayList<Handler>();
new_handlerChain.add(sh);
((BindingProvider)servicePort).getBinding().setHandlerChain(new_handlerChain);
} catch (Throwable e) {
e.printStackTrace();
}
//((BindingProvider)servicePort).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "user_us");
//((BindingProvider)servicePort).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "*******");
}
public void historyTest() throws ProductNotAllowedFault_Exception, InvalidItemIdStructureFault_Exception {
GetHistoryInput input = new GetHistoryInput();
input.setItemId("CC027607063NL");
input.setProduct(Product.EPG);
System.out.println("Check method call");
GetHistoryOutput output = servicePort.getHistory(input);
System.out.println("Check result");
//Assert.assertNotNull(output);
//Assert.assertNotNull(output.getHistory());
//Assert.assertNotNull(output.getHistory().getHistoryItem());
System.out.println("Received: " + output.getHistory().getHistoryItem().size() + "elements:");
System.out.println("-----------------------");
for(int i=0;i<output.getHistory().getHistoryItem().size();i++) {
HistoryItem it = output.getHistory().getHistoryItem().get(i);
System.out.println("#" + i + ": id=" + it.getId() + ", type=" + it.getType().value());
}
System.out.println("Check 3 history items");
//Assert.assertEquals(3, output.getHistory().getHistoryItem().size());
HistoryItem it1 = output.getHistory().getHistoryItem().get(0);
HistoryItem it2 = output.getHistory().getHistoryItem().get(1);
HistoryItem it3 = output.getHistory().getHistoryItem().get(2);
/*Assert.assertEquals(Type.QUMQ, it1.getType());
Assert.assertEquals(161L, it1.getId());
Assert.assertEquals(Type.SUM, it2.getType());
Assert.assertEquals(652L, it2.getId());
Assert.assertEquals(Type.L_1_Q, it3.getType());
Assert.assertEquals(13742L, it3.getId());*/
}
public static void main(String[] args) {
ServiceTest test = new ServiceTest();
try {
test.initService();
test.historyTest();
} catch(Exception e ){
e.printStackTrace();
}
}
}
Soap Handler:
package test;
import javax.xml.namespace.QName;
import javax.xml.soap.*;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import java.util.Set;
/**
* <strong>Project: TODO: project name</strong><br/>
* <b>Url:</b> TODO: url<br/>
* <b>Date:</b> 16.05.14<br/>
* <b>Time:</b> 0:48 <br/>
* Copyright(C) 2014 IT Service Plus <br/>
* <b>Description:</b><br/>
* TODO: description
*/
public class CustomSoapHandler implements SOAPHandler<SOAPMessageContext> {
private static final String AUTH_PREFIX = "wsse";
private static final String AUTH_NS =
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
private String username;
private String password;
public CustomSoapHandler(String username, String password) {
this.username = username;
this.password = password;
}
public boolean handleMessage(SOAPMessageContext context) {
try {
SOAPEnvelope envelope =
context.getMessage().getSOAPPart().getEnvelope();
SOAPFactory soapFactory = SOAPFactory.newInstance();
SOAPElement wsSecHeaderElm =
soapFactory.createElement("Security", AUTH_PREFIX, AUTH_NS);
Name wsSecHdrMustUnderstandAttr =
soapFactory.createName("mustUnderstand", "S",
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
wsSecHeaderElm.addAttribute(wsSecHdrMustUnderstandAttr, "1");
SOAPElement userNameTokenElm =
soapFactory.createElement("UsernameToken", AUTH_PREFIX,
AUTH_NS);
Name userNameTokenIdName =
soapFactory.createName("id", "wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd");
userNameTokenElm.addAttribute(userNameTokenIdName,
"UsernameToken-ORbTEPzNsEMDfzrI9sscVA22");
SOAPElement userNameElm =
soapFactory.createElement("Username", AUTH_PREFIX, AUTH_NS);
userNameElm.addTextNode(username);
SOAPElement passwdElm =
soapFactory.createElement("Password", AUTH_PREFIX, AUTH_NS);
Name passwdTypeAttr = soapFactory.createName("Type");
passwdElm.addAttribute(passwdTypeAttr,
"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText");
passwdElm.addTextNode(password);
userNameTokenElm.addChildElement(userNameElm);
userNameTokenElm.addChildElement(passwdElm);
wsSecHeaderElm.addChildElement(userNameTokenElm);
if (envelope.getHeader() == null) {
SOAPHeader sh = envelope.addHeader();
sh.addChildElement(wsSecHeaderElm);
} else {
SOAPHeader sh = envelope.getHeader();
sh.addChildElement(wsSecHeaderElm);
}
} catch (Throwable e) {
e.printStackTrace();
}
return true;
}
#Override
public boolean handleFault(SOAPMessageContext context) {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
#Override
public void close(MessageContext context) {
//To change body of implemented methods use File | Settings | File Templates.
}
#Override
public Set<QName> getHeaders() {
return null;
}
}
The main reason for your error is incompatible JAXB implementation classes:
aused by: java.lang.ClassCastException: com.ibm.xml.xlxp2.jaxb.JAXBContextImpl incompatible with com.sun.xml.internal.bind.api.JAXBRIContext
Probably the best way to fix this is packaging your own version of JAXB within your application(inside the lib folder) and than change the class loader from WebSphere to be Parent Last.
After that, restart and try it again. If still doesn't work you can try adding your JAXB implementation libraries directly to the Application Server classloader. You can do that creating a directory under $WEBSPHERE_HOME/AppServer/classes and placing your JAXB implementation classes there. Be aware that this approach adds the dropped jars to all WebSphere instances running using this binary codebase.
You can learn more about WebSphere classloaders.
Hope this helps.

Issue on Validation using regex on validator class of spring

My requirement is that i want validation on my form field i m doing so using spring validator class and regex so what i m doing here, i am validating my DepartmentNamefield which is in String contains no numeric value any where. This validation i m performing using regex expression [0-9] because if it contains any numeric value then matcher.find() return true if it return true i am throwing error message .So problem i am facing is that when i am providing the string with non numeric value validation is done but if i m providing the pure string then still its throwing same message if i run the application again with providing pure String value then its working, but if again i am providing wrong entry ,validation is happening but after that if m providing the correct entry the same message throw so every time i need to run my application please resolve this issue
here is my validator class
package com.ankur.tutorial.validator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import com.nousinfo.tutorial.service.model.DepartmentBO;
public class DepartmentValidator implements Validator {
boolean found = false;
public boolean supports(Class<?> arg0) {
return DepartmentBO.class.isAssignableFrom(arg0);
}
public void validate(Object object, Errors errors) {
DepartmentBO departmentBO = (DepartmentBO) (object);
System.out.println(departmentBO.getDepartmentName());
if (departmentBO.getDepartmentName().equals("")) {
errors.rejectValue("departmentName", "department.Name");
} else {
Pattern pattern = Pattern.compile("[0-9]");
Matcher matcher = pattern.matcher(departmentBO.getDepartmentName());
while (matcher.find()) {
found = true;
}
System.out.println(found);
if (found) {
errors.rejectValue("departmentName", "department.string");
}
}
}
}
this is my controller
package com.nousinfo.tutorial.controllers;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.nousinfo.tutorial.model.DepartmentForm;
import com.nousinfo.tutorial.service.impl.DepartmentServiceImpl;
import com.nousinfo.tutorial.service.model.DepartmentBO;
import com.nousinfo.tutorial.validator.DepartmentValidator;
#Controller
#RequestMapping("departmentController")
public class DepartmentController {
private DepartmentServiceImpl departmentServiceImpl;
private DepartmentValidator departmentValidator;
public DepartmentServiceImpl getDepartmentServiceImpl() {
return departmentServiceImpl;
}
public void setDepartmentServiceImpl(
DepartmentServiceImpl departmentServiceImpl) {
this.departmentServiceImpl = departmentServiceImpl;
}
public DepartmentValidator getDepartmentValidator() {
return departmentValidator;
}
public void setDepartmentValidator(DepartmentValidator departmentValidator) {
this.departmentValidator = departmentValidator;
}
/**
* Set to set the view
*
* #param model
* #return
* #throws Exception
*/
#RequestMapping(value = "/departmentForm", method = RequestMethod.GET)
public String view(Model model) throws Exception {
DepartmentBO departmentBO = new DepartmentBO();
model.addAttribute("departmentBO", departmentBO);
return "departmentForm";
}
/**
* Create the department
*
* #param departmentForm
* #param bindingResult
* #param model
* #return
* #throws Exception
*/
#RequestMapping(value = "/createDepartment", method = RequestMethod.POST)
public ModelAndView createEmployee(
#ModelAttribute("departmentBO") DepartmentBO departmentBO,
BindingResult bindingResult) throws Exception {
ModelAndView modelAndView = new ModelAndView();
departmentValidator.validate(departmentBO, bindingResult);
if (bindingResult.hasErrors()) {
modelAndView.setViewName("departmentForm");
return modelAndView;
}
modelAndView.addObject("departmentBO", departmentBO);
if (departmentBO.getUpdateStatus() == 'A') {
boolean flag = departmentServiceImpl.actionDecider(departmentBO);
if (flag == false)
modelAndView.setViewName("DBError");
else
modelAndView.setViewName("Success");
}
return modelAndView;
}
You have the variable found as a class property. Validators are singleton. Move the variable found inside the validate method.