Java Examples for javax.xml.ws.WebServiceException
The following java examples will help you to understand the usage of javax.xml.ws.WebServiceException. These source code samples are taken from different open source projects.
Example 1
| Project: cxf-master File: SequenceTest.java View source code |
private void doTestTwowayNoDuplicates(String cfg) throws Exception {
init(cfg);
class MessageNumberInterceptor extends AbstractPhaseInterceptor<Message> {
MessageNumberInterceptor() {
super(Phase.PRE_STREAM);
}
public void handleMessage(Message m) {
RMProperties rmps = RMContextUtils.retrieveRMProperties(m, true);
if (null != rmps && null != rmps.getSequence()) {
rmps.getSequence().setMessageNumber(new Long(1));
}
}
}
greeterBus.getOutInterceptors().add(new MessageNumberInterceptor());
RMManager manager = greeterBus.getExtension(RMManager.class);
manager.getConfiguration().setBaseRetransmissionInterval(new Long(2000));
greeter.greetMe("one");
try {
((BindingProvider) greeter).getRequestContext().put("cxf.synchronous.timeout", 5000);
String s = greeter.greetMe("two");
fail("Expected timeout. Received response: " + s);
} catch (WebServiceException ex) {
assertTrue("Unexpected exception cause", ex.getCause() instanceof IOException);
IOException ie = (IOException) ex.getCause();
assertTrue("Unexpected IOException message", ie.getMessage().startsWith("Timed out"));
}
// wait for resend to occur
awaitMessages(4, 3, 5000);
MessageFlow mf = new MessageFlow(outRecorder.getOutboundMessages(), inRecorder.getInboundMessages(), Names200408.WSA_NAMESPACE_NAME, RM10Constants.NAMESPACE_URI);
// Expected outbound:
// CreateSequence
// + two requests
// + acknowledgement
String[] expectedActions = new String[4];
expectedActions[0] = RM10Constants.CREATE_SEQUENCE_ACTION;
expectedActions[1] = GREETME_ACTION;
expectedActions[2] = GREETME_ACTION;
expectedActions[3] = RM10Constants.SEQUENCE_ACKNOWLEDGMENT_ACTION;
mf.verifyActions(expectedActions, true);
mf.verifyMessageNumbers(new String[] { null, "1", "1", null }, true);
mf.verifyLastMessage(new boolean[expectedActions.length], true);
mf.verifyAcknowledgements(new boolean[] { false, false, false, true }, true);
// Expected inbound:
// createSequenceResponse
// + 1 response without acknowledgement
// + 1 acknowledgement/last message
mf.verifyMessages(3, false);
expectedActions = new String[] { RM10Constants.CREATE_SEQUENCE_RESPONSE_ACTION, GREETME_RESPONSE_ACTION, RM10Constants.SEQUENCE_ACKNOWLEDGMENT_ACTION };
mf.verifyActions(expectedActions, false);
mf.verifyMessageNumbers(new String[] { null, "1", null }, false);
mf.verifyAcknowledgements(new boolean[] { false, false, true }, false);
}Example 2
| Project: siu-master File: ClientProtocolImpl.java View source code |
private ClientResponse getClientResponse(URL wsdlUrl, ClientLog clientLog, NormalizedRequest normalizedRequest, SOAPMessage soapRequest) {
Dispatch<SOAPMessage> dispatch = createSoapMessageDispatch(wsdlUrl, normalizedRequest);
final Map<String, Object> ctx = dispatch.getRequestContext();
logger.finest("Use address '" + normalizedRequest.portSoapAddress + "' for " + normalizedRequest.action);
if (clientLog != null) {
ctx.put(ClientLog.class.getName(), clientLog);
}
ctx.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, normalizedRequest.portSoapAddress);
final String soapAction = normalizedRequest.operation.soapAction;
if (soapAction != null) {
ctx.put(BindingProvider.SOAPACTION_USE_PROPERTY, true);
ctx.put(BindingProvider.SOAPACTION_URI_PROPERTY, soapAction);
}
ClientResponse clientResponse;
try {
clientResponse = processResult(dispatch.invoke(soapRequest));
} catch (SOAPException e) {
throw new RuntimeException(e);
} catch (WebServiceException e) {
logger.log(Level.WARNING, "GWS fail " + e.getLocalizedMessage());
Throwable cause = e.getCause();
while (cause instanceof RuntimeException) {
Throwable root = cause.getCause();
if (root == null) {
break;
}
cause = root;
}
if (cause instanceof IOException) {
throw new RuntimeException(cause);
}
if (cause instanceof RuntimeException) {
throw (RuntimeException) cause;
}
throw e;
}
logResponse(clientLog, clientResponse);
return clientResponse;
}Example 3
| Project: camel-master File: CamelDestinationTest.java View source code |
@Test
public void testCAMEL4073() throws Exception {
try {
Endpoint.publish("camel://foo", new Person() {
public void getPerson(Holder<String> personId, Holder<String> ssn, Holder<String> name) throws UnknownPersonFault {
}
});
fail("Should throw and Exception");
} catch (WebServiceException ex) {
Throwable c = ex.getCause();
assertNotNull(c);
assertTrue(c instanceof NoSuchEndpointException);
}
}Example 4
| Project: jbossws-cxf-master File: SecurityDomainTestCase.java View source code |
private void testOneWay(SecureEndpoint port) throws Exception {
try {
port.helloOneWay("Hello");
fail("Authentication exception expected!");
} catch (Exception e) {
e.printStackTrace();
assertTrue(e.getMessage().contains("Could not send Message"));
assertTrue("Exception Cause message: " + e.getCause().getMessage(), e.getCause().getMessage().contains("401: Unauthorized"));
}
((BindingProvider) port).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "bob");
((BindingProvider) port).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "foo");
try {
port.helloOneWay("Hello");
fail("Authorization exception expected!");
} catch (WebServiceException e) {
}
((BindingProvider) port).getRequestContext().put(BindingProvider.USERNAME_PROPERTY, "john");
((BindingProvider) port).getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, "bar");
try {
port.helloOneWay("Hello");
} catch (Exception e) {
fail("exception is unexpected!");
}
}Example 5
| Project: narayana-master File: XTSServiceTestInterpreter.java View source code |
/// implementation of the interpreter functionality
/**
* simple command interpreter which executes the commands in the command list, inserting the
* corresponding results in the results list and using the supplied bindings list
* to provide values for any parameters supplied in the commands and to bind any results
* obtained by executing the commands
*
* @param commandList a list of command strings
* @param resultsList a list into which results strings are to be inserted
* @param bindings a list of bound variables to be substituted into commands
* or updated with new bindings
*/
private void processCommands(List<String> commandList, List<String> resultsList, HashMap<String, String> bindings) throws WebServiceException {
int size = commandList.size();
if (size == 0) {
throw new WebServiceException("empty command list");
}
String command = commandList.remove(0);
size--;
if (command.equals("block")) {
// we don't bind the command block immediately since bindings may be produced
// by intermediate bind commands
processCommandBlock(commandList, resultsList, bindings);
} else {
int idx = 0;
if (command.equals("enlistDurable")) {
// enlistment commands
bindCommands(commandList, bindings);
String id = participantId("DurableTestParticipant");
DurableTestParticipant participant = new DurableTestParticipant(id);
TransactionManager txman = TransactionManagerFactory.transactionManager();
try {
txman.enlistForDurableTwoPhase(participant, id);
} catch (Exception e) {
throw new WebServiceException("enlistDurable failed ", e);
}
for (idx = 0; idx < size; idx++) {
participant.addCommand(commandList.get(idx));
}
participantMap.put(id, participant);
resultsList.add(id);
} else if (command.equals("enlistVolatile")) {
bindCommands(commandList, bindings);
String id = participantId("VolatileTestParticipant");
VolatileTestParticipant participant = new VolatileTestParticipant(id);
TransactionManager txman = TransactionManagerFactory.transactionManager();
try {
txman.enlistForVolatileTwoPhase(participant, id);
} catch (Exception e) {
throw new WebServiceException("enlistVolatile failed ", e);
}
for (idx = 0; idx < size; idx++) {
participant.addCommand(commandList.get(idx));
}
participantMap.put(id, participant);
resultsList.add(id);
} else if (command.equals("enlistCoordinatorCompletion")) {
bindCommands(commandList, bindings);
String id = participantId("CoordinatorCompletionParticipant");
CoordinatorCompletionTestParticipant participant = new CoordinatorCompletionTestParticipant(id);
BusinessActivityManager baman = BusinessActivityManagerFactory.businessActivityManager();
try {
BAParticipantManager partMan;
partMan = baman.enlistForBusinessAgreementWithCoordinatorCompletion(participant, id);
managerMap.put(id, partMan);
} catch (Exception e) {
throw new WebServiceException("enlistCoordinatorCompletion failed ", e);
}
for (idx = 0; idx < size; idx++) {
participant.addCommand(commandList.get(idx));
}
participantMap.put(id, participant);
resultsList.add(id);
} else if (command.equals("enlistParticipantCompletion")) {
bindCommands(commandList, bindings);
String id = participantId("ParticipantCompletionParticipant");
ParticipantCompletionTestParticipant participant = new ParticipantCompletionTestParticipant(id);
BusinessActivityManager baman = BusinessActivityManagerFactory.businessActivityManager();
try {
BAParticipantManager partMan;
partMan = baman.enlistForBusinessAgreementWithParticipantCompletion(participant, id);
managerMap.put(id, partMan);
} catch (Exception e) {
throw new WebServiceException("enlistParticipantCompletion failed ", e);
}
for (idx = 0; idx < size; idx++) {
participant.addCommand(commandList.get(idx));
}
participantMap.put(id, participant);
resultsList.add(id);
} else if (command.equals("addCommands")) {
// add extra commands to a participant script
bindCommands(commandList, bindings);
String id = commandList.remove(idx);
size--;
ScriptedTestParticipant participant = participantMap.get(id);
if (participant != null) {
for (idx = 0; idx < size; idx++) {
participant.addCommand(commandList.get(idx));
}
resultsList.add("ok");
} else {
throw new WebServiceException("addCommands failed to find participant " + id);
}
} else if (command.equals("exit")) {
// initiate BA manager activities
bindCommands(commandList, bindings);
String id = commandList.remove(idx);
size--;
ScriptedTestParticipant participant = participantMap.get(id);
if (participant != null) {
if (participant instanceof ParticipantCompletionTestParticipant) {
ParticipantCompletionTestParticipant baparticipant = (ParticipantCompletionTestParticipant) participant;
BAParticipantManager manager = managerMap.get(id);
try {
manager.exit();
} catch (Exception e) {
throw new WebServiceException("exit " + id + " failed with exception " + e);
}
resultsList.add("ok");
} else {
throw new WebServiceException("exit invalid participant type " + id);
}
} else {
throw new WebServiceException("exit unknown participant " + id);
}
} else if (command.equals("completed")) {
bindCommands(commandList, bindings);
String id = commandList.remove(idx);
size--;
ScriptedTestParticipant participant = participantMap.get(id);
if (participant != null) {
if (participant instanceof ParticipantCompletionTestParticipant) {
ParticipantCompletionTestParticipant baparticipant = (ParticipantCompletionTestParticipant) participant;
BAParticipantManager manager = managerMap.get(id);
try {
manager.completed();
resultsList.add("ok");
} catch (Exception e) {
throw new WebServiceException("completed " + id + " failed with exception " + e);
}
} else {
throw new WebServiceException("completed invalid participant type " + id);
}
} else {
throw new WebServiceException("completed unknown participant " + id);
}
} else if (command.equals("fail")) {
bindCommands(commandList, bindings);
String id = commandList.remove(idx);
size--;
ScriptedTestParticipant participant = participantMap.get(id);
if (participant != null) {
if (participant instanceof ParticipantCompletionTestParticipant) {
ParticipantCompletionTestParticipant baparticipant = (ParticipantCompletionTestParticipant) participant;
BAParticipantManager manager = managerMap.get(id);
QName qname = new QName("http://jbossts.jboss.org/xts/servicetests/", "fail");
try {
manager.fail(qname);
resultsList.add("ok");
} catch (Exception e) {
throw new WebServiceException("fail " + id + " failed with exception " + e);
}
} else {
throw new WebServiceException("fail invalid participant type " + id);
}
} else {
throw new WebServiceException("fail unknown participant " + id);
}
} else if (command.equals("cannotComplete")) {
bindCommands(commandList, bindings);
String id = commandList.remove(idx);
size--;
ScriptedTestParticipant participant = participantMap.get(id);
if (participant != null) {
if (participant instanceof ParticipantCompletionTestParticipant) {
ParticipantCompletionTestParticipant baparticipant = (ParticipantCompletionTestParticipant) participant;
BAParticipantManager manager = managerMap.get(id);
try {
manager.cannotComplete();
resultsList.add("ok");
} catch (Exception e) {
throw new WebServiceException("cannotComplete " + id + " failed with exception " + e);
}
} else {
throw new WebServiceException("cannotComplete invalid participant type " + id);
}
} else {
throw new WebServiceException("cannotComplete unknown participant " + id);
}
} else if (command.equals("serve")) {
// dispatch commands to a server for execution
// we should find a web service URL and a list of commands to dispatch to that service
String url = commandList.remove(idx);
size--;
// we throw an error if the server url is unbound but we allow
// unbound variables in the command list passed on to the server
// since they may be bound by bind commands in the command list
// being served.
url = bindCommand(url, bindings, true);
bindCommands(commandList, bindings, false);
CommandsType newCommands = new CommandsType();
List<String> newCommandList = newCommands.getCommandList();
for (int i = 0; i < size; i++) {
newCommandList.add(commandList.get(i));
}
ResultsType subResults = serveSubordinate(url, newCommands);
List<String> subResultsList = subResults.getResultList();
size = subResultsList.size();
for (idx = 0; idx < size; idx++) {
resultsList.add(subResultsList.get(idx));
}
} else if (command.equals("subtransaction")) {
// create subordinate AT transaction
// this is surplus to requirements since we should really be running against a service which uses
// the subordinate interposition JaxWS handler to install a subordinate transaction before
// entering the service method. we ought to test that handler rather than hand crank the
// interposition in the service
TxContext currentTx;
TxContext newTx;
try {
currentTx = TransactionManager.getTransactionManager().currentTransaction();
} catch (SystemException e) {
throw new WebServiceException("subtransaction currentTransaction() failed with exception " + e);
}
try {
UserTransaction userTransaction = UserTransactionFactory.userSubordinateTransaction();
userTransaction.begin();
newTx = TransactionManager.getTransactionManager().currentTransaction();
} catch (Exception e) {
throw new WebServiceException("subtransaction begin() failed with exception " + e);
}
String id = transactionId("at");
subordinateTransactionMap.put(id, newTx);
resultsList.add(id);
} else if (command.equals("subactivity")) {
// create subordinate BA transaction
// this is surplus ot requirements since we should really be running against a service which uses
// the subordinate interposition JaxWS handler to install a subordinate activity before
// entering the service method. we ought to test that handler rather than hand crank the
// interposition in the service
TxContext currentTx;
TxContext newTx;
try {
currentTx = BusinessActivityManagerFactory.businessActivityManager().currentTransaction();
} catch (SystemException e) {
throw new WebServiceException("subtransaction currentTransaction() failed with exception " + e);
}
try {
UserBusinessActivity userBusinessActivity = UserBusinessActivityFactory.userBusinessActivity();
// this is nto implemented yet!!!
// userBusinessActivity.beginSubordinate();
// and this will fail with a WrongStateException
userBusinessActivity.begin();
newTx = BusinessActivityManager.getBusinessActivityManager().currentTransaction();
} catch (Exception e) {
throw new WebServiceException("subtransaction begin() failed with exception " + e);
}
String id = transactionId("ba");
subordinateActivityMap.put(id, newTx);
resultsList.add(id);
} else if (command.equals("subtransactionserve")) {
// dispatch commands in a subordinate transaction or activity
// we should find the id of a subordinate transaction, a web service URL
// and a list of commands to dispatch to that transaction
// the txid and url must be resolved if supplied as bindings
String txId = bindCommand(commandList.remove(idx), bindings, true);
size--;
String url = bindCommand(commandList.remove(idx), bindings, true);
size--;
TxContext newTx = subordinateTransactionMap.get(txId);
if (newTx != null) {
try {
TransactionManager.getTransactionManager().resume(newTx);
} catch (Exception e) {
throw new WebServiceException("subtransactioncommands resume() failed with exception " + e);
}
} else {
throw new WebServiceException("subtransactioncommands unknown subordinate transaction id " + txId);
}
// ok, now we install the relevant transaction and then just pass the commands on to
// the web service
// we allow unresolved variable references in the rest of the command list as
// they may be satisfied by embedded bind commands
bindCommands(commandList, bindings, false);
CommandsType newCommands = new CommandsType();
List<String> newCommandList = newCommands.getCommandList();
for (int i = 0; i < size; i++) {
newCommandList.add(commandList.get(i));
}
ResultsType subResults = serveSubordinate(url, newCommands);
List<String> subResultsList = subResults.getResultList();
size = subResultsList.size();
for (idx = 0; idx < size; idx++) {
resultsList.add(subResultsList.get(idx));
}
} else if (command.equals("subactivityserve")) {
// dispatch commands in a subordinate transaction or activity
// we should find the id of a subordinate transaction, a web service URL
// and a list of commands to dispatch to that transaction
// the txid and url must be resolved if supplied as bindings
String txId = bindCommand(commandList.remove(idx), bindings, true);
size--;
String url = bindCommand(commandList.remove(idx), bindings, true);
size--;
TxContext newTx = subordinateActivityMap.get(txId);
if (newTx != null) {
try {
TransactionManager.getTransactionManager().resume(newTx);
} catch (Exception e) {
throw new WebServiceException("subactivitycommands resume() failed with exception " + e);
}
} else {
throw new WebServiceException("subactivitycommands unknown subordinate transaction id " + txId);
}
// ok, now we install the relevant transaction and then just pass the commands on to
// the web service
// we allow unresolved variable references in the rest of the command list as
// they may be satisfied by embedded bind commands
bindCommands(commandList, bindings, false);
CommandsType newCommands = new CommandsType();
List<String> newCommandList = newCommands.getCommandList();
for (int i = 0; i < size; i++) {
newCommandList.add(commandList.get(i));
}
ResultsType subResults = serveSubordinate(url, newCommands);
List<String> subResultsList = subResults.getResultList();
size = subResultsList.size();
for (idx = 0; idx < size; idx++) {
resultsList.add(subResultsList.get(idx));
}
}
}
}Example 6
| Project: opensearchserver-master File: WebCrawlerImpl.java View source code |
@Override
public CommonResult crawl(String use, String login, String key, String url, Boolean returnData) {
try {
Client client = getLoggedClient(use, login, key, Role.WEB_CRAWLER_START_STOP);
ClientFactory.INSTANCE.properties.checkApi();
WebCrawlThread webCrawlThread = client.getWebCrawlMaster().manualCrawl(LinkUtils.newEncodedURL(url), HostUrlList.ListType.MANUAL);
if (!webCrawlThread.waitForStart(120))
throw new WebServiceException("Time out reached (120 seconds)");
if (!webCrawlThread.waitForEnd(3600))
throw new WebServiceException("Time out reached (3600 seconds)");
UrlItem urlItem = webCrawlThread.getCurrentUrlItem();
CommonResult cr = null;
if (BooleanUtils.isTrue(returnData)) {
Crawl crawl = webCrawlThread.getCurrentCrawl();
if (crawl != null) {
List<IndexDocument> indexDocuments = crawl.getTargetIndexDocuments();
if (CollectionUtils.isNotEmpty(indexDocuments)) {
CommonListResult<ArrayList<FieldValueList>> clr = new CommonListResult<ArrayList<FieldValueList>>(indexDocuments.size());
for (IndexDocument indexDocument : indexDocuments) {
ArrayList<FieldValueList> list = FieldValueList.getNewList(indexDocument);
if (list != null)
clr.items.add(list);
}
cr = clr;
}
}
}
String message = urlItem != null ? "Result: " + urlItem.getFetchStatus() + " - " + urlItem.getParserStatus() + " - " + urlItem.getIndexStatus() : null;
if (cr == null)
cr = new CommonResult(true, message);
if (urlItem != null) {
cr.addDetail("URL", urlItem.getUrl());
cr.addDetail("HttpResponseCode", urlItem.getResponseCode());
cr.addDetail("RobotsTxtStatus", urlItem.getRobotsTxtStatus());
cr.addDetail("FetchStatus", urlItem.getFetchStatus());
cr.addDetail("ParserStatus", urlItem.getParserStatus());
cr.addDetail("IndexStatus", urlItem.getIndexStatus());
cr.addDetail("RedirectionURL", urlItem.getRedirectionUrl());
cr.addDetail("ContentBaseType", urlItem.getContentBaseType());
cr.addDetail("ContentTypeCharset", urlItem.getContentTypeCharset());
cr.addDetail("ContentLength", urlItem.getContentLength());
}
return cr;
} catch (MalformedURLException e) {
throw new CommonServiceException(e);
} catch (SearchLibException e) {
throw new CommonServiceException(e);
} catch (ParseException e) {
throw new CommonServiceException(e);
} catch (IOException e) {
throw new CommonServiceException(e);
} catch (SyntaxError e) {
throw new CommonServiceException(e);
} catch (URISyntaxException e) {
throw new CommonServiceException(e);
} catch (ClassNotFoundException e) {
throw new CommonServiceException(e);
} catch (InterruptedException e) {
throw new CommonServiceException(e);
} catch (InstantiationException e) {
throw new CommonServiceException(e);
} catch (IllegalAccessException e) {
throw new CommonServiceException(e);
}
}Example 7
| Project: zeroth-master File: GatewayServiceClient.java View source code |
/**
* Submit SOAP method.
* @param <T> application model type
* @param aSoapRequest SOAP request
* @return SOAP response
* @throws EnterpriseException MalformedURLException or
* WebServiceException
*/
@SuppressWarnings("unchecked")
public <T> T submit(final GatewayModel aSoapRequest) throws EnterpriseException {
URL url;
try {
url = new URL("http://localhost:8080/ReferenceService/CalcService?wsdl");
final QName serviceName = new QName("http://zeroth.com/soap/", "ReferenceService");
final Service service = Service.create(url, serviceName);
log.fine(service.getWSDLDocumentLocation().toString());
final GatewayService port = service.getPort(GatewayService.class);
final Map<String, Object> context = ((BindingProvider) port).getRequestContext();
log.fine(context.entrySet().toString());
final GatewayModel returnedValue = port.submit(aSoapRequest);
return (T) returnedValue.getBody();
} catch (final MalformedURLException e) {
log.warning(e.getLocalizedMessage());
throw new EnterpriseException(e.getLocalizedMessage());
} catch (final WebServiceException e) {
log.warning(e.getLocalizedMessage());
throw new EnterpriseException(e.getLocalizedMessage());
}
}Example 8
| Project: AnalyzerBeans-master File: SimpleServiceSession.java View source code |
@Override
public ServiceResult<R> invokeService(Callable<R> callable) {
_requestCount.incrementAndGet();
_activeRequestsCount.incrementAndGet();
try {
final R result = callable.call();
return new ServiceResult<R>(result);
} catch (Throwable e) {
if (e instanceof WebServiceException && e.getCause() != null) {
logger.info("Exception thrown was a WebServiceException. Handling cause exception instead.", e);
e = e.getCause();
}
return new ServiceResult<R>(e);
} finally {
_activeRequestsCount.decrementAndGet();
}
}Example 9
| Project: axis2-java-master File: AddNumbersHandlerTests.java View source code |
/**
* Validate that setting a property reverts the logic for how local exceptions are handled.
* Validate that a local exception (in this case a ConnectionException caused by an invalid
* host on the EPR) is returned as a WebServiceExcpetion (not a SOAPFaultException), and the
* JAX-WS application handler handleMessage() methods are driven.
*/
public void testAddNumbersClientHandlerWithLocalException_RevertBehaviorFlag() {
try {
TestLogger.logger.debug("----------------------------------");
TestLogger.logger.debug("test: " + getName());
AddNumbersHandlerService service = new AddNumbersHandlerService();
setAxisConfigParameter(service, org.apache.axis2.jaxws.Constants.DISABLE_SOAPFAULT_FOR_LOCAL_EXCEPTION, "true");
AddNumbersHandlerPortType proxy = service.getAddNumbersHandlerPort();
BindingProvider p = (BindingProvider) proxy;
// Force a local connection exception by using an invalid host/port
p.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, invalidAxisEndpoint);
List<Handler> handlers = p.getBinding().getHandlerChain();
if (handlers == null)
handlers = new ArrayList<Handler>();
handlers.add(new AddNumbersClientLogicalHandler4());
handlers.add(new AddNumbersClientLogicalHandler2());
p.getBinding().setHandlerChain(handlers);
int total = proxy.addNumbersHandler(1, 2);
fail("Should have got an exception, but we didn't.");
} catch (Exception e) {
assertTrue("Exception should be WebServiceException.", e instanceof WebServiceException);
assertFalse("Exception should not be SOAPFaultException.", e instanceof SOAPFaultException);
assertTrue("Cause should be instanceof UnknownHostException", (e.getCause() instanceof java.net.UnknownHostException));
String log = readLogFile();
String expected_calls = "AddNumbersClientLogicalHandler4 HANDLE_MESSAGE_OUTBOUND\n" + "AddNumbersClientLogicalHandler2 HANDLE_MESSAGE_OUTBOUND\n" + "AddNumbersClientLogicalHandler2 HANDLE_MESSAGE_INBOUND\n" + "AddNumbersClientLogicalHandler4 HANDLE_MESSAGE_INBOUND\n" + "AddNumbersClientLogicalHandler2 CLOSE\n" + "AddNumbersClientLogicalHandler4 CLOSE\n";
assertEquals(expected_calls, log);
}
TestLogger.logger.debug("----------------------------------");
}Example 10
| Project: jaxws-undertow-httpspi-master File: EndpointBean.java View source code |
public DHResponse echoDataHandler(DHRequest request) {
this.ensureInit();
DataHandler dataHandler = request.getDataHandler();
try {
if (!dataHandler.getContentType().equals("text/plain")) {
throw new WebServiceException("Wrong content type");
}
if (!dataHandler.getContent().equals("some string")) {
throw new WebServiceException("Wrong data");
}
} catch (IOException e) {
throw new WebServiceException(e);
}
DataHandler responseData = new DataHandler("Server data", "text/plain");
return new DHResponse(responseData);
}Example 11
| Project: JBossAS51-master File: InvocationHandlerEJB21.java View source code |
public void init(Endpoint ep) {
String ejbName = ep.getShortName();
Deployment dep = ep.getService().getDeployment();
EJBArchiveMetaData apMetaData = dep.getAttachment(EJBArchiveMetaData.class);
EJBMetaData beanMetaData = (EJBMetaData) apMetaData.getBeanByEjbName(ejbName);
if (beanMetaData == null)
throw new WebServiceException("Cannot obtain ejb meta data for: " + ejbName);
// get the MBeanServer
server = MBeanServerLocator.locateJBoss();
// get the bean's JNDI name
jndiName = beanMetaData.getContainerObjectNameJndiName();
if (jndiName == null)
throw new WebServiceException("Cannot obtain JNDI name for: " + ejbName);
}Example 12
| Project: JBossAS_5_1_EDG-master File: InvocationHandlerEJB21.java View source code |
public void init(Endpoint ep) {
String ejbName = ep.getShortName();
Deployment dep = ep.getService().getDeployment();
EJBArchiveMetaData apMetaData = dep.getAttachment(EJBArchiveMetaData.class);
EJBMetaData beanMetaData = (EJBMetaData) apMetaData.getBeanByEjbName(ejbName);
if (beanMetaData == null)
throw new WebServiceException("Cannot obtain ejb meta data for: " + ejbName);
// get the MBeanServer
server = MBeanServerLocator.locateJBoss();
// get the bean's JNDI name
jndiName = beanMetaData.getContainerObjectNameJndiName();
if (jndiName == null)
throw new WebServiceException("Cannot obtain JNDI name for: " + ejbName);
}Example 13
| Project: musings-of-a-programming-addict-master File: ConfigurableValidationTubeFactory.java View source code |
/**
* Creates a {@link ConfigurableServerSchemaValidationTube}. Implementation
* based on Metro's ServerTubeAssemblerContext.
*/
public Tube createTube(ServerTubelineAssemblyContext context) throws WebServiceException {
ServerTubeAssemblerContext wrappedContext = context.getWrappedContext();
WSEndpoint<?> endpoint = wrappedContext.getEndpoint();
WSBinding binding = endpoint.getBinding();
Tube next = context.getTubelineHead();
WSDLPort wsdlModel = wrappedContext.getWsdlModel();
SEIModel seiModel = wrappedContext.getSEIModel();
if (binding instanceof SOAPBinding && binding.isFeatureEnabled(SchemaValidationFeature.class) && wsdlModel != null) {
return new ConfigurableServerSchemaValidationTube(endpoint, binding, seiModel, wsdlModel, next);
} else
return next;
}Example 14
| Project: openjdk-master File: Packet.java View source code |
/**
* Gives a list of Reference Parameters in the Message
* <p>
* Headers which have attribute wsa:IsReferenceParameter="true"
* This is not cached as one may reset the Message.
*<p>
*/
@Property(MessageContext.REFERENCE_PARAMETERS)
@NotNull
public List<Element> getReferenceParameters() {
Message msg = getMessage();
List<Element> refParams = new ArrayList<Element>();
if (msg == null) {
return refParams;
}
MessageHeaders hl = msg.getHeaders();
for (Header h : hl.asList()) {
String attr = h.getAttribute(AddressingVersion.W3C.nsUri, "IsReferenceParameter");
if (attr != null && (attr.equals("true") || attr.equals("1"))) {
Document d = DOMUtil.createDom();
SAX2DOMEx s2d = new SAX2DOMEx(d);
try {
h.writeTo(s2d, XmlUtil.DRACONIAN_ERROR_HANDLER);
refParams.add((Element) d.getLastChild());
} catch (SAXException e) {
throw new WebServiceException(e);
}
/*
DOMResult result = new DOMResult(d);
XMLDOMWriterImpl domwriter = new XMLDOMWriterImpl(result);
try {
h.writeTo(domwriter);
refParams.add((Element) result.getNode().getLastChild());
} catch (XMLStreamException e) {
throw new WebServiceException(e);
}
*/
}
}
return refParams;
}Example 15
| Project: solarnetwork-node-master File: HeartbeatJob.java View source code |
@Override
protected void executeInternal(JobExecutionContext jobContext) throws Exception {
if (service == null) {
log.warn("No CentralSystemServiceFactory available, cannot post heartbeat message.");
return;
}
try {
if (!service.isBootNotificationPosted()) {
service.postBootNotification();
return;
}
CentralSystemService client = service.service();
if (client == null) {
log.warn("No CentralSystemService avaialble, cannot post heartbeat message.");
return;
}
HeartbeatRequest req = new HeartbeatRequest();
HeartbeatResponse res = client.heartbeat(req, service.chargeBoxIdentity());
log.info("OCPP heartbeat response: {}", res == null ? null : res.getCurrentTime());
} catch (WebServiceException e) {
log.warn("Error communicating with OCPP central system: {}", e.getMessage());
}
}Example 16
| Project: tmdm-studio-se-master File: Util.java View source code |
public static TMDMService getMDMService(URL url, final String username, final String password, boolean showMissingJarDialog) throws XtentisException {
url = checkAndAddSuffix(url);
boolean needCheck = true;
TMDMService service = (TMDMService) cachedMDMService.get(url, username, password);
if (service == null) {
needCheck = false;
boolean checkResult = MissingJarService.getInstance().checkMissingJar(showMissingJarDialog);
if (!checkResult) {
//$NON-NLS-1$
throw new MissingJarsException("Missing dependency libraries.");
}
try {
TMDMService_Service service_service = new TMDMService_Service(url);
service = service_service.getTMDMPort();
BindingProvider stub = (BindingProvider) service;
// Do not maintain session via cookies
stub.getRequestContext().put(BindingProvider.SESSION_MAINTAIN_PROPERTY, false);
Map<String, Object> context = stub.getRequestContext();
// // dynamic set endpointAddress
// context.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpointAddress);
// authentication
context.put(BindingProvider.USERNAME_PROPERTY, username);
context.put(BindingProvider.PASSWORD_PROPERTY, password);
IWebServiceHook wsHook = getWebServiceHook();
if (wsHook != null) {
wsHook.preRequestSendingHook(stub, username);
}
cachedMDMService.put(url, username, password, service);
} catch (WebServiceException e) {
XtentisException ex = convertWebServiceException(e);
log.error(Messages.bind(Messages.UnableAccessEndpoint, url, e.getMessage()), e);
if (ex != null) {
throw ex;
}
}
}
if (needCheck) {
try {
service.ping(new WSPing());
} catch (WebServiceException e) {
cachedMDMService.remove(url, username, password);
XtentisException ex = convertWebServiceException(e);
log.error(Messages.bind(Messages.UnableAccessEndpoint, url, e.getMessage()), e);
if (ex != null) {
throw ex;
}
}
}
return service;
}Example 17
| Project: categolj2-backend-master File: BookServiceImpl.java View source code |
@Override
public List<BookDto> searchByTitle(String title) {
List<BookDto> books = new ArrayList<>();
try {
ItemSearchRequest requestForBooks = new ItemSearchRequest();
requestForBooks.setTitle(title);
requestForBooks.setSearchIndex("Books");
Response<ItemSearchResponse> responseForBooks = searchBook(requestForBooks);
ItemSearchRequest requestForForeignBooks = new ItemSearchRequest();
requestForForeignBooks.setTitle(title);
requestForForeignBooks.setSearchIndex("ForeignBooks");
Response<ItemSearchResponse> responseForForeignBooks = searchBook(requestForForeignBooks);
books.addAll(reseponseToBooks(responseForBooks.get()));
books.addAll(reseponseToBooks(responseForForeignBooks.get()));
} catch (ExecutionExceptionInterruptedException | WebServiceException | e) {
throw new SystemException(MessageKeys.E_CT_BO_9501, e);
}
return books;
}Example 18
| Project: circuitbreaker-master File: CircuitBreakerTest.java View source code |
@Test
public void shouldNotRecordIOExceptionAsAFailure() {
// tag::shouldNotRecordIOExceptionAsAFailure[]
// Given
CircuitBreakerConfig circuitBreakerConfig = CircuitBreakerConfig.custom().ringBufferSizeInClosedState(2).ringBufferSizeInHalfOpenState(2).waitDurationInOpenState(Duration.ofMillis(1000)).recordFailure( throwable -> Match(throwable).of(Case($(instanceOf(WebServiceException.class)), true), Case($(), false))).build();
CircuitBreaker circuitBreaker = CircuitBreaker.of("testName", circuitBreakerConfig);
// Simulate a failure attempt
circuitBreaker.onError(0, new WebServiceException());
// CircuitBreaker is still CLOSED, because 1 failure is allowed
assertThat(circuitBreaker.getState()).isEqualTo(CircuitBreaker.State.CLOSED);
//When
CheckedRunnable checkedRunnable = CircuitBreaker.decorateCheckedRunnable(circuitBreaker, () -> {
throw new SocketTimeoutException("BAM!");
});
Try result = Try.run(checkedRunnable);
//Then
assertThat(result.isFailure()).isTrue();
// CircuitBreaker is still CLOSED, because SocketTimeoutException has not been recorded as a failure
assertThat(circuitBreaker.getState()).isEqualTo(CircuitBreaker.State.CLOSED);
assertThat(result.failed().get()).isInstanceOf(IOException.class);
// end::shouldNotRecordIOExceptionAsAFailure[]
CircuitBreaker.Metrics metrics = circuitBreaker.getMetrics();
assertThat(metrics.getNumberOfBufferedCalls()).isEqualTo(1);
assertThat(metrics.getNumberOfFailedCalls()).isEqualTo(1);
}Example 19
| Project: classlib6-master File: WSDLGenerator.java View source code |
/**
* Generates the types section of the WSDL
*/
protected void generateTypes() {
types = portDefinitions.types();
if (model.getJAXBContext() != null) {
try {
model.getJAXBContext().generateSchema(resolver);
} catch (IOException e) {
e.printStackTrace();
throw new WebServiceException(e.getMessage());
}
}
}Example 20
| Project: DataCleaner-master File: SimpleServiceSession.java View source code |
@Override
public ServiceResult<R> invokeService(final Callable<R> callable) {
_requestCount.incrementAndGet();
_activeRequestsCount.incrementAndGet();
try {
final R result = callable.call();
return new ServiceResult<>(result);
} catch (Throwable e) {
if (e instanceof WebServiceException && e.getCause() != null) {
logger.info("Exception thrown was a WebServiceException. Handling cause exception instead.", e);
e = e.getCause();
}
return new ServiceResult<>(e);
} finally {
_activeRequestsCount.decrementAndGet();
}
}Example 21
| Project: HR-WebServices-Examples-Java-master File: DynamicServiceProvider.java View source code |
public Source invoke(Source source) {
//TestLogger.logger.debug(">> SourceProvider: Request received.\n");
if (source == null) {
return source;
}
if (context == null) {
//TestLogger.logger.debug("[DynamicServiceProvider] the WebServiceContext was null.");
throw new WebServiceException("A WebServiceException should have been injected.");
}
QName wsdlService = (QName) context.getMessageContext().get(MessageContext.WSDL_SERVICE);
QName wsdlOperation = (QName) context.getMessageContext().get(MessageContext.WSDL_OPERATION);
System.out.println("[DynamicServiceProvider] service name: " + wsdlService);
System.out.println("[DynamicServiceProvider] operation name: " + wsdlOperation);
//TestLogger.logger.debug("[DynamicServiceProvider] service name: " + wsdlService);
//TestLogger.logger.debug("[DynamicServiceProvider] operation name: " + wsdlOperation);
StringWriter writer = new StringWriter();
try {
Transformer t = TransformerFactory.newInstance().newTransformer();
Result result = new StreamResult(writer);
t.transform(source, result);
} catch (TransformerConfigurationException e) {
throw new WebServiceException(e);
} catch (TransformerFactoryConfigurationError e) {
throw new WebServiceException(e);
} catch (TransformerException e) {
throw new WebServiceException(e);
}
String text = writer.getBuffer().toString();
if (text != null && text.contains("throwWebServiceException")) {
throw new WebServiceException("provider");
}
ByteArrayInputStream stream = new ByteArrayInputStream(text.getBytes());
Source srcStream = new StreamSource((InputStream) stream);
return srcStream;
}Example 22
| Project: ikvm-openjdk-master File: WSDLGenerator.java View source code |
/**
* Generates the types section of the WSDL
*/
protected void generateTypes() {
types = portDefinitions.types();
if (model.getJAXBContext() != null) {
try {
model.getJAXBContext().generateSchema(resolver);
} catch (IOException e) {
e.printStackTrace();
throw new WebServiceException(e.getMessage());
}
}
}Example 23
| Project: jaxws-master File: Packet.java View source code |
/**
* Gives a list of Reference Parameters in the Message
* <p>
* Headers which have attribute wsa:IsReferenceParameter="true"
* This is not cached as one may reset the Message.
*<p>
*/
@Property(MessageContext.REFERENCE_PARAMETERS)
@NotNull
public List<Element> getReferenceParameters() {
Message msg = getMessage();
List<Element> refParams = new ArrayList<Element>();
if (msg == null) {
return refParams;
}
MessageHeaders hl = msg.getHeaders();
for (Header h : hl.asList()) {
String attr = h.getAttribute(AddressingVersion.W3C.nsUri, "IsReferenceParameter");
if (attr != null && (attr.equals("true") || attr.equals("1"))) {
Document d = DOMUtil.createDom();
SAX2DOMEx s2d = new SAX2DOMEx(d);
try {
h.writeTo(s2d, XmlUtil.DRACONIAN_ERROR_HANDLER);
refParams.add((Element) d.getLastChild());
} catch (SAXException e) {
throw new WebServiceException(e);
}
/*
DOMResult result = new DOMResult(d);
XMLDOMWriterImpl domwriter = new XMLDOMWriterImpl(result);
try {
h.writeTo(domwriter);
refParams.add((Element) result.getNode().getLastChild());
} catch (XMLStreamException e) {
throw new WebServiceException(e);
}
*/
}
}
return refParams;
}Example 24
| Project: ManagedRuntimeInitiative-master File: WSDLGenerator.java View source code |
/**
* Generates the types section of the WSDL
*/
protected void generateTypes() {
types = portDefinitions.types();
if (model.getJAXBContext() != null) {
try {
model.getJAXBContext().generateSchema(resolver);
} catch (IOException e) {
e.printStackTrace();
throw new WebServiceException(e.getMessage());
}
}
}Example 25
| Project: marketcetera-master File: MarketDataServiceClientImpl.java View source code |
/* (non-Javadoc)
* @see org.springframework.context.Lifecycle#start()
*/
@Override
public synchronized void start() {
Validate.notNull(hostname);
Validate.notNull(username);
Validate.notNull(password);
Validate.isTrue(port > 0);
serviceClient = new Client(hostname, port, APP_ID, contextClassProvider);
try {
serviceClient.login(username, password.toCharArray());
} catch (WebServiceException e) {
if (e.getCause() != null && e.getCause() instanceof ConnectException) {
throw new ConnectionException(hostname, port);
}
} catch (RemoteException e) {
throw new CredentialsException(username);
} catch (Exception e) {
SLF4JLoggerProxy.warn(this, e);
throw new RuntimeException(e);
}
marketDataService = serviceClient.getService(MarketDataService.class);
// do one test heartbeat to catch a bad (lazy-loaded) connection exception here
try {
marketDataService.heartbeat(serviceClient.getContext());
} catch (RemoteExceptionWebServiceException | e) {
if (e.getCause() != null) {
if (e.getCause() instanceof java.net.UnknownHostException) {
throw new UnknownHostException(hostname, port);
}
}
throw new RuntimeException(e);
}
heartbeatToken = heartbeatExecutor.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
try {
marketDataService.heartbeat(serviceClient.getContext());
} catch (Exception e) {
heartbeatError(e);
}
}
}, heartbeatInterval, heartbeatInterval, TimeUnit.MILLISECONDS);
running.set(true);
}Example 26
| Project: MyPublicRepo-master File: Service.java View source code |
private void invoke(String opName, boolean inboundRawMode, boolean outboundRawMode, Object[] inParams, List<Object> outParams, ByteBufferWrapper inWrapper, ByteBufferWrapper outWrapper) throws ServiceInvocationException {
RawDataServiceDispatch dispatch = null;
try {
try {
dispatch = new RawDataServiceDispatch(opName, m_serviceLocations, m_serviceDesc, m_wsdlLocation, m_invokerOptions, m_serviceVersion, m_cookies, m_sessionTransportHeaders, m_sessionMessageHeaders, m_g11nOptions, getRequestContext(), null, null);
RawDispatchData rawData = new RawDispatchData(inboundRawMode, outboundRawMode, inParams, outParams, inWrapper, outWrapper);
// Cache functionality doesn't support call for cache policy
// (getCachePolicy)
// and "raw" calls
boolean cacheSupported = !(SOAConstants.OP_GET_CACHE_POLICY.equals(opName) || inboundRawMode);
if (cacheSupported && m_serviceDesc.isCacheDisabledOnLocal() != null && m_serviceDesc.isCacheDisabledOnLocal().booleanValue()) {
if (getInvokerOptions() != null && SOAConstants.TRANSPORT_LOCAL.equalsIgnoreCase(getInvokerOptions().getTransportName())) {
cacheSupported = false;
} else if (SOAConstants.TRANSPORT_LOCAL.equalsIgnoreCase(m_serviceDesc.getDefTransportName())) {
cacheSupported = false;
}
}
CacheProvider cacheProvider = null;
if (cacheSupported) {
cacheProvider = m_serviceDesc.getCacheProviderClass();
// if cacheProvider somehow is not available, then we can't
// use any caches
cacheSupported = cacheProvider != null;
if (cacheSupported) {
try {
cacheProvider.init(m_serviceDesc, (m_serviceLocations == null || m_serviceLocations.isEmpty()) ? null : m_serviceLocations.get(0));
} catch (ServiceException e) {
if (m_serviceDesc.isSkipCacheOnError() != null && !m_serviceDesc.isSkipCacheOnError().booleanValue()) {
throw e;
}
}
}
}
if (cacheSupported && cacheProvider.isCacheEnabled()) {
// cacheContext
CacheContext cacheContext = new CacheContext().setOpName(opName).setRequest(inParams[0]);
Object result = cacheProvider.lookup(cacheContext);
if (result != null) {
outParams.add(result);
} else {
dispatch.invoke(rawData);
cacheContext.setResponse(outParams.get(0));
cacheProvider.insert(cacheContext);
}
} else {
// "Old" behavior, which is a direct call to server
dispatch.invoke(rawData);
return;
}
} catch (WebServiceException e) {
throw e.getCause();
}
} catch (RuntimeException e) {
throw e;
} catch (Error e) {
throw e;
} catch (ServiceInvocationException e) {
throw e;
} catch (Throwable e) {
throw new WebServiceException(e);
} finally {
if (dispatch != null) {
m_urlPathInfo = dispatch.getUrlPathInfo();
m_requestContext = dispatch.getDispatchRequestContext();
m_responseContext = dispatch.getDispatchResponseContext();
m_numTries = dispatch.getLastTryCount();
}
}
}Example 27
| Project: Secure-Service-Specification-and-Deployment-master File: CompositionPlansCreationAdapter.java View source code |
protected IStatus run(IProgressMonitor monitor) {
monitor.beginTask("Discovering services in the Marketplace for all the service tasks", 100);
ServiceCompositionFrameworkInterface scf = org.activiti.designer.elsag.Activator.getDefault().getServiceCompositionFramework();
URI uri = diagram.eResource().getURI();
URI bpmnUri = uri.trimFragment();
bpmnUri = bpmnUri.trimFileExtension();
bpmnUri = bpmnUri.appendFileExtension("bpmn20.xml");
String platformString = bpmnUri.toPlatformString(true);
IResource fileResource = ResourcesPlugin.getWorkspace().getRoot().findMember(platformString);
if (fileResource != null) {
boolean discovered = true;
ServiceTask task = null;
List<String> serviceTasksDiscovered = new Vector<String>();
EList<PictogramLink> list = diagram.getPictogramLinks();
List<List<String>> servicesNotDiscovered = new Vector<List<String>>();
for (PictogramLink link : list) {
EList<EObject> elist = link.getBusinessObjects();
for (EObject ob : elist) {
if (ob instanceof ServiceTask) {
task = (ServiceTask) ob;
if (!serviceTasksDiscovered.contains(task.getId())) {
String taskId = task.getId();
Hashtable<String, Set<Service>> hashTableLocations = org.activiti.designer.elsag.data.Data.hashTableLocationsProcess.get(processId);
if (hashTableLocations == null) {
hashTableLocations = new Hashtable<String, Set<Service>>();
}
Set<Service> setOld = hashTableLocations.get(taskId);
if (setOld != null) {
hashTableLocations.put(taskId, setOld);
org.activiti.designer.elsag.data.Data.hashTableLocationsProcess.put(processId, hashTableLocations);
} else {
hashTableLocations.put(taskId, new HashSet<Service>());
org.activiti.designer.elsag.data.Data.hashTableLocationsProcess.put(processId, hashTableLocations);
}
Hashtable<String, Hashtable<String, List<List<String>>>> hashTableTaskOperationInputType = org.activiti.designer.elsag.data.Data.hashTableTaskOperationInputTypeProcess.get(processId);
if (hashTableTaskOperationInputType == null) {
hashTableTaskOperationInputType = new Hashtable<String, Hashtable<String, List<List<String>>>>();
}
Hashtable<String, List<List<String>>> hashTableInputTypeOld = hashTableTaskOperationInputType.get(taskId);
if (hashTableInputTypeOld != null) {
hashTableTaskOperationInputType.put(taskId, hashTableInputTypeOld);
org.activiti.designer.elsag.data.Data.hashTableTaskOperationInputTypeProcess.put(processId, hashTableTaskOperationInputType);
} else {
hashTableTaskOperationInputType.put(taskId, new Hashtable<String, List<List<String>>>());
org.activiti.designer.elsag.data.Data.hashTableTaskOperationInputTypeProcess.put(processId, hashTableTaskOperationInputType);
}
Hashtable<String, Hashtable<String, List<String>>> hashTableTaskOperationOutputType = org.activiti.designer.elsag.data.Data.hashTableTaskOperationOutputTypeProcess.get(processId);
if (hashTableTaskOperationOutputType == null) {
hashTableTaskOperationOutputType = new Hashtable<String, Hashtable<String, List<String>>>();
}
Hashtable<String, List<String>> hashTableOperationOutputTypeOld = hashTableTaskOperationOutputType.get(taskId);
if (hashTableOperationOutputTypeOld != null) {
hashTableTaskOperationOutputType.put(taskId, hashTableOperationOutputTypeOld);
org.activiti.designer.elsag.data.Data.hashTableTaskOperationOutputTypeProcess.put(processId, hashTableTaskOperationOutputType);
} else {
hashTableTaskOperationOutputType.put(taskId, new Hashtable<String, List<String>>());
org.activiti.designer.elsag.data.Data.hashTableTaskOperationOutputTypeProcess.put(processId, hashTableTaskOperationOutputType);
}
Hashtable<String, Hashtable<String, Set<Service>>> hashTableTaskOperations = org.activiti.designer.elsag.data.Data.hashTableTaskOperationsProcess.get(processId);
if (hashTableTaskOperations == null) {
hashTableTaskOperations = new Hashtable<String, Hashtable<String, Set<Service>>>();
}
Hashtable<String, Set<Service>> hashTableOld = hashTableTaskOperations.get(taskId);
if (hashTableOld != null) {
hashTableTaskOperations.put(taskId, hashTableOld);
org.activiti.designer.elsag.data.Data.hashTableTaskOperationsProcess.put(processId, hashTableTaskOperations);
} else {
hashTableTaskOperations.put(taskId, new Hashtable<String, Set<Service>>());
org.activiti.designer.elsag.data.Data.hashTableTaskOperationsProcess.put(processId, hashTableTaskOperations);
}
monitor.subTask("Connecting to the Marketplace");
monitor.worked(20);
Hashtable<String, Set<Service>> hashOperations = new Hashtable<String, Set<Service>>();
List<FieldExtension> fieldExtensions = task.getFieldExtensions();
for (FieldExtension field : fieldExtensions) {
if (field.getFieldname().equals("type")) {
String type = field.getExpression();
String secReq = "";
if (!type.equals("")) {
ServiceQuery serviceQuery = new ServiceQuery(type, secReq);
Set<Service> servicesDiscovered = null;
try {
log.debug("Connecting to the SCF bundle");
Properties prop = Activator.getConfigProperties();
scf.setProxy(prop.getProperty("proxyHost"), prop.getProperty("proxyPort"), prop.getProperty("proxyUsername"), prop.getProperty("proxyPassword"));
servicesDiscovered = scf.discoverServices(serviceQuery, prop.getProperty("MarketplaceAddress"));
log.debug("Services discovered");
} catch (javax.xml.ws.WebServiceException ex) {
log.error("Unable to connect to the Marketplace");
showErrorMessage("Unable to connect to the Marketplace");
System.out.println("Unable to connect to the Marketplace");
System.out.println(ex);
return Status.CANCEL_STATUS;
}
Set<String> locations = new HashSet<String>();
if (servicesDiscovered.size() == 0) {
List<String> typeAndId = new Vector<String>();
typeAndId.add(0, type);
typeAndId.add(1, taskId);
typeAndId.add(2, task.getName());
boolean contains = false;
for (List<String> service : servicesNotDiscovered) {
if (service.get(1).equals(taskId))
contains = true;
}
if (!contains)
servicesNotDiscovered.add(typeAndId);
break;
}
for (Service service : servicesDiscovered) {
locations.add(service.getLocation());
}
hashTableLocations = org.activiti.designer.elsag.data.Data.hashTableLocationsProcess.get(processId);
hashTableLocations.put(task.getId(), servicesDiscovered);
org.activiti.designer.elsag.data.Data.hashTableLocationsProcess.put(processId, (Hashtable<String, Set<Service>>) hashTableLocations);
serviceTasksDiscovered.add(task.getId());
if (locations.size() > 0) {
log.debug("Discovered " + locations.size() + " services for " + type);
log.debug("Locations:");
Hashtable<String, List<List<String>>> hashTableOperationInputType = new Hashtable<String, List<List<String>>>();
Hashtable<String, List<String>> hashTableOperationOutputType = new Hashtable<String, List<String>>();
String[] labels = null;
List<String> operations = new Vector<String>();
String errorMsg = "";
Iterator<Service> it = servicesDiscovered.iterator();
while (it.hasNext()) {
Service service = it.next();
String location = service.getLocation();
log.debug("--- " + location);
List<String> listOperations = new Vector<String>();
try {
listOperations = WsdlParser.getInstance().getOperations(location);
} catch (WSDLException e) {
if (errorMsg.startsWith("Unable to")) {
errorMsg = errorMsg + location + "\n";
} else {
errorMsg = "Unable to reach WSDL at location: \n" + location + "\n";
}
it.remove();
}
List<String> inputTypes = null;
String outputType = null;
for (int i = 0; i < listOperations.size(); i++) {
inputTypes = WsdlParser.getInstance().getInputTypes(location, listOperations.get(i));
outputType = WsdlParser.getInstance().getOutputTypes(location, listOperations.get(i));
List<List<String>> actualInputTypes = hashTableOperationInputType.get(listOperations.get(i));
List<String> actualOutputTypes = hashTableOperationOutputType.get(listOperations.get(i));
if (actualInputTypes == null) {
actualInputTypes = new Vector<List<String>>();
}
if (actualOutputTypes == null) {
actualOutputTypes = new Vector<String>();
}
if (outputType.equals("")) {
outputType = "void";
}
if (!actualInputTypes.contains(inputTypes) && !actualOutputTypes.contains(outputType)) {
actualInputTypes.add(inputTypes);
// hashTableOperationInputType = org.activiti.designer.elsag.data.Data.hashTableTaskOperationInputType.get(task.getId());
hashTableOperationInputType.put(listOperations.get(i), actualInputTypes);
hashTableTaskOperationInputType = org.activiti.designer.elsag.data.Data.hashTableTaskOperationInputTypeProcess.get(processId);
hashTableTaskOperationInputType.put(taskId, hashTableOperationInputType);
org.activiti.designer.elsag.data.Data.hashTableTaskOperationInputTypeProcess.put(processId, hashTableTaskOperationInputType);
actualOutputTypes.add(outputType);
// hashTableOperationOutputType = org.activiti.designer.elsag.data.Data.hashTableTaskOperationOutputType.get(task.getId());
hashTableOperationOutputType.put(listOperations.get(i), actualOutputTypes);
hashTableTaskOperationOutputType = org.activiti.designer.elsag.data.Data.hashTableTaskOperationOutputTypeProcess.get(processId);
hashTableTaskOperationOutputType.put(taskId, hashTableOperationOutputType);
org.activiti.designer.elsag.data.Data.hashTableTaskOperationOutputTypeProcess.put(processId, hashTableTaskOperationOutputType);
String offset = "";
for (String inputType : inputTypes) {
offset = offset + inputType;
}
offset = offset + "O" + outputType;
if (hashOperations.containsKey(listOperations.get(i) + offset)) {
Set<Service> services = hashOperations.get(listOperations.get(i) + offset);
Set<String> locs = new HashSet<String>();
for (Service s : services) {
String l = s.getLocation();
locs.add(l);
}
if (!locs.contains(location)) {
services.add(service);
hashOperations.put(listOperations.get(i) + offset, services);
hashTableTaskOperations = org.activiti.designer.elsag.data.Data.hashTableTaskOperationsProcess.get(processId);
hashTableTaskOperations.put(taskId, hashOperations);
org.activiti.designer.elsag.data.Data.hashTableTaskOperationsProcess.put(processId, hashTableTaskOperations);
}
} else {
Set<Service> services = new HashSet<Service>();
services.add(service);
hashOperations.put(listOperations.get(i) + offset, services);
hashTableTaskOperations = org.activiti.designer.elsag.data.Data.hashTableTaskOperationsProcess.get(processId);
hashTableTaskOperations.put(taskId, hashOperations);
org.activiti.designer.elsag.data.Data.hashTableTaskOperationsProcess.put(processId, hashTableTaskOperations);
}
operations.add(listOperations.get(i));
} else if (!actualInputTypes.contains(inputTypes) && actualOutputTypes.contains(outputType)) {
actualInputTypes.add(inputTypes);
// hashTableOperationInputType = org.activiti.designer.elsag.data.Data.hashTableTaskOperationInputType.get(task.getId());
hashTableOperationInputType.put(listOperations.get(i), actualInputTypes);
hashTableTaskOperationInputType = org.activiti.designer.elsag.data.Data.hashTableTaskOperationInputTypeProcess.get(processId);
hashTableTaskOperationInputType.put(taskId, hashTableOperationInputType);
org.activiti.designer.elsag.data.Data.hashTableTaskOperationInputTypeProcess.put(processId, hashTableTaskOperationInputType);
String offset = "";
for (String inputType : inputTypes) {
offset = offset + inputType;
}
offset = offset + "O" + outputType;
if (hashOperations.containsKey(listOperations.get(i) + offset)) {
Set<Service> services = hashOperations.get(listOperations.get(i) + offset);
Set<String> locs = new HashSet<String>();
for (Service s : services) {
String l = s.getLocation();
locs.add(l);
}
if (!locs.contains(location)) {
services.add(service);
hashOperations.put(listOperations.get(i) + offset, services);
hashTableTaskOperations = org.activiti.designer.elsag.data.Data.hashTableTaskOperationsProcess.get(processId);
hashTableTaskOperations.put(taskId, hashOperations);
org.activiti.designer.elsag.data.Data.hashTableTaskOperationsProcess.put(processId, hashTableTaskOperations);
}
} else {
Set<Service> services = new HashSet<Service>();
services.add(service);
hashOperations.put(listOperations.get(i) + offset, services);
hashTableTaskOperations = org.activiti.designer.elsag.data.Data.hashTableTaskOperationsProcess.get(processId);
hashTableTaskOperations.put(taskId, hashOperations);
org.activiti.designer.elsag.data.Data.hashTableTaskOperationsProcess.put(processId, hashTableTaskOperations);
}
operations.add(listOperations.get(i));
} else if (actualInputTypes.contains(inputTypes) && !actualOutputTypes.contains(outputType)) {
actualOutputTypes.add(outputType);
// hashTableOperationOutputType = org.activiti.designer.elsag.data.Data.hashTableTaskOperationOutputType.get(task.getId());
hashTableOperationOutputType.put(listOperations.get(i), actualOutputTypes);
hashTableTaskOperationOutputType = org.activiti.designer.elsag.data.Data.hashTableTaskOperationOutputTypeProcess.get(processId);
hashTableTaskOperationOutputType.put(taskId, hashTableOperationOutputType);
String offset = "";
for (String inputType : inputTypes) {
offset = offset + inputType;
}
offset = offset + "O" + outputType;
if (hashOperations.containsKey(listOperations.get(i) + offset)) {
Set<Service> services = hashOperations.get(listOperations.get(i) + offset);
Set<String> locs = new HashSet<String>();
for (Service s : services) {
String l = s.getLocation();
locs.add(l);
}
if (!locs.contains(location)) {
services.add(service);
hashOperations.put(listOperations.get(i) + offset, services);
hashTableTaskOperations = org.activiti.designer.elsag.data.Data.hashTableTaskOperationsProcess.get(processId);
hashTableTaskOperations.put(taskId, hashOperations);
org.activiti.designer.elsag.data.Data.hashTableTaskOperationsProcess.put(processId, hashTableTaskOperations);
}
} else {
Set<Service> services = new HashSet<Service>();
services.add(service);
hashOperations.put(listOperations.get(i) + offset, services);
hashTableTaskOperations = org.activiti.designer.elsag.data.Data.hashTableTaskOperationsProcess.get(processId);
hashTableTaskOperations.put(taskId, hashOperations);
org.activiti.designer.elsag.data.Data.hashTableTaskOperationsProcess.put(processId, hashTableTaskOperations);
}
operations.add(listOperations.get(i));
} else {
String offset = "";
for (String inputType : inputTypes) {
offset = offset + inputType;
}
offset = offset + "O" + outputType;
if (hashOperations.containsKey(listOperations.get(i) + offset)) {
Set<Service> services = hashOperations.get(listOperations.get(i) + offset);
Set<String> locs = new HashSet<String>();
for (Service s : services) {
String l = s.getLocation();
locs.add(l);
}
if (!locs.contains(location)) {
services.add(service);
hashOperations.put(listOperations.get(i) + offset, services);
hashTableTaskOperations = org.activiti.designer.elsag.data.Data.hashTableTaskOperationsProcess.get(processId);
hashTableTaskOperations.put(taskId, hashOperations);
org.activiti.designer.elsag.data.Data.hashTableTaskOperationsProcess.put(processId, hashTableTaskOperations);
}
} else {
Set<Service> services = new HashSet<Service>();
services.add(service);
hashOperations.put(listOperations.get(i) + offset, services);
hashTableTaskOperations = org.activiti.designer.elsag.data.Data.hashTableTaskOperationsProcess.get(processId);
hashTableTaskOperations.put(taskId, hashOperations);
org.activiti.designer.elsag.data.Data.hashTableTaskOperationsProcess.put(processId, hashTableTaskOperations);
}
operations.add(listOperations.get(i));
}
}
}
monitor.subTask("Parsing WSDL files");
monitor.worked(60);
hashTableTaskOperationInputType = org.activiti.designer.elsag.data.Data.hashTableTaskOperationInputTypeProcess.get(processId);
hashTableTaskOperationOutputType = org.activiti.designer.elsag.data.Data.hashTableTaskOperationOutputTypeProcess.get(processId);
Set<String> setOperations = hashTableTaskOperationInputType.get(taskId).keySet();
Object[] operationsArray = setOperations.toArray();
int size = 0;
size = hashOperations.size();
if (!errorMsg.equals("")) {
showErrorMessage(errorMsg);
}
if (size == 0) {
List<String> typeAndId = new Vector<String>();
typeAndId.add(0, type);
typeAndId.add(1, taskId);
typeAndId.add(2, task.getName());
servicesNotDiscovered.add(typeAndId);
}
labels = new String[size];
Hashtable<String, String> hashLabel = new Hashtable<String, String>();
for (int j = 0; j < operationsArray.length; j++) {
List<List<String>> inputT = hashTableTaskOperationInputType.get(taskId).get(operationsArray[j]);
List<String> outputT = hashTableTaskOperationOutputType.get(taskId).get(operationsArray[j]);
for (List<String> list1 : inputT) {
String inputTypeString = "";
Iterator<String> iterator = list1.iterator();
while (iterator.hasNext()) {
inputTypeString = inputTypeString + iterator.next();
if (iterator.hasNext()) {
inputTypeString = inputTypeString + ", ";
}
}
for (String outputString : outputT) {
if (outputString.equals("")) {
outputString = "void";
}
String stringValue = operationsArray[j] + " (input: " + inputTypeString + ")" + " (output: " + outputString + ")";
hashLabel.put(stringValue, stringValue);
}
}
}
Set<String> keys = hashLabel.keySet();
int cont = 0;
for (String key : keys) {
labels[cont] = hashLabel.get(key);
cont++;
}
Hashtable<String, Set<Service>> hashTableLocations1 = org.activiti.designer.elsag.data.Data.hashTableLocationsProcess.get(processId);
hashTableLocations1.put(taskId, servicesDiscovered);
org.activiti.designer.elsag.data.Data.hashTableLocationsProcess.put(processId, hashTableLocations1);
}
}
}
}
}
}
}
}
if (serviceTasksDiscovered.size() == getListOfServiceTasks().size() && servicesNotDiscovered.size() == 0) {
monitor.subTask("Services Discovered");
monitor.worked(20);
monitor.done();
log.debug("All the services have been successfully discovered");
return Status.OK_STATUS;
} else if (discovered) {
String message = "";
for (List<String> service : servicesNotDiscovered) {
String type = service.get(0);
String id = service.get(1);
String name = service.get(2);
message = message + "Id:" + id + " Name: " + name + " Type: " + type + " \n";
}
showErrorMessage("Unable to find services for the following Service Tasks:\n" + message + "\n\n" + "Check the types and click again on the \"Create composition plans\" button");
return Status.CANCEL_STATUS;
} else {
return Status.CANCEL_STATUS;
}
} else {
return Status.CANCEL_STATUS;
}
}Example 28
| Project: servicemix4-features-master File: NmrEndpoint.java View source code |
protected void init() {
// configure handlers
try {
initHandlers();
} catch (Exception e) {
throw new WebServiceException("Error configuring handlers", e);
}
// Set service to invoke the target ejb
service.setInvoker(new EjbMethodInvoker(this.bus, deploymentInfo));
// Remove interceptors that perform handler processing since
// handler processing must happen within the EJB container.
Endpoint endpoint = getEndpoint();
removeHandlerInterceptors(bus.getInInterceptors());
removeHandlerInterceptors(endpoint.getInInterceptors());
removeHandlerInterceptors(endpoint.getBinding().getInInterceptors());
removeHandlerInterceptors(endpoint.getService().getInInterceptors());
// Install SAAJ interceptor
if (endpoint.getBinding() instanceof SoapBinding && !this.implInfo.isWebServiceProvider()) {
endpoint.getService().getInInterceptors().add(new SAAJInInterceptor());
}
WSDLQueryHandler wsdl = new WSDLQueryHandler(bus);
wsdl.writeResponse("http://localhost/service?wsdl", null, endpoint.getEndpointInfo(), System.err);
}Example 29
| Project: turmeric-runtime-master File: Service.java View source code |
private void invoke(String opName, boolean inboundRawMode, boolean outboundRawMode, Object[] inParams, List<Object> outParams, ByteBufferWrapper inWrapper, ByteBufferWrapper outWrapper) throws ServiceInvocationException {
RawDataServiceDispatch dispatch = null;
try {
try {
dispatch = new RawDataServiceDispatch(opName, m_serviceLocations, m_serviceDesc, m_wsdlLocation, m_invokerOptions, m_serviceVersion, m_cookies, m_sessionTransportHeaders, m_sessionMessageHeaders, m_g11nOptions, getRequestContext(), null, null);
RawDispatchData rawData = new RawDispatchData(inboundRawMode, outboundRawMode, inParams, outParams, inWrapper, outWrapper);
// Cache functionality doesn't support call for cache policy
// (getCachePolicy)
// and "raw" calls
boolean cacheSupported = !(SOAConstants.OP_GET_CACHE_POLICY.equals(opName) || inboundRawMode);
if (cacheSupported && m_serviceDesc.isCacheDisabledOnLocal() != null && m_serviceDesc.isCacheDisabledOnLocal().booleanValue()) {
if (getInvokerOptions() != null && SOAConstants.TRANSPORT_LOCAL.equalsIgnoreCase(getInvokerOptions().getTransportName())) {
cacheSupported = false;
} else if (SOAConstants.TRANSPORT_LOCAL.equalsIgnoreCase(m_serviceDesc.getDefTransportName())) {
cacheSupported = false;
}
}
CacheProvider cacheProvider = null;
if (cacheSupported) {
cacheProvider = m_serviceDesc.getCacheProviderClass();
// if cacheProvider somehow is not available, then we can't
// use any caches
cacheSupported = cacheProvider != null;
if (cacheSupported) {
try {
cacheProvider.init(m_serviceDesc, (m_serviceLocations == null || m_serviceLocations.isEmpty()) ? null : m_serviceLocations.get(0));
} catch (ServiceException e) {
if (m_serviceDesc.isSkipCacheOnError() != null && !m_serviceDesc.isSkipCacheOnError().booleanValue()) {
throw e;
}
}
}
}
if (cacheSupported && cacheProvider.isCacheEnabled()) {
// cacheContext
CacheContext cacheContext = new CacheContext().setOpName(opName).setRequest(inParams[0]);
Object result = cacheProvider.lookup(cacheContext);
if (result != null) {
outParams.add(result);
} else {
dispatch.invoke(rawData);
cacheContext.setResponse(outParams.get(0));
cacheProvider.insert(cacheContext);
}
} else {
// "Old" behavior, which is a direct call to server
dispatch.invoke(rawData);
return;
}
} catch (WebServiceException e) {
throw e.getCause();
}
} catch (RuntimeException e) {
throw e;
} catch (Error e) {
throw e;
} catch (ServiceInvocationException e) {
throw e;
} catch (Throwable e) {
throw new WebServiceException(e);
} finally {
if (dispatch != null) {
m_urlPathInfo = dispatch.getUrlPathInfo();
m_requestContext = dispatch.getDispatchRequestContext();
m_responseContext = dispatch.getDispatchResponseContext();
m_numTries = dispatch.getLastTryCount();
}
}
}Example 30
| Project: wildfly-master File: EJBEndpointAuthenticationTestCase.java View source code |
// ------------------------------------------------------------------------------
//
// Tests for hello method
//
@Test
public void accessHelloWithoutUsernameAndPassord() throws Exception {
URL wsdlURL = new URL(baseUrl, "/jaxws-authentication-ejb3/EJB3AuthService?wsdl");
Service service = Service.create(wsdlURL, serviceName);
EJBEndpointIface proxy = service.getPort(EJBEndpointIface.class);
try {
proxy.hello("World");
Assert.fail("Test should fail, HTTP response '401: Unauthorized' was expected");
} catch (WebServiceException e) {
Assert.assertTrue("HTTPException '401: Unauthorized' was expected", e.getCause().getMessage().contains("401: Unauthorized"));
}
}Example 31
| Project: bdd_videoannotator-master File: AnnotationService.java View source code |
/**
* Writes the buffered Annotations to the annotation output file and stops
* video recording.
*/
private void writeAnnotationFile() {
if (!currentScenario.hasStepAnnotations()) {
return;
}
currentScenario.setNameVideoFile(videoOutputFile.getName());
try {
currentScenario.setSha1ChecksumVideo(Helper.calcSha1Checksum(videoOutputFile));
annotationExporter.write(currentScenario);
} catch (Exception e) {
throw new WebServiceException("Could not write Annotation-Outputfile: " + e.getMessage());
} finally {
currentScenario = null;
}
}Example 32
| Project: appverse-web-master File: AbstractWSClient.java View source code |
/**
* Returns the remote service interface.
* @return service interface
*/
public I getService() throws Exception {
try {
if (remoteService == null) {
WebServiceClient ann = serviceType.getAnnotation(WebServiceClient.class);
URL remoteWsdl = new URL(getRemoteWSDLURL());
service = serviceType.getConstructor(URL.class, QName.class).newInstance(remoteWsdl, new QName(ann.targetNamespace(), ann.name()));
remoteService = service.getPort(interfaceType);
if (handlers.size() > 0) {
BindingProvider bindProv = (BindingProvider) remoteService;
bindProv.getBinding().setHandlerChain(handlers);
}
}
} catch (WebServiceException ex) {
throw new Exception("Service connection fails.");
} catch (NullPointerException e) {
throw new Exception("Review JaxWSClient configuration.");
}
return remoteService;
}Example 33
| Project: glassfish-main-master File: PipeHelper.java View source code |
// always returns response with embedded fault
//public static Packet makeFaultResponse(Packet response, Throwable t) {
public Packet makeFaultResponse(Packet response, Throwable t) {
// wrap throwable in WebServiceException, if necessary
if (!(t instanceof WebServiceException)) {
t = (Throwable) new WebServiceException(t);
}
if (response == null) {
response = new Packet();
}
// is thrown, create new packet, and create fault in it.
try {
return response.createResponse(Messages.create(t, this.soapVersion));
} catch (Exception e) {
response = new Packet();
}
return response.createResponse(Messages.create(t, this.soapVersion));
}Example 34
| Project: glassfish-master File: WebServiceReferenceManagerImpl.java View source code |
private WebServiceFeature getWebServiceFeatureBean(Annotation a) {
WebServiceFeatureAnnotation wsfa = a.annotationType().getAnnotation(WebServiceFeatureAnnotation.class);
Class<? extends WebServiceFeature> beanClass = wsfa.bean();
WebServiceFeature bean;
Constructor ftrCtr = null;
String[] paramNames = null;
for (Constructor con : beanClass.getConstructors()) {
FeatureConstructor ftrCtrAnn = (FeatureConstructor) con.getAnnotation(FeatureConstructor.class);
if (ftrCtrAnn != null) {
if (ftrCtr == null) {
ftrCtr = con;
paramNames = ftrCtrAnn.value();
} else {
throw new WebServiceException(ModelerMessages.RUNTIME_MODELER_WSFEATURE_MORETHANONE_FTRCONSTRUCTOR(a, beanClass));
}
}
}
if (ftrCtr == null) {
throw new WebServiceException(ModelerMessages.RUNTIME_MODELER_WSFEATURE_NO_FTRCONSTRUCTOR(a, beanClass));
}
if (ftrCtr.getParameterTypes().length != paramNames.length) {
throw new WebServiceException(ModelerMessages.RUNTIME_MODELER_WSFEATURE_ILLEGAL_FTRCONSTRUCTOR(a, beanClass));
}
try {
Object[] params = new Object[paramNames.length];
for (int i = 0; i < paramNames.length; i++) {
Method m = a.annotationType().getDeclaredMethod(paramNames[i]);
params[i] = m.invoke(a);
}
bean = (WebServiceFeature) ftrCtr.newInstance(params);
} catch (Exception e) {
throw new WebServiceException(e);
}
return bean;
}Example 35
| Project: googleads-java-lib-master File: DfpJaxWsSoapIntegrationTest.java View source code |
/**
* Tests that the request timeout in ads.properties is enforced.
*/
@Test
public void testRequestTimeoutEnforced() throws Exception {
System.setProperty("api.dfp.soapRequestTimeout", "100");
testHttpServer.setMockResponseBody(SoapResponseXmlProvider.getTestSoapResponse(API_VERSION));
testHttpServer.setDelay(200);
GoogleCredential credential = new GoogleCredential.Builder().setTransport(new NetHttpTransport()).setJsonFactory(new JacksonFactory()).build();
credential.setAccessToken("TEST_ACCESS_TOKEN");
DfpSession session = new DfpSession.Builder().withApplicationName("TEST_APP").withOAuth2Credential(credential).withEndpoint(testHttpServer.getServerUrl()).withNetworkCode("TEST_NETWORK_CODE").build();
CompanyServiceInterface companyService = new DfpServices().get(session, CompanyServiceInterface.class);
thrown.expect(WebServiceException.class);
thrown.expectMessage("Read timed out");
companyService.createCompanies(Lists.newArrayList(new Company()));
}Example 36
| Project: i2b2-master File: RestfulService.java View source code |
public Source invoke(Source source) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
StreamResult sr = new StreamResult(bos);
Transformer trans = TransformerFactory.newInstance().newTransformer();
Properties oprops = new Properties();
oprops.put(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperties(oprops);
trans.transform(source, sr);
System.out.println("**** Response ******" + bos.toString());
MessageContext mc = wsContext.getMessageContext();
String path = (String) mc.get(MessageContext.PATH_INFO);
String method = (String) mc.get(MessageContext.HTTP_REQUEST_METHOD);
System.out.println("Got HTTP " + method + " request for " + path);
if (method.equals("GET"))
return get(mc);
if (method.equals("POST"))
return post(source, mc);
if (method.equals("PUT"))
return put(source, mc);
if (method.equals("DELETE"))
return delete(source, mc);
throw new WebServiceException("Unsupported method:" + method);
} catch (Exception je) {
throw new WebServiceException(je);
}
}Example 37
| Project: javaone2015-cloudone-master File: LoadBalancer.java View source code |
private void update(ApplicationFullName appName, Ports ports) {
if (appName == null) {
return;
}
try {
HashMap<Integer, PortInfo> servicePorts = CumulonimbusClient.getInstance().getServicePorts(appName.getServiceName());
final List<Integer> registeredPorts = new ArrayList<>(servicePorts.size());
for (PortInfo portInfo : servicePorts.values()) {
Integer port = portInfo.getApplicationPorts().get(appName.getApplicationName());
if (port != null) {
registeredPorts.add(port);
}
}
//Check for added ports
final List<Integer> addPorts = new ArrayList<>();
final Set<Integer> checkedPorts = new HashSet<>(ports.ports.size());
for (Integer port : registeredPorts) {
boolean add = true;
for (Integer key : ports.ports.keySet()) {
if (key.equals(port)) {
add = false;
checkedPorts.add(port);
break;
}
}
if (add) {
addPorts.add(port);
}
}
//Check for removed ports
if (checkedPorts.size() < ports.ports.size()) {
Iterator<Map.Entry<Integer, Stats>> iterator = ports.ports.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<Integer, Stats> entry = iterator.next();
if (!checkedPorts.contains(entry.getKey())) {
iterator.remove();
}
}
}
//Add added ports
if (!addPorts.isEmpty()) {
long baseDuration = 0L;
Stats lowest = getLowest(ports);
if (lowest != null) {
baseDuration = lowest.durationSum;
}
for (Integer addPort : addPorts) {
ports.ports.put(addPort, new Stats(addPort, baseDuration));
}
}
//Update timestamp
ports.updated = System.currentTimeMillis();
} catch (WebServiceException webExc) {
LOGGER.warn("No more registered instance of service: " + appName.getServiceName() + "! Remove from cache");
ports.ports.clear();
ports.updated = System.currentTimeMillis();
} catch (Exception e) {
LOGGER.error("Cannot update ports for " + appName + "!", e);
}
}Example 38
| Project: JDK-master File: FactoryFinder.java View source code |
/**
* Creates an instance of the specified class using the specified
* <code>ClassLoader</code> object.
*
* @exception WebServiceException if the given class could not be found
* or could not be instantiated
*/
private static Object newInstance(String className, ClassLoader classLoader) {
try {
Class spiClass = safeLoadClass(className, classLoader);
return spiClass.newInstance();
} catch (ClassNotFoundException x) {
throw new WebServiceException("Provider " + className + " not found", x);
} catch (Exception x) {
throw new WebServiceException("Provider " + className + " could not be instantiated: " + x, x);
}
}Example 39
| Project: jsr352-master File: ExceptionClassFilterTest.java View source code |
@Test
public void exceptionClassFilter2() throws Exception {
final ClassLoader cl = this.getClass().getClassLoader();
final Job job = ArchiveXmlLoader.loadJobXml("exception-class-filter.xml", cl, new ArrayList<Job>(), new MetaInfBatchJobsJobXmlResolver());
Chunk chunk = getChunk(job, "exception-class-filter-step");
ExceptionClassFilter filter = chunk.getSkippableExceptionClasses();
Assert.assertEquals(false, filter.matches(Exception.class));
Assert.assertEquals(false, filter.matches(IOException.class));
filter = chunk.getRetryableExceptionClasses();
Assert.assertEquals(true, filter.matches(RuntimeException.class));
Assert.assertEquals(true, filter.matches(IllegalStateException.class));
Assert.assertEquals(true, filter.matches(AlreadyConnectedException.class));
Assert.assertEquals(false, filter.matches(Exception.class));
Assert.assertEquals(false, filter.matches(IOException.class));
filter = chunk.getNoRollbackExceptionClasses();
Assert.assertEquals(false, filter.matches(Exception.class));
Assert.assertEquals(false, filter.matches(RuntimeException.class));
Assert.assertEquals(false, filter.matches(IOException.class));
Assert.assertEquals(false, filter.matches(IllegalStateException.class));
Assert.assertEquals(false, filter.matches(AlreadyConnectedException.class));
chunk = getChunk(job, "exception-class-filter-step2");
filter = chunk.getSkippableExceptionClasses();
Assert.assertEquals(false, filter.matches(Exception.class));
Assert.assertEquals(false, filter.matches(IOException.class));
Assert.assertEquals(false, filter.matches(IllegalStateException.class));
Assert.assertEquals(false, filter.matches(AlreadyConnectedException.class));
filter = chunk.getRetryableExceptionClasses();
Assert.assertEquals(true, filter.matches(RuntimeException.class));
Assert.assertEquals(true, filter.matches(Exception.class));
Assert.assertEquals(true, filter.matches(IllegalArgumentException.class));
Assert.assertEquals(false, filter.matches(IllegalStateException.class));
Assert.assertEquals(false, filter.matches(AlreadyConnectedException.class));
Assert.assertEquals(false, filter.matches(IOException.class));
Assert.assertEquals(true, filter.matches(FileNotFoundException.class));
filter = chunk.getNoRollbackExceptionClasses();
Assert.assertEquals(true, filter.matches(Exception.class));
Assert.assertEquals(true, filter.matches(RuntimeException.class));
Assert.assertEquals(true, filter.matches(FileNotFoundException.class));
Assert.assertEquals(true, filter.matches(IllegalStateException.class));
Assert.assertEquals(true, filter.matches(AlreadyConnectedException.class));
chunk = getChunk(job, "exception-class-filter-step3");
filter = chunk.getSkippableExceptionClasses();
Assert.assertEquals(true, filter.matches(Exception.class));
Assert.assertEquals(true, filter.matches(java.io.EOFException.class));
Assert.assertEquals(false, filter.matches(IOException.class));
Assert.assertEquals(false, filter.matches(java.io.FileNotFoundException.class));
Assert.assertEquals(true, filter.matches(AlreadyConnectedException.class));
filter = chunk.getRetryableExceptionClasses();
Assert.assertEquals(true, filter.matches(Exception.class));
Assert.assertEquals(true, filter.matches(javax.xml.ws.WebServiceException.class));
Assert.assertEquals(false, filter.matches(java.lang.RuntimeException.class));
Assert.assertEquals(true, filter.matches(IOException.class));
Assert.assertEquals(true, filter.matches(FileNotFoundException.class));
Assert.assertEquals(false, filter.matches(AlreadyConnectedException.class));
Assert.assertEquals(true, filter.matches(javax.xml.ws.ProtocolException.class));
Assert.assertEquals(true, filter.matches(javax.xml.ws.http.HTTPException.class));
filter = chunk.getNoRollbackExceptionClasses();
Assert.assertEquals(true, filter.matches(IOException.class));
Assert.assertEquals(true, filter.matches(java.io.FileNotFoundException.class));
Assert.assertEquals(true, filter.matches(java.util.zip.ZipException.class));
Assert.assertEquals(true, filter.matches(java.util.jar.JarException.class));
Assert.assertEquals(false, filter.matches(Exception.class));
Assert.assertEquals(false, filter.matches(Throwable.class));
Assert.assertEquals(false, filter.matches(Error.class));
Assert.assertEquals(false, filter.matches(RuntimeException.class));
Assert.assertEquals(false, filter.matches(IllegalStateException.class));
}Example 40
| Project: keycloak-master File: ProductPortalServlet.java View source code |
private String sendWsReq(HttpServletRequest req, String productId, boolean secured) {
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(Product.class);
factory.setAddress("http://localhost:8282/ProductServiceCF");
Product simpleClient = (Product) factory.create();
java.lang.String _getProduct_productIdVal = productId;
javax.xml.ws.Holder<java.lang.String> _getProduct_productId = new javax.xml.ws.Holder<java.lang.String>(_getProduct_productIdVal);
javax.xml.ws.Holder<java.lang.String> _getProduct_name = new javax.xml.ws.Holder<java.lang.String>();
// Attach Authorization header
if (secured) {
Client clientProxy = ClientProxy.getClient(simpleClient);
KeycloakSecurityContext session = (KeycloakSecurityContext) req.getAttribute(KeycloakSecurityContext.class.getName());
Map<String, List<String>> headers = new HashMap<String, List<String>>();
headers.put("Authorization", Arrays.asList("Bearer " + session.getTokenString()));
clientProxy.getRequestContext().put(Message.PROTOCOL_HEADERS, headers);
}
try {
simpleClient.getProduct(_getProduct_productId, _getProduct_name);
return String.format("Product received: id=%s, name=%s", _getProduct_productId.value, _getProduct_name.value);
} catch (UnknownProductFault upf) {
return "UnknownProductFault has occurred. Details: " + upf.toString();
} catch (WebServiceException wse) {
String error = "Can't receive product. Reason: " + wse.getMessage();
if (wse.getCause() != null) {
Throwable cause = wse.getCause();
error = error + " Details: " + cause.getClass().getName() + ": " + cause.getMessage();
}
return error;
}
}Example 41
| Project: kfs-master File: AwardServiceImpl.java View source code |
@Override
public Collection findMatching(Map fieldValues) {
List<AwardDTO> result = null;
AwardFieldValuesDto criteria = new AwardFieldValuesDto();
Object awardId = fieldValues.get(KFSPropertyConstants.PROPOSAL_NUMBER);
if (awardId instanceof String) {
criteria.setAwardId(Long.parseLong((String) awardId));
} else {
criteria.setAwardId((Long) awardId);
}
criteria.setAwardNumber((String) fieldValues.get("awardNumber"));
criteria.setChartOfAccounts((String) fieldValues.get(KFSPropertyConstants.CHART_OF_ACCOUNTS_CODE));
criteria.setAccountNumber((String) fieldValues.get(KFSPropertyConstants.ACCOUNT_NUMBER));
criteria.setPrincipalInvestigatorId((String) fieldValues.get("principalId"));
try {
result = this.getWebService().getMatchingAwards(criteria);
} catch (WebServiceException ex) {
LOG.error(KcConstants.WEBSERVICE_UNREACHABLE, ex);
GlobalVariablesExtractHelper.insertError(KcConstants.WEBSERVICE_UNREACHABLE, getConfigurationService().getPropertyValueAsString(KFSConstants.KC_APPLICATION_URL_KEY));
}
if (result == null) {
return new ArrayList();
} else {
List<Award> awards = new ArrayList<Award>();
for (AwardDTO dto : result) {
awards.add(awardFromDTO(dto));
}
return awards;
}
}Example 42
| Project: opencirm-master File: OWLWebServiceCall.java View source code |
private void invoke(String wsdlLocation, String namespace, String serviceName, String portName, String endpoint, String soapAction, Set<OWLNamedIndividual> inputs, Set<OWLNamedIndividual> outputs, ArgumentMap argMap) throws Exception {
QName svc = new QName(namespace, serviceName);
QName port = new QName(namespace, portName);
Service service = Service.create(new URL(wsdlLocation), svc);
Dispatch<SOAPMessage> dispatch = service.createDispatch(port, SOAPMessage.class, Service.Mode.MESSAGE);
BindingProvider bp = (BindingProvider) dispatch;
if (endpoint != null)
bp.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, endpoint);
if (soapAction != null) {
bp.getRequestContext().put(BindingProvider.SOAPACTION_USE_PROPERTY, Boolean.TRUE);
bp.getRequestContext().put(BindingProvider.SOAPACTION_URI_PROPERTY, soapAction);
}
if (username != null && password != null) {
bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, username.getLiteral());
bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password.getLiteral());
}
MessageFactory factory = ((SOAPBinding) bp.getBinding()).getMessageFactory();
SOAPMessage request = factory.createMessage();
SOAPHeader header = request.getSOAPHeader();
SOAPBody body = request.getSOAPBody();
Document req = createRequest(namespace);
addInputs(req, inputs, argMap);
body.addDocument(req);
write(req);
SOAPMessage reply = null;
try {
reply = dispatch.invoke(request);
} catch (WebServiceException e) {
throw e;
}
try {
body = reply.getSOAPBody();
Document resp = body.extractContentAsDocument();
// write(resp);
getOutputs(resp, outputs, argMap);
} catch (SOAPException e) {
throw e;
}
}Example 43
| Project: opennaas-master File: AutobahnProtocolSession.java View source code |
private <T> T createSoapService(String uri, QName serviceName, QName portName, Class<T> clazz) throws ProtocolException {
/*
* The JAXWS SPI uses the context class loader to locate an implementation. We therefore make sure the context class loader is set to our
* class loader.
*/
Thread thread = Thread.currentThread();
ClassLoader oldLoader = thread.getContextClassLoader();
try {
thread.setContextClassLoader(getClass().getClassLoader());
Service service = Service.create(serviceName);
service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, uri);
return service.getPort(portName, clazz);
} catch (WebServiceException e) {
throw new ProtocolException("Failed to create Autobahn session: " + e.getMessage(), e);
} finally {
thread.setContextClassLoader(oldLoader);
}
}Example 44
| Project: opennaas-routing-nfv-master File: AutobahnProtocolSession.java View source code |
private <T> T createSoapService(String uri, QName serviceName, QName portName, Class<T> clazz) throws ProtocolException {
/*
* The JAXWS SPI uses the context class loader to locate an implementation. We therefore make sure the context class loader is set to our
* class loader.
*/
Thread thread = Thread.currentThread();
ClassLoader oldLoader = thread.getContextClassLoader();
try {
thread.setContextClassLoader(getClass().getClassLoader());
Service service = Service.create(serviceName);
service.addPort(portName, SOAPBinding.SOAP11HTTP_BINDING, uri);
return service.getPort(portName, clazz);
} catch (WebServiceException e) {
throw new ProtocolException("Failed to create Autobahn session: " + e.getMessage(), e);
} finally {
thread.setContextClassLoader(oldLoader);
}
}Example 45
| Project: Payara-master File: WebServiceReferenceManagerImpl.java View source code |
private WebServiceFeature getWebServiceFeatureBean(Annotation a) {
WebServiceFeatureAnnotation wsfa = a.annotationType().getAnnotation(WebServiceFeatureAnnotation.class);
Class<? extends WebServiceFeature> beanClass = wsfa.bean();
WebServiceFeature bean;
Constructor ftrCtr = null;
String[] paramNames = null;
for (Constructor con : beanClass.getConstructors()) {
FeatureConstructor ftrCtrAnn = (FeatureConstructor) con.getAnnotation(FeatureConstructor.class);
if (ftrCtrAnn != null) {
if (ftrCtr == null) {
ftrCtr = con;
paramNames = ftrCtrAnn.value();
} else {
throw new WebServiceException(ModelerMessages.RUNTIME_MODELER_WSFEATURE_MORETHANONE_FTRCONSTRUCTOR(a, beanClass));
}
}
}
if (ftrCtr == null) {
throw new WebServiceException(ModelerMessages.RUNTIME_MODELER_WSFEATURE_NO_FTRCONSTRUCTOR(a, beanClass));
}
if (ftrCtr.getParameterTypes().length != paramNames.length) {
throw new WebServiceException(ModelerMessages.RUNTIME_MODELER_WSFEATURE_ILLEGAL_FTRCONSTRUCTOR(a, beanClass));
}
try {
Object[] params = new Object[paramNames.length];
for (int i = 0; i < paramNames.length; i++) {
Method m = a.annotationType().getDeclaredMethod(paramNames[i]);
params[i] = m.invoke(a);
}
bean = (WebServiceFeature) ftrCtr.newInstance(params);
} catch (Exception e) {
throw new WebServiceException(e);
}
return bean;
}Example 46
| Project: release-master File: JBossWSEndpoint.java View source code |
/**
* {@inheritDoc}
*/
public void publish(ServiceDomain domain, String contextRoot, Map<String, String> urlPatternToClassNameMap, WebservicesMetaData wsMetadata, SOAPBindingModel bindingModel, InboundHandler handler) throws Exception {
EndpointConfigModel epcModel = bindingModel.getEndpointConfig();
JBossWebservicesMetaData jbwsMetadata = null;
if (epcModel != null) {
String configFile = epcModel.getConfigFile();
if (configFile != null) {
URL jbwsURL = Classes.getResource(configFile, getClass());
try {
JBossWebservicesFactory factory = new JBossWebservicesFactory(jbwsURL);
jbwsMetadata = factory.load(jbwsURL);
} catch (WebServiceException e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.error("Unable to load jboss-webservices metadata", e);
}
jbwsMetadata = new JBossWebservicesMetaData(jbwsURL);
jbwsMetadata.setConfigFile(configFile);
}
}
String configName = epcModel.getConfigName();
if (configName != null) {
if (jbwsMetadata == null) {
jbwsMetadata = new JBossWebservicesMetaData(null);
}
jbwsMetadata.setConfigName(configName);
}
}
ClassLoader tccl = Classes.getTCCL();
_context = _publisher.publish(contextRoot, tccl, urlPatternToClassNameMap, wsMetadata, jbwsMetadata);
for (org.jboss.wsf.spi.deployment.Endpoint ep : _context.getEndpoints()) {
BaseWebService wsProvider = (BaseWebService) ep.getInstanceProvider().getInstance(BaseWebService.class.getName()).getValue();
wsProvider.setInvocationClassLoader(tccl);
// Hook the handler
wsProvider.setConsumer(handler);
// Hook the interceptors
Interceptors.addInterceptors(ep, bindingModel, tccl);
// Set the security domain
ep.setSecurityDomainContext(new SwitchYardSecurityDomainContext(domain.getServiceSecurity(bindingModel.getService().getComponentService().getSecurity()).getSecurityDomain(), ep.getSecurityDomainContext()));
}
WebResource resource = SwitchYardDeployment.getResource(domain, contextRoot);
if (resource == null) {
resource = new WebResource();
resource.setStarted(true);
WebDeploymentController handle = _context.getEndpoints().get(0).getService().getDeployment().getAttachment(WebDeploymentController.class);
resource.setHandle(handle);
WebDeploymentBuilder deployment = new WebDeploymentBuilder();
deployment.setContextRoot(contextRoot);
ServletBuilder servlet = new ServletBuilder();
servlet.setServletClass(WSFServlet.class);
deployment.addServlet(servlet);
// A dummy deployment builder
resource.setDeployment(deployment);
SwitchYardDeployment.addResource(domain, resource);
}
setWebResource(resource);
}Example 47
| Project: resin-master File: AbstractAction.java View source code |
public static AbstractAction createAction(Method method, JAXBContextImpl jaxbContext, String targetNamespace, WSDLDefinitions wsdl, Marshaller marshaller, Unmarshaller unmarshaller) throws JAXBException, WebServiceException { // There are three valid modes in JAX-WS: // // 1. Document wrapped -- all the parameters and return values // are encapsulated in a single encoded object (i.e. the document). // This is selected by // SOAPBinding.style() == DOCUMENT // SOAPBinding.use() == LITERAL // SOAPBinding.parameterStyle() == WRAPPED // // 2. Document bare -- the method must have at most one input and // one output parameter. No wrapper objects are created. // This is selected by // SOAPBinding.style() == DOCUMENT // SOAPBinding.use() == LITERAL // SOAPBinding.parameterStyle() == BARE // // 3. RPC style -- parameters and return values are mapped to // wsdl:parts. This is selected by: // SOAPBinding.style() == RPC // SOAPBinding.use() == LITERAL // SOAPBinding.parameterStyle() == WRAPPED // // It seems that "use" is never ENCODED in JAX-WS and is not allowed // by WS-I, so we don't allow it either. // // Check for the SOAPBinding annotation... // look at the declaring class and method first Class cl = method.getDeclaringClass(); Method eiMethod = null; SOAPBinding soapBinding = (SOAPBinding) cl.getAnnotation(SOAPBinding.class); if (method.isAnnotationPresent(SOAPBinding.class)) soapBinding = method.getAnnotation(SOAPBinding.class); if (soapBinding == null) { // Then look at the endpoint interface, if available WebService webService = (WebService) cl.getAnnotation(WebService.class); if (webService != null) { if (!"".equals(webService.endpointInterface())) { try { ClassLoader loader = cl.getClassLoader(); Class endpointInterface = loader.loadClass(webService.endpointInterface()); soapBinding = (SOAPBinding) endpointInterface.getAnnotation(SOAPBinding.class); eiMethod = endpointInterface.getMethod(method.getName(), method.getParameterTypes()); if (eiMethod.isAnnotationPresent(SOAPBinding.class)) soapBinding = eiMethod.getAnnotation(SOAPBinding.class); } catch (ClassNotFoundException e) { throw new WebServiceException(L.l("Endpoint interface {0} not found", webService.endpointInterface()), e); } catch (NoSuchMethodException e) { } } } } // Document wrapped is the default for methods w/o a @SOAPBinding if (soapBinding == null) return new DocumentWrappedAction(method, eiMethod, jaxbContext, targetNamespace, wsdl, marshaller, unmarshaller); if (soapBinding.use() == SOAPBinding.Use.ENCODED) throw new UnsupportedOperationException(L.l("SOAP encoded style is not supported by JAX-WS")); if (soapBinding.style() == SOAPBinding.Style.DOCUMENT) { if (soapBinding.parameterStyle() == SOAPBinding.ParameterStyle.WRAPPED) return new DocumentWrappedAction(method, eiMethod, jaxbContext, targetNamespace, wsdl, marshaller, unmarshaller); else { return new DocumentBareAction(method, eiMethod, jaxbContext, targetNamespace, wsdl, marshaller, unmarshaller); } } else { if (soapBinding.parameterStyle() != SOAPBinding.ParameterStyle.WRAPPED) throw new UnsupportedOperationException(L.l("SOAP RPC bare style not supported")); return new RpcAction(method, eiMethod, jaxbContext, targetNamespace, wsdl, marshaller, unmarshaller); } }
Example 48
| Project: sf-api-connector-master File: PartnerConnectionImpl.java View source code |
private Tout executeOpWrapper(ConfiguredBinding<Soap> configuredBinding, Tin param) throws ApiException {
Timer.Context context = timer.time();
Tout out;
try {
// release the permit sooner since getUsername() used by getApiException can also cause an api hit
PartnerConnectionImpl.this.acquireSemaphore();
try {
out = this.executeOp(configuredBinding.getBinding(), param);
} finally {
PartnerConnectionImpl.this.releaseSemaphore();
}
} catch (InvalidFieldFault_Exception e) {
throw this.getApiExceptionWithCauseAndQueryFault("Invalid field", e, e.getFaultInfo());
} catch (InvalidIdFault_Exception e) {
throw this.getApiExceptionWithCauseAndFault("Invalid Id", e, e.getFaultInfo());
} catch (InvalidQueryLocatorFault_Exception e) {
throw this.getApiExceptionWithCauseAndFault("Invalid query locator", e, e.getFaultInfo());
} catch (InvalidSObjectFault_Exception e) {
throw this.getApiExceptionWithCauseAndQueryFault("Invalid SObject", e, e.getFaultInfo());
} catch (MalformedQueryFault_Exception e) {
throw this.getApiExceptionWithCauseAndQueryFault("Malformed query", e, e.getFaultInfo());
} catch (UnexpectedErrorFault_Exception e) {
throw this.getApiExceptionWithCauseAndFault("Unexpected error", e, e.getFaultInfo());
} catch (WebServiceException e) {
throw PartnerConnectionImpl.this.getApiExceptionWithCause("Web Service exception", e);
} finally {
context.stop();
}
return out;
}Example 49
| Project: sharepoint-master File: SharePointAdaptorTest.java View source code |
@Test
public void testGetDocContentVirtualServerContentDBError() throws Exception {
MockPeopleSoap mockPeople = new MockPeopleSoap();
mockPeople.addToResult("NT AUTHORITY\\LOCAL SERVICE", "NT AUTHORITY\\LOCAL SERVICE", SPPrincipalType.USER);
mockPeople.addToResult("GDC-PSL\\spuser1", "spuser1", SPPrincipalType.USER);
mockPeople.addToResult("GDC-PSL\\Administrator", "dministrator", SPPrincipalType.USER);
SoapFactory siteDataFactory = MockSoapFactory.blank().endpoint(VS_ENDPOINT, MockSiteData.blank().register(VS_CONTENT_EXCHANGE.replaceInContent("</ContentDatabases>", "<ContentDatabase ID=\"{error content db}\" />" + "</ContentDatabases>")).register(CD_CONTENT_EXCHANGE).register(new ContentExchange(ObjectType.CONTENT_DATABASE, "{error content db}", null, null, true, false, null, "error", new WebServiceException("Content database not available")))).endpoint("http://localhost:1/_vti_bin/People.asmx", mockPeople);
adaptor = new SharePointAdaptor(siteDataFactory, new UnsupportedHttpClient(), executorFactory, new MockAuthenticationClientFactoryForms(), new UnsupportedActiveDirectoryClientFactory());
adaptor.init(new MockAdaptorContext(config, pusher));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GetContentsResponse response = new GetContentsResponse(baos);
adaptor.getDocContent(new GetContentsRequest(new DocId("")), response);
String responseString = new String(baos.toByteArray(), charset);
final String golden = "<!DOCTYPE html>\n" + "<html><head><title>http://localhost:1/</title></head>" + "<body><h1><!--googleoff: index-->Virtual Server" + "<!--googleon: index--> http://localhost:1/</h1>" + "<p><!--googleoff: index-->Sites<!--googleon: index--></p><ul>" + // prefix is correct.
"<li><a href=\"./http://localhost:1\">localhost:1</a></li>" + "<li><a href=\"./http://localhost:1/sites/SiteCollection\">" + "SiteCollection</a></li>" + "</ul></body></html>";
assertEquals(golden, responseString);
assertEquals(new Acl.Builder().setEverythingCaseInsensitive().setInheritanceType(Acl.InheritanceType.PARENT_OVERRIDES).setPermitUsers(Arrays.asList(GDC_PSL_ADMINISTRATOR, GDC_PSL_SPUSER1, NT_AUTHORITY_LOCAL_SERVICE)).build(), response.getAcl());
assertNull(response.getDisplayUrl());
}Example 50
| Project: spring-framework-master File: JaxWsPortClientInterceptor.java View source code |
/**
* Perform a JAX-WS service invocation based on the given method invocation.
* @param invocation the AOP method invocation
* @return the invocation result, if any
* @throws Throwable in case of invocation failure
* @see #getPortStub()
* @see #doInvoke(org.aopalliance.intercept.MethodInvocation, Object)
*/
protected Object doInvoke(MethodInvocation invocation) throws Throwable {
try {
return doInvoke(invocation, getPortStub());
} catch (SOAPFaultException ex) {
throw new JaxWsSoapFaultException(ex);
} catch (ProtocolException ex) {
throw new RemoteConnectFailureException("Could not connect to remote service [" + getEndpointAddress() + "]", ex);
} catch (WebServiceException ex) {
throw new RemoteAccessException("Could not access remote service at [" + getEndpointAddress() + "]", ex);
}
}Example 51
| Project: syncope-master File: SyncopeView.java View source code |
public void run() {
Shell shell = viewer.getControl().getShell();
if (e instanceof java.security.AccessControlException) {
MessageDialog.openError(shell, "Incorrect Credentials", "Unable to authenticate " + vcp.username);
} else if (e instanceof javax.ws.rs.ProcessingException) {
MessageDialog.openError(shell, "Incorrect Url", "Unable to find apache syncope at " + vcp.deploymentUrl);
} else if (e instanceof javax.xml.ws.WebServiceException) {
MessageDialog.openError(shell, "Invalid Url", "Not a valid url " + vcp.username);
} else {
e.printStackTrace();
}
}Example 52
| Project: teiid-master File: WSConnectionImpl.java View source code |
@Override
public DataSource invoke(DataSource msg) {
try {
final URL url = new URL(this.endpoint);
//ensure this is a valid uri
url.toURI();
final String httpMethod = (String) this.requestContext.get(MessageContext.HTTP_REQUEST_METHOD);
// see to use patch
// http://stackoverflow.com/questions/32067687/how-to-use-patch-method-in-cxf
Bus bus = getBus(this.configFile);
if (httpMethod.equals("PATCH")) {
bus.setProperty("use.async.http.conduit", Boolean.TRUE);
bus.setExtension(new AsyncHTTPConduitFactory(bus), HTTPConduitFactory.class);
}
this.client = createWebClient(this.endpoint, bus);
Map<String, List<String>> header = (Map<String, List<String>>) this.requestContext.get(MessageContext.HTTP_REQUEST_HEADERS);
for (Map.Entry<String, List<String>> entry : header.entrySet()) {
this.client.header(entry.getKey(), entry.getValue().toArray());
}
if (this.requestContext.get(AuthorizationPolicy.class.getName()) != null) {
HTTPConduit conduit = (HTTPConduit) WebClient.getConfig(this.client).getConduit();
AuthorizationPolicy policy = (AuthorizationPolicy) this.requestContext.get(AuthorizationPolicy.class.getName());
conduit.setAuthorization(policy);
} else if (this.requestContext.get(GSSCredential.class.getName()) != null) {
WebClient.getConfig(this.client).getRequestContext().put(GSSCredential.class.getName(), this.requestContext.get(GSSCredential.class.getName()));
//$NON-NLS-1$
WebClient.getConfig(this.client).getRequestContext().put("auth.spnego.requireCredDelegation", true);
} else if (this.requestContext.get(OAuthCredential.class.getName()) != null) {
OAuthCredential credential = (OAuthCredential) this.requestContext.get(OAuthCredential.class.getName());
this.client.header(AUTHORIZATION, credential.getAuthorizationHeader(this.endpoint, httpMethod));
}
InputStream payload = null;
if (msg != null) {
payload = msg.getInputStream();
}
HTTPClientPolicy clientPolicy = WebClient.getConfig(this.client).getHttpConduit().getClient();
Long timeout = (Long) this.requestContext.get(RECEIVE_TIMEOUT);
if (timeout != null) {
clientPolicy.setReceiveTimeout(timeout);
}
timeout = (Long) this.requestContext.get(CONNECTION_TIMEOUT);
if (timeout != null) {
clientPolicy.setConnectionTimeout(timeout);
}
javax.ws.rs.core.Response response = this.client.invoke(httpMethod, payload);
this.responseContext.put(WSConnection.STATUS_CODE, response.getStatus());
this.responseContext.putAll(response.getMetadata());
ArrayList contentTypes = (ArrayList) //$NON-NLS-1$
this.responseContext.get(//$NON-NLS-1$
"content-type");
String contentType = contentTypes != null ? (String) contentTypes.get(0) : "application/octet-stream";
return new HttpDataSource(url, (InputStream) response.getEntity(), contentType);
} catch (IOException e) {
throw new WebServiceException(e);
} catch (URISyntaxException e) {
throw new WebServiceException(e);
}
}Example 53
| Project: tomee-master File: JaxWsProviderWrapper.java View source code |
private static Provider findProvider() {
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null) {
classLoader = ClassLoader.getSystemClassLoader();
}
// 0. System.getProperty("openejb.javax.xml.ws.spi.Provider")
// This is so those using old axis rules still work as expected
String providerClass = System.getProperty("openejb." + JAXWSPROVIDER_PROPERTY);
Provider provider = createProviderInstance(providerClass, classLoader);
if (provider != null) {
return provider;
}
// 1. META-INF/services/javax.xml.ws.spi.Provider
try {
for (final URL url : Collections.list(classLoader.getResources("META-INF/services/" + JAXWSPROVIDER_PROPERTY))) {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(url.openStream()));
providerClass = in.readLine();
provider = createProviderInstance(providerClass, classLoader);
if (provider != null) {
return provider;
}
} catch (Exception ignored) {
} finally {
if (in != null) {
try {
in.close();
} catch (Throwable e) {
}
}
}
}
} catch (Exception ingored) {
logger.log(Level.INFO, "No META-INF/services/javax.xml.ws.spi.Provider found");
}
// 2. $java.home/lib/jaxws.properties
final String javaHome = System.getProperty("java.home");
final File jaxrpcPropertiesFile = new File(new File(javaHome, "lib"), "jaxrpc.properties");
if (jaxrpcPropertiesFile.exists()) {
InputStream in = null;
try {
in = new FileInputStream(jaxrpcPropertiesFile);
final Properties properties = new Properties();
properties.load(in);
providerClass = properties.getProperty(JAXWSPROVIDER_PROPERTY);
provider = createProviderInstance(providerClass, classLoader);
if (provider != null) {
return provider;
}
} catch (Exception ignored) {
} finally {
if (in != null) {
try {
in.close();
} catch (Throwable e) {
}
}
}
}
// 3. System.getProperty("javax.xml.ws.spi.Provider")
providerClass = System.getProperty(JAXWSPROVIDER_PROPERTY);
provider = createProviderInstance(providerClass, classLoader);
if (provider != null) {
return provider;
}
// 4. Use javax.xml.ws.spi.Provider default
try {
// disable the OpenEJB JaxWS provider
if (classLoader instanceof ProviderClassLoader) {
((ProviderClassLoader) classLoader).enabled = false;
}
System.getProperties().remove(JAXWSPROVIDER_PROPERTY);
provider = Provider.provider();
if (provider != null && !provider.getClass().getName().equals(JaxWsProviderWrapper.class.getName())) {
return provider;
}
} finally {
// reenable the OpenEJB JaxWS provider
System.setProperty(JAXWSPROVIDER_PROPERTY, providerClass);
if (classLoader instanceof ProviderClassLoader) {
((ProviderClassLoader) classLoader).enabled = true;
}
}
throw new WebServiceException("No " + JAXWSPROVIDER_PROPERTY + " implementation found");
}Example 54
| Project: erechnung.gv.at-webservice-client-master File: WS200Sender.java View source code |
/**
* This is the main sending routine. It can be invoked multiple times with
* different invoices.
*
* @param aOriginalInvoice
* The original invoice in an XML representation. May not be
* <code>null</code>. It may be in any of the formats supported by
* ER>B (ebInterface 3.0, 3.02, 4.0, 4.1 or UBL 2.0, 2.1).
* @param aAttachments
* An optional list of attachments to this invoice. If the list is non-
* <code>null</code> it must contain only non-<code>null</code>
* elements.
* @param aSettings
* The settings element as specified by the ER>B Webservice 1.2.
* Within this settings element e.g. the test-flag can be set. May not
* be <code>null</code>.
* @return A non-<code>null</code> upload status as returned by the ER>B
* Webservice. In case of an internal error, a corresponding error
* structure is created.
*/
@Nonnull
public DeliveryResponseType deliverInvoice(@Nonnull final Node aOriginalInvoice, @Nullable final List<DeliveryEmbeddedAttachmentType> aAttachments, @Nonnull final DeliverySettingsType aSettings) {
ValueEnforcer.notNull(aOriginalInvoice, "OriginalInvoice");
ValueEnforcer.notNull(aSettings, "Settings");
// Some debug output
SystemProperties.setPropertyValue("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", isDebugMode());
SystemProperties.setPropertyValue("com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump", isDebugMode());
// Convert XML node to a String
final XMLWriterSettings aXWS = new XMLWriterSettings().setCharset(getInvoiceEncoding());
final String sInvoiceString = XMLWriter.getNodeAsString(aOriginalInvoice, aXWS);
if (sInvoiceString == null) {
s_aLogger.error("Failed to serialize the specified XML document to a String!");
return _createError("document", "Failed to serialize the specified XML document to a String!");
}
// Prepare document
final DeliveryType aDelivery = new DeliveryType();
// Main invoice
final DeliveryInvoiceType aInvoice = new DeliveryInvoiceType();
aInvoice.setValue(sInvoiceString.getBytes(getInvoiceEncoding()));
aInvoice.setEncoding(getInvoiceEncoding().name());
aDelivery.setInvoice(aInvoice);
// Embedded attachments
aDelivery.setEmbeddedAttachment(aAttachments);
// ER>B does not support external attachments!
// Settings
aDelivery.setSettings(aSettings);
try {
final WSClientConfig aWSClientConfig = new WSClientConfig(isTestVersion() ? ENDPOINT_URL_TEST : ENDPOINT_URL_PRODUCTION);
if (isTrustAllCertificates()) {
// Maybe required to trust txm.portal.at depending on the installed OS
// root certificates.
aWSClientConfig.setSSLSocketFactoryTrustAll();
}
if (isTrustAllHostnames())
aWSClientConfig.setHostnameVerifierTrustAll();
// Ensure the WSSE headers are added using our handler
aWSClientConfig.addHandler(new SOAPAddWSSEHeaderHandler(getWebserviceUsername(), getWebservicePassword()));
// Invoke WS
final WSInvoiceDeliveryService aService = new WSInvoiceDeliveryService();
final WSInvoiceDeliveryPort aPort = aService.getWSInvoiceDeliveryPort();
aWSClientConfig.applyWSSettingsToBindingProvider((BindingProvider) aPort);
// Main sending
final DeliveryResponseType aResult = aPort.deliverInvoice(aDelivery);
return aResult;
} catch (final DeliverInvoiceFaultInvoice ex) {
s_aLogger.error("Error uploading the document to ER>B Webservice 2.0!", ex);
return _createError("document", ex.getFaultInfo() != null ? ex.getFaultInfo().getMessage() : CollectionHelper.newList(ex.getMessage()));
} catch (final WebServiceException ex) {
s_aLogger.error("Error transmitting the document to ER>B Webservice 2.0!", ex);
return _createError("webservice", ex.getMessage());
} catch (final Throwable t) {
s_aLogger.error("Generic error invoking ER>B Webservice 2.0", t);
return _createError("general", t.getMessage());
}
}Example 55
| Project: Genoogle-master File: WebServices.java View source code |
@SuppressWarnings("unchecked")
@WebMethod(operationName = "parameters")
public List<String> parameters() {
MessageContext mc = wsContext.getMessageContext();
HttpSession session = ((javax.servlet.http.HttpServletRequest) mc.get(MessageContext.SERVLET_REQUEST)).getSession();
if (session == null) {
throw new WebServiceException("No session in WebServiceContext");
}
Map<Parameter, Object> parameters = (Map<Parameter, Object>) session.getAttribute("parameters");
if (parameters == null) {
parameters = SearchParams.getSearchParamsMap();
}
List<String> parametersList = Lists.newLinkedList();
for (Entry<Parameter, Object> entry : parameters.entrySet()) {
parametersList.add(entry.getKey().toString() + "=" + entry.getValue().toString());
}
return parametersList;
}Example 56
| Project: geronimo-specs-master File: W3CEndpointReference.java View source code |
@Override
public void writeTo(Result result) {
if (result == null) {
//TODO NLS enable
throw new IllegalArgumentException("Null is not allowed.");
}
try {
Marshaller m = jaxbContext.createMarshaller();
m.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
m.marshal(this, result);
} catch (Exception e) {
throw new WebServiceException("writeTo failure.", e);
}
}Example 57
| Project: jboss-fuse-examples-master File: WsHelloWorldServiceTest.java View source code |
@Test(expected = WebServiceException.class)
public void callFailsOverHttp() throws InvalidObjectException {
HelloWorldRequest request = new HelloWorldRequest();
request.setHello("bob");
WsEndpointConfiguration<HelloWorldEndpoint> config = getDefaultConfig();
config.setWsAddress("http://0.0.0.0:9001/cxf/helloWorldService");
WsHelloWorldService service = new WsHelloWorldService(config, isCxfBeanFactory());
HelloWorldResponse response = service.sayHello(request);
Assert.assertNotNull(response);
Assert.assertNotNull(response.getGoodbye());
Assert.assertTrue(response.getGoodbye().length() > 0);
Assert.assertTrue(response.getGoodbye().startsWith(request.getHello()));
}Example 58
| Project: jboss-jaxws-api_spec-master File: FactoryFinder.java View source code |
/**
* Creates an instance of the specified class using the specified
* <code>ClassLoader</code> object.
*
* @exception WebServiceException if the given class could not be found
* or could not be instantiated
*/
private static Object newInstance(String className, ClassLoader classLoader) {
try {
Class spiClass = safeLoadClass(className, classLoader);
return spiClass.newInstance();
} catch (ClassNotFoundException x) {
throw new WebServiceException("Provider " + className + " not found", x);
} catch (Exception x) {
throw new WebServiceException("Provider " + className + " could not be instantiated: " + x, x);
}
}Example 59
| Project: mbit-cloud-platform-master File: AwsApaRequesterImpl.java View source code |
@Override
public ItemSearchResponse itemSearch(ItemSearchRequest request) {
final AWSECommerceServicePortType port = preparePort();
final ItemSearch itemSearch = prepareItemSearch(request);
ItemSearchResponse response = invokeWithRetry(new WebServiceInvoker<ItemSearchResponse>() {
@Override
public ItemSearchResponse invoke() throws WebServiceException {
return port.itemSearch(itemSearch);
}
});
return response;
}Example 60
| Project: nuxeo-chemistry-master File: CmisFeatureSessionWebServices.java View source code |
/*
* Puts in the servlet context the proper delegate expected by WSServlet.
*/
@Override
public void contextInitialized(ServletContextEvent event) {
try {
ServletContext context = event.getServletContext();
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null) {
cl = getClass().getClassLoader();
}
ResourceLoader loader = new ServletContextResourceLoader(context);
Container container = newServletContainer(context);
AdapterFactory<ServletAdapter> adapterFactory = new ServletAdapterList();
DeploymentDescriptorParser<ServletAdapter> parser = new DeploymentDescriptorParser<ServletAdapter>(cl, loader, container, adapterFactory);
URL endpoints = context.getResource(JAXWS_XML);
if (endpoints == null) {
throw new WebServiceException("No endpoints configured, missing file: " + JAXWS_XML);
}
List<ServletAdapter> adapters = parser.parse(endpoints.toExternalForm(), endpoints.openStream());
delegate = new WSServletDelegate(adapters, context);
context.setAttribute(WSServlet.JAXWS_RI_RUNTIME_INFO, delegate);
} catch (WebServiceException e) {
throw e;
} catch (Exception e) {
throw new WebServiceException(e.toString(), e);
}
}Example 61
| Project: opencit-master File: VMwareConnectionPool.java View source code |
/**
* Creates a new client for the given connection string and adds it to the
* pool. If there was already an existing client for that connection string,
* it is replaced with the new one.
*
* For normal use you should call getClientForConnection(String) because it
* will re-use existing connections and automatically create new ones as needed.
*
* @param connectionString
* @return
* @throws VMwareConnectionException
*/
public VMwareClient createClientForConnection(TlsConnection tlsConnection) throws VMwareConnectionException {
try {
// log.debug("VMwareConnectionPool create client for connection {}", tlsConnection.getConnectionString());
VMwareClient client = factory.makeObject(tlsConnection);
if (factory.validateObject(tlsConnection, client)) {
// log.debug("VMwareConnectionPool caching new connection {}", tlsConnection.getConnectionString());
pool.put(tlsConnection, client);
// log.debug("Opening new vCenter connection for "+client.getEndpoint());
return client;
} else {
throw new Exception("Failed to validate new vmware connection");
}
} catch (javax.xml.ws.WebServiceException e) {
if (e.getCause() != null && e.getCause() instanceof javax.net.ssl.SSLHandshakeException) {
javax.net.ssl.SSLHandshakeException e2 = (javax.net.ssl.SSLHandshakeException) e.getCause();
if (e2.getCause() != null && e2.getCause() instanceof com.intel.dcsg.cpg.tls.policy.UnknownCertificateException) {
com.intel.dcsg.cpg.tls.policy.UnknownCertificateException e3 = (com.intel.dcsg.cpg.tls.policy.UnknownCertificateException) e2.getCause();
log.warn("Failed to connect to vcenter due to unknown certificate exception: {}", e3.toString());
X509Certificate[] chain = e3.getCertificateChain();
if (chain == null || chain.length == 0) {
log.error("Server certificate is missing");
} else {
for (X509Certificate certificate : chain) {
try {
log.debug("Server certificate fingerprint: {} and subject: {}", new Sha1Digest(X509Util.sha1fingerprint(certificate)), certificate.getSubjectX500Principal().getName());
} catch (NoSuchAlgorithmException e4) {
log.error("Cannot read server certificate: {}", e4.toString(), e4);
throw new VMwareConnectionException(e4);
} catch (CertificateEncodingException e4) {
log.error("Cannot read server certificate: {}", e4.toString(), e4);
throw new VMwareConnectionException(e4);
}
}
throw new VMwareConnectionException("VMwareConnectionPool not able to read host information: " + e3.toString());
}
} else {
throw new VMwareConnectionException("Failed to connect to vcenter due to SSL handshake exception", e2);
}
} else {
throw new VMwareConnectionException("Failed to connect to vcenter due to exception: " + e.toString(), e);
}
} catch (Exception e) {
log.error("Failed to connect to vcenter: " + e.toString(), e);
e.printStackTrace(System.err);
throw new VMwareConnectionException("Cannot connect to vcenter: " + tlsConnection.getURL().getHost(), e);
}
throw new VMwareConnectionException("Failed to connect to vcenter: unknown error");
}Example 62
| Project: proarc-master File: DesaClient.java View source code |
/**
* Authenticates an operator.
*
* @param operator operator user name
* @param passwd operator password
* @param producerCode producer code (not ID)
* @return the authenticated operator
* @throws AuthenticateUserFault authentication failure
* @throws WebServiceException soap failure
*/
public AuthenticateUserResponse authenticateUser(String operator, String passwd, String producerCode) throws AuthenticateUserFault, WebServiceException {
AuthenticateUserRequest request = new AuthenticateUserRequest();
request.setLogin(operator);
request.setPassword(passwd);
request.setProducerCode(producerCode);
AuthenticateUserResponse response = getSoapClient().authenticateUser(request);
if ("OK".equals(response.getStatus())) {
return response;
} else {
String msg = String.format("operator: %s, producer: %s, status: %s", operator, producerCode, response.getStatus());
throw new AuthenticateUserFault(msg, null);
}
}Example 63
| Project: cxf-circuit-switcher-master File: JaxwsFailoverIntegrationTest.java View source code |
@Test(expected = WebServiceException.class)
public void shouldThrowExceptionAfterAllNodesFail() throws SAXException, IOException {
CircuitSwitcherClusteringFeature cbcFeature = createCircuitBreakerFeature();
cbcFeature.setFailureThreshold(1);
cbcFeature.setResetTimeout(100000);
cbcFeature.setReceiveTimeout(800l);
Greeter greeterClient = createServiceClient(cbcFeature);
// causing timeout on node1 (1st request)
node1Controller.webserviceOperation(sayHiOperation).setUp(sayHiResponse().withResponseDelaySec(1));
// causing timeout on node2 (1st request)
node2Controller.webserviceOperation(sayHiOperation).setUp(sayHiResponse().withResponseDelaySec(1));
// no more nodes are available
try {
greeterClient.sayHi();
} finally {
Document recordedRequests1Node = node1Controller.webserviceOperation(sayHiOperation).recordedRequests();
assertThat(recordedRequests1Node, hasXPath("count(//sayHi)", equalTo("1")));
Document recordedRequests2Node = node2Controller.webserviceOperation(sayHiOperation).recordedRequests();
assertThat(recordedRequests2Node, hasXPath("count(//sayHi)", equalTo("1")));
}
}Example 64
| Project: federation-master File: PicketLinkSTSUnitTestCase.java View source code |
/**
* <p>
* This test case first generates a SAMLV1.1 assertion and then sends a WS-Trust cancel message to the STS to cancel the
* assertion. A canceled assertion cannot be renewed or considered valid anymore.
* </p>
*
* @throws Exception if an error occurs while running the test.
*/
@Test
public void testInvokeSAML11Cancel() throws Exception {
// create a simple token request.
RequestSecurityToken request = this.createRequest("testcontext", WSTrustConstants.ISSUE_REQUEST, SAMLUtil.SAML11_TOKEN_TYPE, null);
Source requestMessage = this.createSourceFromRequest(request);
// invoke the token service.
Source responseMessage = this.tokenService.invoke(requestMessage);
WSTrustParser parser = new WSTrustParser();
BaseRequestSecurityTokenResponse baseResponse = (BaseRequestSecurityTokenResponse) parser.parse(DocumentUtil.getSourceAsStream(responseMessage));
// validate the response and get the SAML assertion from the request.
this.validateSAML11AssertionResponse(baseResponse, "testcontext", "jduke", SAMLUtil.SAML11_BEARER_URI);
RequestSecurityTokenResponseCollection collection = (RequestSecurityTokenResponseCollection) baseResponse;
Element assertion = (Element) collection.getRequestSecurityTokenResponses().get(0).getRequestedSecurityToken().getAny().get(0);
// now construct a WS-Trust cancel request with the generated assertion.
request = this.createRequest("cancelcontext", WSTrustConstants.CANCEL_REQUEST, null, null);
CancelTargetType cancelTarget = new CancelTargetType();
cancelTarget.add(assertion);
request.setCancelTarget(cancelTarget);
// invoke the token service.
responseMessage = this.tokenService.invoke(this.createSourceFromRequest(request));
baseResponse = (BaseRequestSecurityTokenResponse) parser.parse(DocumentUtil.getSourceAsStream(responseMessage));
// validate the response contents.
assertNotNull("Unexpected null response", baseResponse);
assertTrue("Unexpected response type", baseResponse instanceof RequestSecurityTokenResponseCollection);
collection = (RequestSecurityTokenResponseCollection) baseResponse;
assertEquals("Unexpected number of responses", 1, collection.getRequestSecurityTokenResponses().size());
RequestSecurityTokenResponse response = collection.getRequestSecurityTokenResponses().get(0);
assertEquals("Unexpected response context", "cancelcontext", response.getContext());
assertNotNull("Cancel response should contain a RequestedTokenCancelled element", response.getRequestedTokenCancelled());
// try to validate the canceled assertion.
request = this.createRequest("validatecontext", WSTrustConstants.VALIDATE_REQUEST, null, null);
ValidateTargetType validateTarget = new ValidateTargetType();
validateTarget.add(assertion);
request.setValidateTarget(validateTarget);
// the response should contain a status indicating that the token is not valid.
responseMessage = this.tokenService.invoke(this.createSourceFromRequest(request));
collection = (RequestSecurityTokenResponseCollection) parser.parse(DocumentUtil.getSourceAsStream(responseMessage));
assertEquals("Unexpected number of responses", 1, collection.getRequestSecurityTokenResponses().size());
response = collection.getRequestSecurityTokenResponses().get(0);
assertEquals("Unexpected response context", "validatecontext", response.getContext());
assertEquals("Unexpected token type", WSTrustConstants.STATUS_TYPE, response.getTokenType().toString());
StatusType status = response.getStatus();
assertNotNull("Unexpected null status", status);
assertEquals("Unexpected status code", WSTrustConstants.STATUS_CODE_INVALID, status.getCode());
assertEquals("Unexpected status reason", "Validation failure: assertion with id " + assertion.getAttribute("AssertionID") + " has been canceled", status.getReason());
// now try to renew the canceled assertion.
request = this.createRequest("renewcontext", WSTrustConstants.RENEW_REQUEST, null, null);
RenewTargetType renewTarget = new RenewTargetType();
renewTarget.add(assertion);
request.setRenewTarget(renewTarget);
// we should receive an exception when renewing the token.
try {
this.tokenService.invoke(this.createSourceFromRequest(request));
fail("Renewing a canceled token should result in an exception being thrown");
} catch (WebServiceException we) {
Throwable t = we.getCause();
assertTrue("Unexpected cause type", t instanceof WSTrustException);
String msg = t.getMessage();
if (msg.contains("has been canceled and cannot be renewed") == false)
throw new RuntimeException("Unexpected exception message");
}
}Example 65
| Project: jbosgi-master File: WebServiceEndpointTestCase.java View source code |
@Test
public void testDeferredBundleWithWabExtension() throws Exception {
InputStream input = deployer.getDeployment(BUNDLE_C_WAB);
Bundle bundle = context.installBundle(BUNDLE_C_WAB, input);
try {
Assert.assertEquals("INSTALLED", Bundle.INSTALLED, bundle.getState());
try {
QName serviceName = new QName("http://osgi.smoke.test.as.jboss.org", "EndpointService");
Service service = Service.create(getWsdl("/bundle-c"), serviceName);
Endpoint port = service.getPort(Endpoint.class);
port.echo("Foo");
Assert.fail("WebServiceException expected");
} catch (WebServiceException ex) {
}
bundle.start();
Assert.assertEquals("ACTIVE", Bundle.ACTIVE, bundle.getState());
QName serviceName = new QName("http://osgi.smoke.test.as.jboss.org", "EndpointService");
Service service = Service.create(getWsdl("/bundle-c"), serviceName);
Endpoint port = service.getPort(Endpoint.class);
Assert.assertEquals("Foo", port.echo("Foo"));
} finally {
bundle.uninstall();
}
}Example 66
| Project: pentaho-kettle-master File: PurRepositoryConnector.java View source code |
@Override public WebServiceException call() throws Exception { try { IUnifiedRepositoryJaxwsWebService repoWebService = null; if (log.isBasic()) { //$NON-NLS-1$ log.logBasic(BaseMessages.getString(PKG, "PurRepositoryConnector.CreateRepositoryWebService.Start")); } repoWebService = //$NON-NLS-1$ serviceManager.createService(username, decryptedPassword, IUnifiedRepositoryJaxwsWebService.class); if (log.isBasic()) { //$NON-NLS-1$ log.logBasic(BaseMessages.getString(PKG, "PurRepositoryConnector.CreateRepositoryWebService.End")); } if (log.isBasic()) { //$NON-NLS-1$ log.logBasic(BaseMessages.getString(PKG, "PurRepositoryConnector.CreateUnifiedRepositoryToWebServiceAdapter.Start")); } result.setUnifiedRepository(new UnifiedRepositoryToWebServiceAdapter(repoWebService)); } catch (WebServiceException wse) { return wse; } return null; }
Example 67
| Project: picketlink-bindings-master File: PicketLinkDispatch.java View source code |
@SuppressWarnings({ "unchecked", "rawtypes" })
public Source invoke(Source requestMessage) {
PLMessageContext msgContext = new PLMessageContext();
msgContext.put(MessageContext.MESSAGE_OUTBOUND_PROPERTY, Boolean.TRUE);
/** The JACC PolicyContext key for the current Subject */
String WEB_REQUEST_KEY = "javax.servlet.http.HttpServletRequest";
HttpServletRequest request = null;
try {
request = (HttpServletRequest) PolicyContext.getContext(WEB_REQUEST_KEY);
} catch (PolicyContextException e1) {
throw new RuntimeException(e1);
}
msgContext.put(MessageContext.SERVLET_REQUEST, request);
SOAPMessage soapMessage = null;
try {
soapMessage = SOAPUtil.create();
} catch (SOAPException e2) {
throw new RuntimeException(e2);
}
String userName = (String) parent.getRequestContext().get(BindingProvider.USERNAME_PROPERTY);
String passwd = (String) parent.getRequestContext().get(BindingProvider.PASSWORD_PROPERTY);
if (StringUtil.isNotNull(userName)) {
try {
if (useWSSE) {
SOAPElement security = create(userName, passwd);
soapMessage.getSOAPHeader().appendChild(security);
} else {
String authorization = Base64.encodeBytes((userName + ":" + passwd).getBytes());
soapMessage.getMimeHeaders().addHeader("Authorization", "Basic " + authorization);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
try {
SOAPUtil.addData(requestMessage, soapMessage);
} catch (SOAPException e1) {
throw new RuntimeException(e1);
}
msgContext.setMessage(soapMessage);
List<Handler> handlers = getBinding().getHandlerChain();
for (Handler handler : handlers) {
boolean result = handler.handleMessage(msgContext);
if (!result) {
throw new WebServiceException(ErrorCodes.PROCESSING_EXCEPTION + "Handler " + handler.getClass() + " returned false");
}
}
if (sslSocketFactory != null) {
HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
}
SOAPMessage response = null;
try {
SOAPConnectionFactory connectFactory = SOAPConnectionFactory.newInstance();
SOAPConnection connection = connectFactory.createConnection();
// Send it across the wire
URL url = new URL(endpoint);
response = connection.call(soapMessage, url);
} catch (Exception e) {
throw new RuntimeException(e);
}
try {
return new DOMSource(SOAPUtil.getSOAPData(response));
} catch (SOAPException e) {
throw new RuntimeException(e);
}
}Example 68
| Project: FireflowEngine20-master File: ProcessServiceProvider.java View source code |
// public Integer getProcessVersion() {
// return processVersion;
// }
// public void setProcessVersion(Integer processVersion) {
// this.processVersion = processVersion;
// }
public Source invoke(Source request) {
Expression correlation = callbackService.getCorrelation();
final QName responseRootElementQName = new QName(callbackService.getTargetNamespaceUri(), this.serviceBinding.getOperationName() + "Response");
//下é?¢æ˜¯æµ‹è¯•代ç ?
/*
try{
Transformer transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(
"{http://xml.apache.org/xslt}indent-amount", "2");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
// transformer.transform()方法 将 XML Source转�为 Result
transformer.transform(request, new StreamResult(
outputStream));
System.out.println( outputStream.toString());
}catch(Exception e){
e.printStackTrace();
}
*/
final Document requestDOM;
try {
Transformer transformer = transformerFactory.newTransformer();
DOMResult domResult = new DOMResult();
transformer.transform(request, domResult);
//从reuqestä¸èŽ·å¾—DOM对象
requestDOM = (Document) domResult.getNode();
} catch (TransformerException e) {
throw new WebServiceException("Can NOT transform request to DOM.", e);
}
final WorkflowSession session = WorkflowSessionFactory.createWorkflowSession(workflowRuntimeContext, FireWorkflowSystem.getInstance());
if (//调用æŸ?个ä¸é—´èŠ‚ç‚¹
!startNewProcess) {
if (correlation == null || StringUtils.isEmpty(correlation.getBody())) {
throw new WebServiceException("The correlation can NOT be empty; the callbackservice is " + callbackService.getName());
}
//1�通过serviceId和service version获得candidate activityInstance
WorkflowQuery<ActivityInstance> query = session.createWorkflowQuery(ActivityInstance.class);
List<ActivityInstance> candidates = query.add(Restrictions.eq(ActivityInstanceProperty.SERVICE_ID, callbackService.getId())).add(Restrictions.eq(ActivityInstanceProperty.SERVICE_VERSION, callbackService.getVersion())).add(Restrictions.eq(ActivityInstanceProperty.STATE, ActivityInstanceState.RUNNING)).list();
//2�匹�correlation
//correlation是一个bool表达�,如:processVars.var1==xpath(requestDom,'method1Request/id')
ProcessInstance theProcessInstance = null;
ActivityInstance theActivityInstance = null;
if (candidates != null && candidates.size() > 0) {
for (ActivityInstance activityInstance : candidates) {
ProcessInstance processInstance = activityInstance.getProcessInstance(session);
((WorkflowSessionLocalImpl) session).setCurrentProcessInstance(processInstance);
((WorkflowSessionLocalImpl) session).setCurrentActivityInstance(activityInstance);
Map<String, Object> varContext = ScriptEngineHelper.fulfillScriptContext(session, workflowRuntimeContext, processInstance, activityInstance);
varContext.put(ScriptContextVariableNames.INPUTS, requestDOM);
Object result = ScriptEngineHelper.evaluateExpression(workflowRuntimeContext, correlation, varContext);
if (result != null && (result instanceof Boolean)) {
if ((Boolean) result) {
theActivityInstance = activityInstance;
theProcessInstance = processInstance;
break;
}
}
}
}
//匹�上的activityInstance
final ActivityInstance theMatchedActivityInstance = theActivityInstance;
final ProcessInstance theMatchedProcessInstance = theProcessInstance;
if (theMatchedActivityInstance != null) {
//1�首先设置currentProcessInstance和CurrentActivityInstance
((WorkflowSessionLocalImpl) session).setCurrentActivityInstance(theMatchedActivityInstance);
((WorkflowSessionLocalImpl) session).setCurrentProcessInstance(theMatchedProcessInstance);
try {
this.transactionTemplate.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
//2�设置�程��
List<Assignment> inputAssignments_ = serviceBinding.getInputAssignments();
Map<String, Object> scriptContext = new HashMap<String, Object>();
scriptContext.put(ScriptContextVariableNames.INPUTS, requestDOM);
try {
ScriptEngineHelper.assignOutputToVariable(session, workflowRuntimeContext, theMatchedProcessInstance, theMatchedActivityInstance, inputAssignments_, scriptContext);
} catch (ScriptException e) {
throw new RuntimeException("Can NOT assign inputs to process instance varialbes,the callback service is " + callbackService.getName(), e);
}
//3�执行closeActivity的�作
ActivityInstanceManager actInstMgr = workflowRuntimeContext.getEngineModule(ActivityInstanceManager.class, theMatchedProcessInstance.getProcessType());
actInstMgr.onServiceCompleted(session, theMatchedActivityInstance);
return null;
}
});
} catch (TransactionException e) {
throw new WebServiceException(e);
}
//4�返回结果
try {
Map<String, Object> allTheVars = ScriptEngineHelper.fulfillScriptContext(session, workflowRuntimeContext, theMatchedProcessInstance, theMatchedActivityInstance);
List<Assignment> outputAssignments = serviceBinding.getOutputAssignments();
Document doc = DOMInitializer.generateDocument(callbackService.getXmlSchemaCollection(), responseRootElementQName);
allTheVars.put(ScriptContextVariableNames.OUTPUTS, doc);
Map<String, Object> tmp = ScriptEngineHelper.resolveAssignments(workflowRuntimeContext, outputAssignments, allTheVars);
Document resultDOM = (Document) tmp.get(ScriptContextVariableNames.OUTPUTS);
return new DOMSource(resultDOM);
} catch (ScriptException e) {
throw new WebServiceException("Can NOT assign process instance varialbes to output,the callback service is " + callbackService.getName(), e);
} catch (ParserConfigurationException e) {
throw new WebServiceException("Can NOT init output DOM,the callback service is " + callbackService.getName(), e);
}
} else {
throw new WebServiceException("Process instance NOT found for the conditions as follows,service id='" + callbackService.getId() + "' and service version='" + callbackService.getVersion() + "' and correlation='" + correlation.getBody() + "'");
}
} else //�动新的�程实例
{
//1�获得输入��,解�bizId
final Map<String, Object> processVars;
final String bizId;
try {
List<Assignment> inputAssignments_ = serviceBinding.getInputAssignments();
Map<String, Object> scriptContext = new HashMap<String, Object>();
scriptContext.put(ScriptContextVariableNames.INPUTS, requestDOM);
Map<String, Object> temp = ScriptEngineHelper.resolveAssignments(workflowRuntimeContext, inputAssignments_, scriptContext);
processVars = (Map<String, Object>) temp.get(ScriptContextVariableNames.PROCESS_VARIABLES);
Map<String, Object> varContext = new HashMap<String, Object>();
varContext.put(ScriptContextVariableNames.INPUTS, requestDOM);
Object result = ScriptEngineHelper.evaluateExpression(workflowRuntimeContext, correlation, varContext);
bizId = result == null ? null : result.toString();
} catch (ScriptException e) {
throw new WebServiceException("Can NOT assign inputs to process instance varialbes,the callback service is " + callbackService.getName(), e);
}
//2��动�程
ProcessInstance processInstance = null;
try {
processInstance = (ProcessInstance) transactionTemplate.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
WorkflowStatement stmt = session.createWorkflowStatement(processType);
ProcessInstance procInst = null;
try {
procInst = stmt.startProcess(processId, bizId, processVars);
} catch (InvalidModelException e1) {
throw new RuntimeException("Start process instance error! The callback service is " + callbackService.getName() + "; the process is " + processId, e1);
} catch (WorkflowProcessNotFoundException e1) {
throw new RuntimeException("Start process instance error! The callback service is " + callbackService.getName() + "; the process is " + processId, e1);
} catch (InvalidOperationException e1) {
throw new RuntimeException("Start process instance error! The callback service is " + callbackService.getName() + "; the process is " + processId, e1);
}
return procInst;
}
});
} catch (TransactionException e) {
throw new WebServiceException(e);
}
//3�返回结果
try {
Map<String, Object> allTheVars = ScriptEngineHelper.fulfillScriptContext(session, workflowRuntimeContext, processInstance, null);
List<Assignment> outputAssignments = serviceBinding.getOutputAssignments();
// 首先�始化返回的DOM对象
Document doc = DOMInitializer.generateDocument(callbackService.getXmlSchemaCollection(), responseRootElementQName);
allTheVars.put(ScriptContextVariableNames.OUTPUTS, doc);
Map<String, Object> tmp = ScriptEngineHelper.resolveAssignments(workflowRuntimeContext, outputAssignments, allTheVars);
Document resultDOM = (Document) tmp.get(ScriptContextVariableNames.OUTPUTS);
return new DOMSource(resultDOM);
} catch (ScriptException e) {
throw new WebServiceException("Can NOT assign process instance varialbes to output,the callback service is " + callbackService.getName(), e);
} catch (ParserConfigurationException e) {
throw new WebServiceException("Can NOT init output DOM,the callback service is " + callbackService.getName(), e);
}
}
}Example 69
| Project: rapidminer-5-master File: UpdateDialog.java View source code |
@Override
public void run() {
getProgressListener().setTotal(100);
getProgressListener().setCompleted(33);
try {
UpdateManager.resetService();
UpdateManager.getService();
} catch (WebServiceException e) {
SwingTools.showVerySimpleErrorMessage("failed_update_server_simple");
LogService.getRoot().log(Level.WARNING, "com.rapid_i.deployment.update.client.UpdateDialog.could_not_connect", e);
return;
} catch (Exception e) {
SwingTools.showSimpleErrorMessage("failed_update_server", e, UpdateManager.getBaseUrl());
LogService.getRoot().log(Level.WARNING, "com.rapid_i.deployment.update.client.UpdateDialog.could_not_connect", e);
return;
}
getProgressListener().setCompleted(100);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
UpdateDialog updateDialog = new UpdateDialog(preselectedExtensions);
if (selectUpdateTab) {
updateDialog.showUpdateTab();
}
updateDialog.setVisible(true);
}
});
}Example 70
| Project: spring-framework-2.5.x-master File: JaxWsPortClientInterceptor.java View source code |
/**
* Perform a JAX-WS service invocation based on the given method invocation.
* @param invocation the AOP method invocation
* @return the invocation result, if any
* @throws Throwable in case of invocation failure
* @see #getPortStub()
* @see #doInvoke(org.aopalliance.intercept.MethodInvocation, Object)
*/
protected Object doInvoke(MethodInvocation invocation) throws Throwable {
try {
return doInvoke(invocation, getPortStub());
} catch (SOAPFaultException ex) {
throw new JaxWsSoapFaultException(ex);
} catch (ProtocolException ex) {
throw new RemoteConnectFailureException("Could not connect to remote service [" + this.portQName + "]", ex);
} catch (WebServiceException ex) {
throw new RemoteAccessException("Could not access remote service at [" + this.portQName + "]", ex);
}
}Example 71
| Project: api-thetvdb-master File: TvdbParser.java View source code |
/**
* Get a list of the actors from the URL
*
* @param urlString
* @return
* @throws com.omertron.thetvdbapi.TvDbException
*/
public static List<Actor> getActors(String urlString) throws TvDbException {
List<Actor> results = new ArrayList<>();
Actor actor;
Document doc;
NodeList nlActor;
Node nActor;
Element eActor;
try {
doc = DOMHelper.getEventDocFromUrl(urlString);
if (doc == null) {
return results;
}
} catch (WebServiceException ex) {
LOG.trace(ERROR_GET_XML, ex);
return results;
}
nlActor = doc.getElementsByTagName("Actor");
for (int loop = 0; loop < nlActor.getLength(); loop++) {
nActor = nlActor.item(loop);
if (nActor.getNodeType() == Node.ELEMENT_NODE) {
eActor = (Element) nActor;
actor = new Actor();
actor.setId(DOMHelper.getValueFromElement(eActor, "id"));
String image = DOMHelper.getValueFromElement(eActor, "Image");
if (!image.isEmpty()) {
actor.setImage(URL_BANNER + image);
}
actor.setName(DOMHelper.getValueFromElement(eActor, "Name"));
actor.setRole(DOMHelper.getValueFromElement(eActor, "Role"));
actor.setSortOrder(DOMHelper.getValueFromElement(eActor, "SortOrder"));
results.add(actor);
}
}
Collections.sort(results);
return results;
}Example 72
| Project: BWS-Samples-master File: SampleBwsClient.java View source code |
/*******************************************************************************************************************
*
* Get the authenticator object for the authenticator name.
*
* @param authenticatorName
* A string containing the name of the desired authenticator.
* @return Returns the requested authenticator if it is found, null otherwise.
*
*******************************************************************************************************************
*/
public static Authenticator getAuthenticator(String authenticatorName) {
final String METHOD_NAME = "getAuthenticator()";
final String BWS_API_NAME = "_bwsUtil.getAuthenticators()";
logMessage("Entering %s", METHOD_NAME);
Authenticator returnValue = null;
GetAuthenticatorsRequest request = new GetAuthenticatorsRequest();
request.setMetadata(REQUEST_METADATA);
GetAuthenticatorsResponse response = null;
try {
logRequest(BWS_API_NAME);
response = _bwsUtil.getAuthenticators(request);
logResponse(BWS_API_NAME, response.getReturnStatus().getCode(), response.getMetadata());
} catch (WebServiceException e) {
logMessage("Exiting %s with exception \"%s\"", METHOD_NAME, e.getMessage());
throw e;
}
if (response.getReturnStatus().getCode().equals("SUCCESS")) {
if (response.getAuthenticators() != null && !response.getAuthenticators().isEmpty()) {
for (Authenticator authenticator : response.getAuthenticators()) {
if (authenticator.getName().equalsIgnoreCase(authenticatorName)) {
returnValue = authenticator;
break;
}
}
if (returnValue == null) {
logMessage("Could not find \"%s\" in GetAuthenticatorsResponse", authenticatorName);
}
} else {
logMessage("No authenticators in GetAuthenticatorsResponse");
}
} else {
logMessage("Error Message: \"%s\"", response.getReturnStatus().getMessage());
}
logMessage("Exiting %s with %s", METHOD_NAME, returnValue == null ? "\"null\"" : "Authenticator object (Name \"" + returnValue.getName() + "\")");
return returnValue;
}Example 73
| Project: cloudstack-master File: VmwareClient.java View source code |
/**
* This method returns a boolean value specifying whether the Task is
* succeeded or failed.
*
* @param task
* ManagedObjectReference representing the Task.
*
* @return boolean value representing the Task result.
* @throws InvalidCollectorVersionFaultMsg
* @throws RuntimeFaultFaultMsg
* @throws InvalidPropertyFaultMsg
*/
public boolean waitForTask(ManagedObjectReference task) throws InvalidPropertyFaultMsg, RuntimeFaultFaultMsg, InvalidCollectorVersionFaultMsg, Exception {
boolean retVal = false;
try {
// info has a property - state for state of the task
Object[] result = waitForValues(task, new String[] { "info.state", "info.error" }, new String[] { "state" }, new Object[][] { new Object[] { TaskInfoState.SUCCESS, TaskInfoState.ERROR } });
if (result[0].equals(TaskInfoState.SUCCESS)) {
retVal = true;
}
if (result[1] instanceof LocalizedMethodFault) {
throw new RuntimeException(((LocalizedMethodFault) result[1]).getLocalizedMessage());
}
} catch (WebServiceException we) {
s_logger.debug("Cancelling vCenter task because task failed with " + we.getLocalizedMessage());
getService().cancelTask(task);
throw new RuntimeException("vCenter task failed due to " + we.getLocalizedMessage());
}
return retVal;
}Example 74
| Project: eclipselink.runtime-master File: ProviderHelper.java View source code |
protected InputStream initXRServiceStream(ClassLoader parentClassLoader, @SuppressWarnings("unused") ServletContext sc) {
InputStream xrServiceStream = null;
for (String searchPath : META_INF_PATHS) {
String path = searchPath + DBWS_SERVICE_XML;
xrServiceStream = parentClassLoader.getResourceAsStream(path);
if (xrServiceStream != null) {
break;
}
}
if (xrServiceStream == null) {
throw new WebServiceException(DBWSException.couldNotLocateFile(DBWS_SERVICE_XML));
}
return xrServiceStream;
}Example 75
| Project: tesb-rt-se-master File: CallContext.java View source code |
public <T extends Source> Dispatch<T> createCallbackDispatch(final Class<T> sourceClass, final Service.Mode mode, final QName operation, final String soapAction, final URL wsdlLocationURL, final String policyAlias) {
final URL wsdlURL;
final CallbackInfo callbackInfo;
if (wsdlLocationURL == null || wsdlLocationURL.equals(this.wsdlLocationURL)) {
wsdlURL = integrateCallbackSenderPolicyAlias(this.wsdlLocationURL, policyAlias);
callbackInfo = getCallbackInfo();
} else {
wsdlURL = integrateCallbackSenderPolicyAlias(wsdlLocationURL, policyAlias);
callbackInfo = new CallbackInfo(wsdlLocationURL);
}
final QName callbackPortTypeName;
final QName callbackServiceName;
final QName callbackPortName;
if (callbackInfo != null) {
callbackPortTypeName = validValue(callbackInfo.getCallbackPortTypeName(), portTypeName.getNamespaceURI(), portTypeName.getLocalPart(), "Consumer");
callbackServiceName = validValue(callbackInfo.getCallbackServiceName(), callbackPortTypeName.getNamespaceURI(), callbackPortTypeName.getLocalPart(), "Service");
callbackPortName = validValue(callbackInfo.getCallbackPortName(), callbackServiceName.getNamespaceURI(), callbackPortTypeName.getLocalPart(), "Port");
} else {
callbackPortTypeName = new QName(portTypeName.getNamespaceURI(), portTypeName.getLocalPart() + "Consumer");
callbackServiceName = new QName(callbackPortTypeName.getNamespaceURI(), callbackPortTypeName.getLocalPart() + "Service");
callbackPortName = new QName(callbackPortTypeName.getNamespaceURI(), callbackPortTypeName.getLocalPart() + "Port");
}
Service service = null;
if (wsdlURL != null) {
try {
service = Service.create(wsdlURL, callbackServiceName);
} catch (WebServiceException e) {
if (LOGGER.isLoggable(Level.INFO)) {
LOGGER.info("Service " + callbackServiceName + " is not defined in WSDL (old-style callback definition");
LOGGER.info("Proceeding without callback service model");
if (LOGGER.isLoggable(Level.FINER)) {
LOGGER.log(Level.FINER, "Exception caught: ", e);
}
}
}
}
final Dispatch<T> dispatch;
if (service != null) {
if (!service.getPorts().hasNext()) {
service.addPort(callbackPortName, bindingId, replyToAddress);
}
dispatch = service.createDispatch(callbackPortName, sourceClass, mode);
dispatch.getRequestContext().put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, replyToAddress);
} else {
service = Service.create(callbackServiceName);
service.addPort(callbackPortName, bindingId, replyToAddress);
dispatch = service.createDispatch(callbackPortName, sourceClass, mode);
}
setupDispatch(dispatch);
final Map<String, Object> requestContext = dispatch.getRequestContext();
requestContext.put(RequestCallbackFeature.CALLCONTEXT_PROPERTY_NAME, this);
// The current request context is still not thread local, but subsequent
// calls to dispatch.getRequestContext() return a thread local one.
requestContext.put(JaxWsClientProxy.THREAD_LOCAL_REQUEST_CONTEXT, Boolean.TRUE);
if (operation != null) {
requestContext.put(MessageContext.WSDL_OPERATION, operation);
requestContext.put(BindingProvider.SOAPACTION_USE_PROPERTY, Boolean.TRUE);
final String action = soapAction == null || soapAction.length() == 0 ? operation.getLocalPart() : soapAction;
requestContext.put(BindingProvider.SOAPACTION_URI_PROPERTY, action);
} else if (soapAction != null && soapAction.length() > 0) {
requestContext.put(BindingProvider.SOAPACTION_USE_PROPERTY, Boolean.TRUE);
requestContext.put(BindingProvider.SOAPACTION_URI_PROPERTY, soapAction);
}
return dispatch;
}Example 76
| Project: tuscany-sca-2.x-master File: JAXWSBindingInvoker.java View source code |
public Message invoke(Message msg) {
try {
SOAPMessage resp = invokeTarget(msg);
SOAPBody body = resp.getSOAPBody();
if (body != null) {
SOAPFault fault = body.getFault();
if (fault != null) {
// setFault(msg, fault);
} else {
// The 1st child element
msg.setBody(body.getChildElements().next());
}
}
} catch (SOAPFaultException e) {
setFault(msg, e);
} catch (WebServiceException e) {
msg.setFaultBody(e);
} catch (SOAPException e) {
msg.setFaultBody(e);
} catch (Throwable e) {
msg.setFaultBody(e);
}
return msg;
}Example 77
| Project: openolat-master File: ViteroManager.java View source code |
public List<ViteroBooking> getBookingByDate(Date start, Date end) throws VmsNotAvailableException {
try {
Booking bookingWs = getBookingWebService();
GetBookingListByDateRequest dateRequest = new GetBookingListByDateRequest();
dateRequest.setStart(format(start));
dateRequest.setEnd(format(end));
dateRequest.setTimezone(viteroModule.getTimeZoneId());
dateRequest.setCustomerid(viteroModule.getCustomerId());
Bookinglist bookingList = bookingWs.getBookingListByDate(dateRequest);
List<Booking_Type> bookings = bookingList.getBooking();
return convert(bookings);
} catch (SOAPFaultException f) {
ErrorCode code = handleAxisFault(f);
switch(code) {
default:
logAxisError("Cannot get the list of bookings by date.", f);
}
return Collections.emptyList();
} catch (WebServiceException e) {
if (e.getCause() instanceof ConnectException) {
throw new VmsNotAvailableException();
}
return Collections.emptyList();
}
}Example 78
| Project: rapidminer-studio-master File: ConfigurableDialog.java View source code |
@Override
public void run() {
try {
remoteModel.checkVersion();
if (!remoteModel.wasVersionCheckDone()) {
collapseRemoteTaskPane(source);
try {
remoteModel.resetConfigurables();
remoteModel.resetConnection();
} catch (RepositoryException e1) {
}
}
} catch (WebServiceException e) {
collapseRemoteTaskPane(source);
try {
remoteModel.resetConfigurables();
remoteModel.resetConnection();
} catch (RepositoryException e1) {
}
}
}Example 79
| Project: picketlink-master File: PicketLinkSTSUnitTestCase.java View source code |
/**
* <p>
* This test case first generates a SAMLV1.1 assertion and then sends a WS-Trust cancel message to the STS to cancel
* the
* assertion. A canceled assertion cannot be renewed or considered valid anymore.
* </p>
*
* @throws Exception if an error occurs while running the test.
*/
@Test
public void testInvokeSAML11Cancel() throws Exception {
// create a simple token request.
RequestSecurityToken request = this.createRequest("testcontext", WSTrustConstants.ISSUE_REQUEST, SAMLUtil.SAML11_TOKEN_TYPE, null);
Source requestMessage = this.createSourceFromRequest(request);
// invoke the token service.
Source responseMessage = this.tokenService.invoke(requestMessage);
WSTrustParser parser = new WSTrustParser();
BaseRequestSecurityTokenResponse baseResponse = (BaseRequestSecurityTokenResponse) parser.parse(DocumentUtil.getSourceAsStream(responseMessage));
// validate the response and get the SAML assertion from the request.
this.validateSAML11AssertionResponse(baseResponse, "testcontext", "jduke", SAMLUtil.SAML11_BEARER_URI);
RequestSecurityTokenResponseCollection collection = (RequestSecurityTokenResponseCollection) baseResponse;
Element assertion = (Element) collection.getRequestSecurityTokenResponses().get(0).getRequestedSecurityToken().getAny().get(0);
// now construct a WS-Trust cancel request with the generated assertion.
request = this.createRequest("cancelcontext", WSTrustConstants.CANCEL_REQUEST, null, null);
CancelTargetType cancelTarget = new CancelTargetType();
cancelTarget.add(assertion);
request.setCancelTarget(cancelTarget);
// invoke the token service.
responseMessage = this.tokenService.invoke(this.createSourceFromRequest(request));
baseResponse = (BaseRequestSecurityTokenResponse) parser.parse(DocumentUtil.getSourceAsStream(responseMessage));
// validate the response contents.
assertNotNull("Unexpected null response", baseResponse);
assertTrue("Unexpected response type", baseResponse instanceof RequestSecurityTokenResponseCollection);
collection = (RequestSecurityTokenResponseCollection) baseResponse;
assertEquals("Unexpected number of responses", 1, collection.getRequestSecurityTokenResponses().size());
RequestSecurityTokenResponse response = collection.getRequestSecurityTokenResponses().get(0);
assertEquals("Unexpected response context", "cancelcontext", response.getContext());
assertNotNull("Cancel response should contain a RequestedTokenCancelled element", response.getRequestedTokenCancelled());
// try to validate the canceled assertion.
request = this.createRequest("validatecontext", WSTrustConstants.VALIDATE_REQUEST, null, null);
ValidateTargetType validateTarget = new ValidateTargetType();
validateTarget.add(assertion);
request.setValidateTarget(validateTarget);
// the response should contain a status indicating that the token is not valid.
responseMessage = this.tokenService.invoke(this.createSourceFromRequest(request));
collection = (RequestSecurityTokenResponseCollection) parser.parse(DocumentUtil.getSourceAsStream(responseMessage));
assertEquals("Unexpected number of responses", 1, collection.getRequestSecurityTokenResponses().size());
response = collection.getRequestSecurityTokenResponses().get(0);
assertEquals("Unexpected response context", "validatecontext", response.getContext());
assertEquals("Unexpected token type", WSTrustConstants.STATUS_TYPE, response.getTokenType().toString());
StatusType status = response.getStatus();
assertNotNull("Unexpected null status", status);
assertEquals("Unexpected status code", WSTrustConstants.STATUS_CODE_INVALID, status.getCode());
assertEquals("Unexpected status reason", "Validation failure: assertion with id " + assertion.getAttribute("AssertionID") + " has been canceled", status.getReason());
// now try to renew the canceled assertion.
request = this.createRequest("renewcontext", WSTrustConstants.RENEW_REQUEST, null, null);
RenewTargetType renewTarget = new RenewTargetType();
renewTarget.add(assertion);
request.setRenewTarget(renewTarget);
// we should receive an exception when renewing the token.
try {
this.tokenService.invoke(this.createSourceFromRequest(request));
fail("Renewing a canceled token should result in an exception being thrown");
} catch (WebServiceException we) {
Throwable t = we.getCause();
assertTrue("Unexpected cause type", t instanceof WSTrustException);
String msg = t.getMessage();
if (msg.contains("has been canceled and cannot be renewed") == false)
throw new RuntimeException("Unexpected exception message");
}
}Example 80
| Project: SOAPClient-master File: PageCacheServiceClientImpl.java View source code |
@Override
public void clear() {
try {
stub.clear();
} catch (RemoteException e) {
throw new WebServiceException(e);
}
}Example 81
| Project: cats-master File: PowerServiceEndPointUnitTest.java View source code |
/**
* Test power service endpoint contructor1.
*
* @throws Exception the exception
*/
@Test(expectedExceptions = WebServiceException.class)
public void testPowerServiceEndpointContructor1() throws Exception {
// This is an invalid wsdl url, hence the constructor throws exception
pwrServiceEndPoint = new PowerServiceEndpoint(new URL("http://192.168.120.102:8080/power-service/PowerService?wsdl"));
}Example 82
| Project: rce-master File: JettyServiceImplTest.java View source code |
/**
* Test method for
* 'de.rcenvironment.rce.communication.jetty.internal.JettyServiceImpl.undeployJetty()' for
* success.
*/
@Test
public void testUndeployWebServiceForSuccess() {
jettyService.undeployWebService(ADDRESS);
WebCall testService = (WebCall) jettyService.createWebServiceClient(WebCall.class, ADDRESS);
try {
testService.call(REQUEST);
fail();
} catch (WebServiceException e) {
assertNotNull(e);
}
}