I'm writing an webservice using Jersey, but I facing an exception during response request of client.
I got exception below: (I explain and attached my code after exception).
jan 19, 2017 7:55:31 PM org.glassfish.jersey.server.ServerRuntime$Responder writeResponse
GRAVE: An I/O error has occurred while writing a response message entity to the container output stream.
org.glassfish.jersey.server.internal.process.MappableException: org.apache.catalina.connector.ClientAbortException: java.io.IOException: Uma conexão estabelecida foi anulada pelo software no computador host
at org.glassfish.jersey.server.internal.MappableExceptionWrapperInterceptor.aroundWriteTo(MappableExceptionWrapperInterceptor.java:92)
at org.glassfish.jersey.message.internal.WriterInterceptorExecutor.proceed(WriterInterceptorExecutor.java:162)
at org.glassfish.jersey.message.internal.MessageBodyFactory.writeTo(MessageBodyFactory.java:1130)
at org.glassfish.jersey.server.ServerRuntime$Responder.writeResponse(ServerRuntime.java:711)
at org.glassfish.jersey.server.ServerRuntime$Responder.processResponse(ServerRuntime.java:444)
at org.glassfish.jersey.server.ServerRuntime$Responder.process(ServerRuntime.java:434)
at org.glassfish.jersey.server.ServerRuntime$2.run(ServerRuntime.java:329)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:271)
at org.glassfish.jersey.internal.Errors$1.call(Errors.java:267)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:267)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:317)
at org.glassfish.jersey.server.ServerRuntime.process(ServerRuntime.java:305)
at org.glassfish.jersey.server.ApplicationHandler.handle(ApplicationHandler.java:1154)
at org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:473)
at org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:388)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:341)
at org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java:228)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:108)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:620)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:349)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:784)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:802)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1455)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
I'm compose an Response (javax.ws.rs.core.Response) with an list on entity response param, this list has object, arrays is big, because of it, I'm trying to reduce its size using "StreamingOutput", but without success, follow my code:
Composite of response
#GET
#Path("/request/getSales")
public Response getSales(#QueryParam(value = "loginKey") String loginKey,
#QueryParam(value = "saleID") String saleID, #QueryParam(value = "date") String date) {
Response response = null;
try {
// if profile has logged on server, it's necessary to get his state.
LoggedProfile loggedProfile = ServerGlobal.getInstance().getLoggedProfile(loginKey);
if(loggedProfile != null) {
List<Sale> sales = null;
if("".equals(saleID) && "".equals(date)) {
log.debug("saleID && date is empty.");
// No sale are saved, it's necessary to check if server saved some sale for current Profile
sales = SaleDao.getInstance().getAllSalesByProfileID(loggedProfile.getProfileID());
} else if(!"".equals(date)) {
log.debug("date is not empty.");
// Search sale for one period
sales = SaleDao.getInstance().getSalesByPeriod(
new Timestamp(Long.valueOf(date)),
!("".equals(saleID)) ? Integer.parseInt(saleID) : null);
}
// Big data compress, low memory and high performance to process json.
StreamingOutput stream = Parser.parserSalesToStreaming(sales);
response = **Response.ok().status(ResponseStatus.RESPONSE_GET_SALES_OK).entity(stream).build();**
My StreamingOutput
public static StreamingOutput parserSalesToStreaming(List<Sale> sales) {
StreamingOutput stream = new StreamingOutput() {
#Override
public void write(OutputStream arg0) throws IOException, WebApplicationException {
JsonFactory jsonFactory = new JsonFactory();
JsonGenerator generator = jsonFactory.createGenerator(arg0, JsonEncoding.UTF8);
ObjectMapper mapper = new ObjectMapper();
generator.writeStartArray();
for(Sale sale : sales) {
generator.writeObject(mapper.writeValueAsString(sale));
}
generator.writeEndArray();
generator.close();
}
};
return stream;
}
I'm starting work with Jersey, so I'm suspect that root cause is size on "Entity", because it's just happening with an big list and this case. Could somebody help me, please?
I'm using Tomcat, Jersey version 2.23.1
Thanks in advance
Related
I'm using external service, based on REST calls, and I want to track the time that took the service to respond to my requests. My code is written with C# (core v2.2)
I planning to count times for all the HTTP requests (with Stopwatch) and keep this information in a List<long>. Every 60 seconds I will write the tracked information from the list to Google Custom Metrics.
In the end, I expect to see the AVERAGE time of execution in a graph.
This is my code so far:
public class CustomMetricsWritter
{
public CustomMetricsWritter(string projectId)
{
this.Client = MetricServiceClient.Create();
this.ProjectId = projectId;
}
private MetricServiceClient Client { get; set; }
public string ProjectId { get; private set; }
public object CreateMetric(string metricType, string title, string description, string unit)
{
// Prepare custom metric descriptor.
MetricDescriptor metricDescriptor = new MetricDescriptor();
metricDescriptor.DisplayName = title;
metricDescriptor.Description = description;
metricDescriptor.MetricKind = MetricKind.Gauge;
metricDescriptor.ValueType = MetricDescriptor.Types.ValueType.Double;
metricDescriptor.Type = metricType;
metricDescriptor.Unit = unit;
CreateMetricDescriptorRequest request = new CreateMetricDescriptorRequest
{
ProjectName = new ProjectName(this.ProjectId),
};
request.MetricDescriptor = metricDescriptor;
// Make the request.
return Client.CreateMetricDescriptor(request);
}
public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public async Task WriteTimeSeriesDataAsync(string metricDescriptor, TypedValue[] points, string machineName)
{
// Initialize request argument(s).
ProjectName name = new ProjectName(this.ProjectId);
// Prepare a data point.
Timestamp timeStamp = new Timestamp();
timeStamp.Seconds = (long)(DateTime.UtcNow - UnixEpoch).TotalSeconds;
TimeInterval interval = new TimeInterval();
interval.EndTime = timeStamp;
// Prepare monitored resource.
MonitoredResource resource = new MonitoredResource();
resource.Type = "global";
resource.Labels.Add("project_id", this.ProjectId);
// Add newly created time series to list of time series to be written.
List<TimeSeries> timeSeries = new List<TimeSeries>(points.Length);
// Prepare custom metric.
Metric metric = new Metric();
metric.Type = metricDescriptor;
metric.Labels.Add("machine", machineName);
// Create a new time series using inputs.
TimeSeries timeSeriesData = new TimeSeries();
timeSeriesData.Metric = metric;
timeSeriesData.Resource = resource;
foreach (var point in points)
{
Point dataPoint = new Point();
dataPoint.Value = point;
dataPoint.Interval = interval;
timeSeriesData.Points.Add(dataPoint);
}
timeSeries.Add(timeSeriesData);
// Write time series data.
await this.Client.CreateTimeSeriesAsync(name, timeSeries).ConfigureAwait(false);
}
}
I running this class with this code (create the metric and then fill it with dummy values):
try
{
CustomMetricsWritter customMetricsWriter = new CustomMetricsWritter(Consts.GOOGLE_CLOUD_PROJECT);
string metric = "custom.googleapis.com/web/latency";
customMetricsWriter.CreateMetric(metric, "Execution Latency", "Calling REST service (MS).", "{INT64}");
// Exception thrown in the next line ----->
await customMetricsWriter.WriteTimeSeriesDataAsync(
metric,
new TypedValue[] {
new TypedValue(){ Int64Value = 150},
new TypedValue(){ Int64Value = 250},
new TypedValue(){ Int64Value = 350},
},
"my-machine-type");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
throw;
}
I getting back this thrown exception:
Grpc.Core.RpcException: Status(StatusCode=InvalidArgument, Detail="One or more TimeSeries could not be written: Field timeSeries[0].points had an invalid value: Only one point can be written per TimeSeries per request.: timeSeries[0]")
at Google.Api.Gax.Grpc.ApiCallRetryExtensions.<>c__DisplayClass0_0`2.<<WithRetry>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at ***.CustomMetricsWritter.WriteTimeSeriesDataAsync(String metricDescriptor, TypedValue[] points, String machineName) in ***\GoogleCloud\CustomMetricsWritter.cs:line 131
at Test.Program.MainAsync() in ***\Test\Program.cs:line 156
What I'm doing wrong?
I'm not a C# expert, but there are examples here:
https://github.com/GoogleCloudPlatform/dotnet-docs-samples/blob/master/monitoring/api/QuickStart/QuickStart.cs
I am following the Corda tutorial to build Corda app. Instead of building it in Kotlin, I built it in Java.
I followed the steps provided in the doc and below is my CarIssueInitiator class.
package com.template.flows;
import co.paralleluniverse.fibers.Suspendable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.template.contracts.CarContract;
import com.template.states.CarState;
import net.corda.core.contracts.Command;
import net.corda.core.contracts.UniqueIdentifier;
import net.corda.core.flows.*;
import net.corda.core.identity.Party;
import net.corda.core.transactions.SignedTransaction;
import net.corda.core.transactions.TransactionBuilder;
import net.corda.core.utilities.ProgressTracker;
import net.corda.core.utilities.ProgressTracker.Step;
import java.util.List;
import java.util.stream.Collectors;
// ******************
// * Initiator flow *
// ******************
#InitiatingFlow
#StartableByRPC
public class CarIssueInitiator extends FlowLogic<SignedTransaction> {
private final Party owningBank;
private final Party holdingDealer;
private final Party manufacturer;
private final String vin;
private final String licensePlateNumber;
private final String make;
private final String model;
private final String dealershipLocation;
private final Step GENERATING_TRANSACTION = new Step("Generating transaction based on new IOU.");
private final Step VERIFYING_TRANSACTION = new Step("Verifying contract constraints.");
private final Step SIGNING_TRANSACTION = new Step("Signing transaction with our private key.");
private final Step GATHERING_SIGS = new Step("Gathering the counterparty's signature.") {
#Override
public ProgressTracker childProgressTracker() {
return CollectSignaturesFlow.Companion.tracker();
}
};
private final Step FINALISING_TRANSACTION = new Step("Obtaining notary signature and recording transaction.") {
#Override
public ProgressTracker childProgressTracker() {
return FinalityFlow.Companion.tracker();
}
};
private final ProgressTracker progressTracker = new ProgressTracker(
GENERATING_TRANSACTION,
VERIFYING_TRANSACTION,
SIGNING_TRANSACTION,
GATHERING_SIGS,
FINALISING_TRANSACTION
);
public CarIssueInitiator(Party owningBank,
Party holdingDealer,
Party manufacturer,
String vin,
String licensePlateNumber,
String make,
String model,
String dealershipLocation){
this.owningBank = owningBank;
this.holdingDealer = holdingDealer;
this.manufacturer = manufacturer;
this.vin = vin;
this.licensePlateNumber = licensePlateNumber;
this.make = make;
this.model = model;
this.dealershipLocation = dealershipLocation;
}
#Override
public ProgressTracker getProgressTracker() {
return progressTracker;
}
#Suspendable
#Override
public SignedTransaction call() throws FlowException {
// Initiator flow logic goes here.
final Party notary = getServiceHub().getNetworkMapCache().getNotaryIdentities().get(0);
// Stage 1.
progressTracker.setCurrentStep(GENERATING_TRANSACTION);
// Generate an unsigned transaction.
Party me = getOurIdentity();
CarState carState = new CarState(this.owningBank,
this.holdingDealer,
this.manufacturer,
this.vin,
this.licensePlateNumber,
this.make,
this.model,
this.dealershipLocation,
new UniqueIdentifier());
final Command<CarContract.Commands.Issue> txCommand = new Command<CarContract.Commands.Issue>(new CarContract.Commands.Issue(),
ImmutableList.of(carState.getOwningBank().getOwningKey(), carState.getHoldingDealer().getOwningKey(), carState.getManufacturer().getOwningKey()));
final TransactionBuilder txBuilder = new TransactionBuilder(notary)
.addOutputState(carState, CarContract.ID)
.addCommand(txCommand);
// Stage 2.
progressTracker.setCurrentStep(VERIFYING_TRANSACTION);
// Verify that the transaction is valid.
txBuilder.verify(getServiceHub());
//Stage 3
progressTracker.setCurrentStep(SIGNING_TRANSACTION);
// Sign the transaction.
final SignedTransaction partSignedTx = getServiceHub().signInitialTransaction(txBuilder);
// Stage 4.
progressTracker.setCurrentStep(GATHERING_SIGS);
// Send the state to the counterparty, and receive it back with their signature.
List<FlowSession> sessions = carState.getParticipants().stream().map(a -> initiateFlow((Destination) a)).collect(Collectors.toList());
//FlowSession session = initiateFlow(me);
final SignedTransaction fullySignedTx = subFlow(
new CollectSignaturesFlow(partSignedTx, sessions, ImmutableList.of(me.getOwningKey()), CollectSignaturesFlow.Companion.tracker()));
// Stage 5.
progressTracker.setCurrentStep(FINALISING_TRANSACTION);
return subFlow(new FinalityFlow(fullySignedTx, sessions));
}
}
I deployed the CordApp and ran the flow. But I ended up with below error
java.lang.IllegalArgumentException: The Initiator of CollectSignaturesFlow must pass in exactly the sessions required to sign the transaction.
at net.corda.core.flows.CollectSignaturesFlow.call(CollectSignaturesFlow.kt:164) ~[corda-core-4.3.jar:?]
at net.corda.core.flows.CollectSignaturesFlow.call(CollectSignaturesFlow.kt:67) ~[corda-core-4.3.jar:?]
at net.corda.node.services.statemachine.FlowStateMachineImpl.subFlow(FlowStateMachineImpl.kt:330) ~[corda-node-4.3.jar:?]
at net.corda.core.flows.FlowLogic.subFlow(FlowLogic.kt:326) ~[corda-core-4.3.jar:?]
at com.template.flows.CarIssueInitiator.call(CarIssueInitiator.java:129) ~[?:?]
at com.template.flows.CarIssueInitiator.call(CarIssueInitiator.java:23) ~[?:?]
at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:270) ~[corda-node-4.3.jar:?]
at net.corda.node.services.statemachine.FlowStateMachineImpl.run(FlowStateMachineImpl.kt:46) ~[corda-node-4.3.jar:?]
at co.paralleluniverse.fibers.Fiber.run1(Fiber.java:1092) ~[quasar-core-0.7.10-jdk8.jar:0.7.10]
at co.paralleluniverse.fibers.Fiber.exec(Fiber.java:788) ~[quasar-core-0.7.10-jdk8.jar:0.7.10]
at co.paralleluniverse.fibers.RunnableFiberTask.doExec(RunnableFiberTask.java:100) ~[quasar-core-0.7.10-jdk8.jar:0.7.10]
at co.paralleluniverse.fibers.RunnableFiberTask.run(RunnableFiberTask.java:91) ~[quasar-core-0.7.10-jdk8.jar:0.7.10]
at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source) ~[?:1.8.0_192]
at java.util.concurrent.FutureTask.run(Unknown Source) ~[?:1.8.0_192]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(Unknown Source) ~[?:1.8.0_192]
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown Source) ~[?:1.8.0_192]
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source) ~[?:1.8.0_192]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) ~[?:1.8.0_192]
at net.corda.node.utilities.AffinityExecutor$ServiceAffinityExecutor$1$thread$1.run(AffinityExecutor.kt:63) ~[corda-node-4.3.jar:?]
I am not getting what is wrong with the code. Request you to please help me out with this.
UPDATE: With below updated code, it works for me.
//Stage 3
progressTracker.setCurrentStep(SIGNING_TRANSACTION);
// Sign the transaction.
final PublicKey ourSigningKey = getServiceHub().getMyInfo().getLegalIdentities().get(0).getOwningKey();
final SignedTransaction partSignedTx = getServiceHub().signInitialTransaction(txBuilder, ourSigningKey);
// Stage 4.
progressTracker.setCurrentStep(GATHERING_SIGS);
// Send the state to the counterparty, and receive it back with their signature.
FlowSession HoldingDealerPartyFlow = initiateFlow(carState.getHoldingDealer());
FlowSession ManufacturerPartyFlow = initiateFlow(carState.getManufacturer());
final SignedTransaction fullySignedTx = subFlow(new CollectSignaturesFlow(
partSignedTx,
ImmutableSet.of(HoldingDealerPartyFlow, ManufacturerPartyFlow),
ImmutableList.of(ourSigningKey))
);
// Stage 5.
progressTracker.setCurrentStep(FINALISING_TRANSACTION);
return subFlow(new FinalityFlow(fullySignedTx, ImmutableSet.of(HoldingDealerPartyFlow, ManufacturerPartyFlow)));
The list of signers in carState.getParticipants()(see Code A) does not match with the list of signers in ImmutableList of CollectSignaturesFlow (see Code B).
Code A:
List<FlowSession> sessions = carState.getParticipants().stream().map(a -> initiateFlow((Destination) a)).collect(Collectors.toList());
Code B: final SignedTransaction fullySignedTx = subFlow(
new CollectSignaturesFlow(partSignedTx, sessions, ImmutableList.of(me.getOwningKey()), CollectSignaturesFlow.Companion.tracker()));
In the ImmutableList you have to add carState.getOwningBank().getOwningKey(), carState.getHoldingDealer().getOwningKey(), carState.getManufacturer().getOwningKey()
EDITED
Try the following code from "Stage 3" onwards
//Stage 3
progressTracker.setCurrentStep(SIGNING_TRANSACTION);
// Sign the transaction.
//final SignedTransaction partSignedTx = getServiceHub().signInitialTransaction(txBuilder);
val ourSigningKey = serviceHub.myInfo.legalIdentities.first().owningKey
val partSignedTx = serviceHub.signInitialTransaction(tx, ourSigningKey)
// Stage 4.
progressTracker.setCurrentStep(GATHERING_SIGS);
// Send the state to the counterparty, and receive it back with their signature.
//List<FlowSession> sessions = carState.getParticipants().stream().map(a -> initiateFlow((Destination) a)).collect(Collectors.toList());
//FlowSession session = initiateFlow(me);
//final SignedTransaction fullySignedTx = subFlow(
// new CollectSignaturesFlow(partSignedTx, sessions, ImmutableList.of(me.getOwningKey()), CollectSignaturesFlow.Companion.tracker()));
val HoldingDealerPartyFlow = initiateFlow(carState.getHoldingDealer())
val ManufacturerPartyFlow = initiateFlow(carState.getManufacturer())
val fullySignedTx = subFlow(CollectSignaturesFlow(
partSignedTx,
setOf(HoldingDealerPartyFlow ManufacturerPartyFlow),
listOf(ourSigningKey))
)
// Stage 5.
progressTracker.setCurrentStep(FINALISING_TRANSACTION);
//return subFlow(new FinalityFlow(fullySignedTx, sessions));
subFlow(FinalityFlow(fullySignedTx, setOf(HoldingDealerPartyFlow ManufacturerPartyFlow)))
return fullySignedTx.tx.outRef<State>(0)
You should only call initiateFlow() for all participants except for yourself, so your code could be like (the grammar might be wrong, but shows the point):
List<FlowSession> sessions = (carState.getParticipants() - me).stream().map(a -> initiateFlow((Destination) a)).collect(Collectors.toList());
I am using Sabre SOAP Api in C#. I got the response from session creation successfully, I added wsdl Service Reference http://webservices.sabre.com/wsdl/tpfc/OTA_AirAvailLLS2.3.0RQ.wsdl to my test project and pass required values to parameters in the request as given in the documentation https://developer.sabre.com/docs/read/soap_apis/air/search/Air_Availability.
this is my code to consume SOAP API
public OTA_AirAvailRS Method(string securitytoken, string convid, string ipcc)
{
try
{
DateTime dt = DateTime.UtcNow;
string tstamp = dt.ToString("s") + "Z";
//Create the message header. Provide the value for the conversation ID, the action code of the Web
//service being called, and the value for wsse:BinarySecurityToken that was returned with
//the SessionCreateRS message.
//This sample calls the OTA_AirAvailLLSRQ Service, and the action code that corresponds to
//this service is OTA_AirAvailLLSRQ.
MessageHeader msgHeader = new MessageHeader();
msgHeader.ConversationId = convid; // Put ConversationId in req header
From from = new From();
PartyId fromPartyId = new PartyId();
PartyId[] fromPartyIdArr = new PartyId[1];
fromPartyId.Value = "WebServiceClient";
fromPartyIdArr[0] = fromPartyId;
from.PartyId = fromPartyIdArr;
msgHeader.From = from;
To to = new To();
PartyId toPartyId = new PartyId();
PartyId[] toPartyIdArr = new PartyId[1];
toPartyId.Value = "WebServiceSupplier";
toPartyIdArr[0] = toPartyId;
to.PartyId = toPartyIdArr;
msgHeader.To = to;
msgHeader.CPAId = ipcc;
msgHeader.Action = "OTA_AirAvailLLSRQ";
Service service = new Service();
service.Value = "AirAvail";
msgHeader.Service = service;
MessageData msgData = new MessageData();
msgData.MessageId = "mid:20001209-133003-2333#clientofsabre.com1";
msgData.Timestamp = tstamp;
msgHeader.MessageData = msgData;
Security1 security = new Security1();
security.BinarySecurityToken = securitytoken; // Put BinarySecurityToken in req header
//Create the request object req and the value for the IPCC in the payload of the request.
OTA_AirAvailRQOriginDestinationInformationFlightSegment seg = new OTA_AirAvailRQOriginDestinationInformationFlightSegment()
{
ArrivalDateTime = "12-21T19:00",
DepartureDateTime = "12-21T18:00",
DestinationLocation = new OTA_AirAvailRQOriginDestinationInformationFlightSegmentDestinationLocation() { LocationCode = "DFW" },
OriginLocation = new OTA_AirAvailRQOriginDestinationInformationFlightSegmentOriginLocation() { LocationCode = "HNL" }
};
OTA_AirAvailRQ req = new OTA_AirAvailRQ();
req.OriginDestinationInformation = new OTA_AirAvailRQOriginDestinationInformation() { FlightSegment = seg };
// req.TimeStamp = tstamp;
// req.OptionalQualifiers.FlightQualifiers.
req.Version="2.3.0";
OTA_AirAvailPortTypeClient c = new OTA_AirAvailPortTypeClient();
OTA_AirAvailRS resp = c.OTA_AirAvailRQ(ref msgHeader, ref security, req);
return resp;
}
catch (Exception e)
{
Console.WriteLine("The file could not be read:");
Console.WriteLine("Exception Stack Trace : " + e.StackTrace);
}
return new OTA_AirAvailRS();
}
its throws an exception Message: ERR.SWS.CLIENT.VALIDATION_FAILED
Stack:
Server stack trace:
at
System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime
operation, ProxyRpc& rpc) at
System.ServiceModel.Channels.ServiceChannel.Call(String action,
Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
Object[] outs, TimeSpan timeout) at
System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
methodCall, ProxyOperationRuntime operation) at
System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
message)
Exception rethrown at [0]: at
System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
reqMsg, IMessage retMsg) at
System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
msgData, Int32 type) at
ConsoleApplication1.ServiceAirAvailLLSReference1.OTA_AirAvailPortType.OTA_AirAvailRQ(OTA_AirAvailRQRequest
request) at
ConsoleApplication1.ServiceAirAvailLLSReference1.OTA_AirAvailPortTypeClient.ConsoleApplication1.ServiceAirAvailLLSReference1.OTA_AirAvailPortType.OTA_AirAvailRQ(OTA_AirAvailRQRequest
request) in e:\ConsoleApplication1\ConsoleApplication1\Service
References\ServiceAirAvailLLSReference1\Reference.cs:line 7012 at
ConsoleApplication1.ServiceAirAvailLLSReference1.OTA_AirAvailPortTypeClient.OTA_AirAvailRQ(MessageHeader&
MessageHeader, Security1& Security, OTA_AirAvailRQ OTA_AirAvailRQ1) in
e:\ConsoleApplication1\ConsoleApplication1\Service
References\ServiceAirAvailLLSReference1\Reference.cs:line 7020 at
ConsoleApplication1.SearchAirAvail.Method(String securitytoken, String
convid, String ipcc) in
e:\ConsoleApplication1\ConsoleApplication1\SearchAirAvail.cs:line 115
Please Help Me
I found the answer of this question..
Just comment
//ArrivalDateTime = "12-21T19:00"
This field is not required for request
I am using apache commons httpclient version 4.2 to execute a simple web service based on SOAP 1.2. I am able to fire the web service properly through SOAP UI but I am unable to do the same using Java.
Following is the method I'm using to invoke the service.
private static byte[] callSOAPServer(String body, String SOAP_ACTION,
String SERVER_URL) {
byte[] result = null;
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
int timeoutConnection = 15000;
HttpConnectionParams.setConnectionTimeout(httpParameters,
timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 35000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
/*
* httpclient.getCredentialsProvider().setCredentials( new
* AuthScope("os.icloud.com", 80, null, "Digest"), new
* UsernamePasswordCredentials(username, password));
*/
HttpPost httppost = new HttpPost(SERVER_URL);
httppost.setHeader("soapaction", SOAP_ACTION);
httppost.setHeader("Content-Type", "text/xml; charset=utf-8");
System.out.println("executing request" + httppost.getRequestLine());
// now create a soap request message as follows:
final StringBuffer soap = new StringBuffer();
soap.append("\n");
soap.append("");
// this is a sample data..you have create your own required data BEGIN
soap.append(" \n");
soap.append(" \n");
soap.append("" + body);
soap.append(" \n");
soap.append(" \n");
/* soap.append(body); */
// END of MEssage Body
soap.append("");
System.out.println("SOAP Request : " + soap.toString());
// END of full SOAP request message
try {
HttpEntity entity = new StringEntity(soap.toString(), HTTP.UTF_8);
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);// calling
// server
HttpEntity r_entity = response.getEntity(); // get response
System.out.println("Reponse Header:Begin..."); // response headers
System.out.println("Reponse Header StatusLine:"
+ response.getStatusLine());
Header[] headers = response.getAllHeaders();
for (Header h : headers) {
System.out.println("Reponse Header " + h.getName() + ": "
+ h.getValue());
}
System.out.println("Reponse Header END...");
if (r_entity != null) {
result = new byte[(int) r_entity.getContentLength()];
if (r_entity.isStreaming()) {
DataInputStream is = new DataInputStream(
r_entity.getContent());
is.readFully(result);
}
}
} catch (Exception E) {
System.out.println("Exception While Connecting " + E.getMessage());
E.printStackTrace();
}
httpclient.getConnectionManager().shutdown(); // shut down the
// connection
return result;
}
Following is my SOAP Request as well as the end point.
String soapRequest = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:typ=\"http://skash.service.sahaj.com/types/\">"
+ "<soap:Header/>"
+ "<soap:Body>"
+ "<typ:remoteSKASHDeductionElement>"
+ "<typ:vleId>?</typ:vleId>"
+ "<typ:paidAmt>?</typ:paidAmt>"
+ "<typ:refTxnId>?</typ:refTxnId>"
+ "</typ:remoteSKASHDeductionElement>"
+ "</soap:Body>"
+ "</soap:Envelope>";
String soapEndPoint = "http://xxx.xxx.xxx.xxx:xxxx/skashws/remoteSKASHDeductionSoap12HttpPort";
String soapAction = "http://xxx.xxx.xxx.xxx:xxxx//remoteSKASHDeduction";
// executeSOAPRequest(soapRequest, soapEndPoint, soapAction);
byte[] resp = callSOAPServer(soapRequest, soapAction, soapEndPoint);
System.out.println(IOUtils.toString(resp));
I can see that the namespace set to Envelope tag is for SOAP 1.2 and is well set. I am not sure where I'm going wrong. I am receiving the following version mismatch error.
<env:Envelope xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<env:Header>
<env:Upgrade>
<env:SupportedEnvelope xmlns:soap12="http://www.w3.org/2003/05/soap-envelope" qname="soap12:Envelope"/>
</env:Upgrade>
</env:Header>
<env:Body>
<env:Fault xmlns:env="http://schemas.xmlsoap.org/soap/envelope/">
<faultcode>env:VersionMismatch</faultcode>
<faultstring>Version Mismatch</faultstring>
<faultactor>http://schemas.xmlsoap.org/soap/actor/next</faultactor>
</env:Fault>
</env:Body>
you may use this code block
public class GenericSoapMessageFactory extends SaajSoapMessageFactory implements InitializingBean {
#Override
public SaajSoapMessage createWebServiceMessage(InputStream inputStream) throws IOException {
setMessageFactoryForRequestContext(soap11);
if (inputStream instanceof TransportInputStream) {
TransportInputStream transportInputStream = (TransportInputStream) inputStream;
if (soapProtocolChooser.useSoap12(transportInputStream)) {
setMessageFactoryForRequestContext(soap12);
}
}
SaajSoapMessageFactory mf = getMessageFactoryForRequestContext();
return mf.createWebServiceMessage(inputStream);
}
}
And web.xml params
<servlet>
<servlet-name>spring-ws2</servlet-name>
<servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
<init-param>
<param-name>messageFactoryBeanName</param-name>
<param-value>genericSoapMessageFactory</param-value>
</init-param>
</servlet>
I saw this error once and I changed the following line;
httppost.setHeader("Content-Type", "text/xml; charset=utf-8");
to
httppost.setHeader("Content-Type", "application/soap+xml;charset=UTF-8;");
and it fixed the issue. Try it.
I am trying to create Restful Webservice as a client of Message Driven Bean, But when i invoke the restful method its giving me following error when
Connection connection = connectionFactory.createConnection();
SEVERE: The RuntimeException could not be mapped to a response, re-throwing to the HTTP container
java.lang.NullPointerException
at com.quant.ws.GetConnection.startThread(GetConnection.java:99)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
here is the following code:
// Inside class declaration
#Resource(mappedName = "jms/testFactory")
private static ConnectionFactory connectionFactory;
#Resource(mappedName = "jms/test")
private static Queue queue;
Web services Method
#GET
#Path("startThread")
#Produces("application/xml")
public String startThread()
{
try{
Connection connection = connectionFactory.createConnection(); // its line number 99
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer( queue);
Message message = session.createTextMessage();
message.setStringProperty("name", "start");
producer.send(message);
}catch(JMSException e){
System.out.println(e);
}
return "<data>START</data>";
}
Do i need to specify anything in sun-web.xml or web.xml ?
I think it depends on your applicationserver setup. Did you inject the connectionFactory somewhere above? Or did a context lookup?
connectionFactory is null. It needs to be initialised somehow.
I have solved it by replacing following code
try{
InitialContext ctx = new InitialContext();
queue = (Queue) ctx.lookup("jms/test");
QueueConnectionFactory factory =
(QueueConnectionFactory) ctx.lookup("jms/testFactory");
Connection connection = factory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer( queue);
Message message = session.createTextMessage();
message.setStringProperty("name", "start");
producer.send(message);
}
catch(NamingException e){
System.out.println(e);
}
catch(JMSException e){
System.out.println(e);
}