I've a web service packaged in a .war and which has the following structure :
-> META-INF
| -> maven
| -> MANIFEST.MF
-> WEB-INF
| -> classes
| -> lib
| -> beans.xml
| ...
-> wsdl
| -> filldatabase.wsdl
| -> filldatabase_schema.xsd
When I put this archive inside my standalone/deployments folder of my wildfly server, that works but if I want to display the WSDL through the browser, it's return me 404 Not Found
The soap address used to be typed in my browser is te following (precised in my filldatabase.wsdl file) :
<soap12:address location="http://localhost:8080/dataRecovery/services"/>
Some additional informations :
my function in java :
#WebService(targetNamespace = "http://dataRecovery/", portName = "FillDataBasePort", serviceName = "FillDataBaseService")
public class FillDataBase {
#WebMethod(operationName = "fillDataBase", action = "urn:FillDataBase")
#RequestWrapper(className = "dataRecovery.jaxws.FillDataBase", localName = "fillDataBase", targetNamespace = "http://dataRecovery/")
#ResponseWrapper(className = "dataRecovery.jaxws.FillDataBaseResponse", localName = "fillDataBaseResponse", targetNamespace = "http://dataRecovery/")
#WebResult(name = "return")
public void fillDataBase() throws IOException {
...
}
Any suggestions ?
Related
I'm writing some unit tests for a rest controller using HttpClient but I'm gettint the error on the title in the exchange part, we are using DynamoDBEmbeddedClient to have a fake data base instead of using the real db for testing, before adding the DynamoDBEmbeddedClient the test was working, so maybe I'm missing something on the test or the controller to mak it work?
The enpoint is just a patch to save or update an entry, the app it actually works and everything, is just the test that it seems to be broken
application-test.yml:
micronaut:
server:
port: -1
application:
name: app
endpoints:
all:
port: 9999
dynamodb:
e-note-table-name: dummy-table-name
environment: test
Controller:
#Validated
#Controller("/api/v1/")
#ExecuteOn(TaskExecutors.IO)
class ENotesController(private val service: ENoteService) {
#Patch("/")
fun createNoteRecord(#Body eNote: ENote
): Mono<HttpResponse<ENote>> {
return service.save(eNote)
.map { HttpResponse.ok(it) }
}
}
Test:
#MicronautTest(startApplication = false)
#ExtendWith(DynamoDBExtension::class)
#TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ENoteControllerTest {
#Inject
#field:Client("/")
lateinit var client: HttpClient
#Test
fun `PATCH eNote - should create a new eNote`() {
val newENote = eNote()
val request = HttpRequest
.PATCH(
"/api/v1/",
newENote
)
val response = client
.toBlocking()
.exchange(request, ENote::class.java)
assertEquals(HttpStatus.OK, response.status)
assertEquals(newENote.noteKey, response.body()!!.noteKey)
assertEquals(newENote.noteEntries, response.body()!!.noteEntries)
}
private fun eNote() = ENote(
studentId = UUID.randomUUID().toString(),
enrollmentId = UUID.randomUUID().toString(),
courseId = UUID.randomUUID().toString(),
activityId = UUID.randomUUID().toString(),
noteEntries = listOf("Test the", "Patch method"),
audit = Audit(
createdBy = UUID.randomUUID().toString(),
updatedBy = UUID.randomUUID().toString(),
createdAt = Instant.now(),
updatedAt = Instant.now()
)
)
}
And this is the ReplacementBeanFactory where we replace the real instance of dynamodb for a fake one for the unit tests
#Factory
class ReplacementBeanFactory() {
#Singleton
#Replaces(DynamoDbAsyncClient::class)
fun dynamoDbAsyncClient(): DynamoDbAsyncClient {
val dynamoDbLocal = DynamoDBEmbedded.create();
return dynamoDbLocal.dynamoDbAsyncClient()
}
#Singleton
#Replaces(DynamoDbEnhancedAsyncClient::class)
fun dynamoDbEnhancedAsyncClient(): DynamoDbEnhancedAsyncClient {
return DynamoDbEnhancedAsyncClient.builder()
.dynamoDbClient(dynamoDbAsyncClient())
.build()
}
}
I am using Marten as an Event Store, in particular to fetch a stream of events.
type AccountCreation = {
Owner: string
AccountId: Guid
CreatedAt: DateTimeOffset
StartingBalance: decimal
}
type AccountEvents =
| AccountCreated of AccountCreation
| AccountCredited of Transaction
| AccountDebited of Transaction
let settings = {
Host = "localhost"
DatabaseName = "postgres"
UserName = "root"
Password = "root"
EventTypes = eventTypes
}
use store = createDocumentStore settings
use session = store.LightweightSession()
let khalidId = Guid.NewGuid()
let billId = Guid.NewGuid()
let khalid = AccountEvents.AccountCreated({
Owner = "Khalid Abuhakmeh"
AccountId = khalidId
StartingBalance = 1000m
CreatedAt = DateTimeOffset.UtcNow
})
let bill = {
Owner = "Bill Boga"
AccountId = billId
StartingBalance = 0m
CreatedAt = DateTimeOffset.UtcNow
}
session.Events.Append(khalidId, khalid) |> ignore
session.Events.Append(billId, bill) |> ignore
session.SaveChanges()
let stream = session.Events.FetchStream()
stream being IReadOnlyList<IEvent> and IEvent defined as:
public interface IEvent
{
Guid Id { get; set; }
int Version { get; set; }
long Sequence { get; set; }
object Data { get; }
Guid StreamId { get; set; }
string StreamKey { get; set; }
DateTimeOffset Timestamp { get; set; }
string TenantId { get; set; }
void Apply<TAggregate>(TAggregate state, IAggregator<TAggregate> aggregator) where TAggregate : class, new();
}
I would like to convert each IEvent to AccountEvents, if the underlying type of the Data property is AccountEvents (if not the item is not yielded in the resulting sequence).
In C# I would simply use the keyword as to achieve that, but in F# I am not sure what is the fastest F#-ish way(in terms of performance) to get that.
I ended up on the following code:
let seqCastOption<'T> sequence =
sequence
|> Seq.map(fun x ->
match box x with
| :? 'T as value -> Some value
| _ -> None)
let fetchStream<'T> (session: IDocumentSession) (id: Guid) =
let stream = session.Events.FetchStream(id)
stream
|> Seq.map(fun x -> x.Data)
|> seqCastOption<'T>
|> Seq.filter (fun x -> x.IsSome)
|> Seq.map(fun x -> x.Value)
But this seems quite "expensive", and I an wondering whether the step of converting .Data to the Option<AccountEvents> + filter the ones that IsSome can be done all at once.
The Seq.choose function mentioned in rmunn's answer is very useful to know for this kind of situation, but for this exact situation I would recommend using the built in .NET method Enumerable.OfType<'T>, which does exactly what you want and is probably quite optimised:
open System.Linq
let fetchStream<'T> (session: IDocumentSession) (id: Guid) =
let stream = session.Events.FetchStream(id)
stream
|> Seq.map(fun x -> x.Data)
|> Enumerable.OfType<'T>
Seq.choose is the function you've been looking for. You give it a function that takes an 'A and returns a 'B option, and it yields the 'B value of the ones that were Some. For your usage scenario, it would look like this:
let castOption<'T> x =
match box x with
| :? 'T as value -> Some value
| _ -> None
let fetchStream<'T> (session: IDocumentSession) (id: Guid) =
let stream = session.Events.FetchStream(id)
stream
|> Seq.map(fun x -> x.Data)
|> Seq.choose castOption<'T>
I have created a Spring Restful API based Web service.
Please suggest how can I create a WADL document for this service.
I access the Web Service through eclipse by :
http://localhost:8080/SampleSpringService/mcxService/getMCX
Service Name : mcxService,
Function name : getMCX
Java File code which is being called as Web Service:
#RestController
#RequestMapping(value = "/mcxService")
#PropertySource(value = "classpath:FileProperty.properties")
public class MCXController {
#Autowired
private MessageSource messageSource;
#Value("${jsonFile.path}")
private String jsonFilePath;
#RequestMapping(value = "/getMCX", method = RequestMethod.GET, produces = "application/json")
public String getMCXData(HttpServletRequest request) throws JsonParseException, JsonMappingException, IOException {
System.out.println(messageSource.getMessage("jsonFile.path", null, null));
// read Form data to String
String data = request.getParameter("firstname");
System.out.println("data = " + data);
if(data == null){return "Data is NULL !!!!" ;}
saveUserList(data);
return "Data (" + data + ") is saved to File : D:/test.txt" ;
}
The Java Code example is all over the web. But where is an example of the properties file contents AwsCredentials.properties?
public AmazonSESMailer(Environment env) throws IOException {
this.env = env;
InputStream resource = AmazonSESMailer.class
.getResourceAsStream("/AwsCredentials.properties");
PropertiesCredentials credentials = new PropertiesCredentials(resource);
this.client = new AmazonSimpleEmailServiceClient(credentials);
Properties props = new Properties();
props.setProperty("mail.transport.protocol", "aws");
props.setProperty("mail.aws.user", credentials.getAWSAccessKeyId());
props.setProperty("mail.aws.password", credentials.getAWSSecretKey());
this.session = Session.getInstance(props);
}
private final static Logger logger = LoggerFactory
.getLogger(AmazonSESMailer.class);
private final static String FROM = "vraptor.simplemail.main.from";
private final static String REPLY_TO = "vraptor.simplemail.main.replyTo";
private final static String SEND_REAL_EMAIL = "vraptor.simplemail.send_real_email";
The getResourceAsStream("/AwsCredentials.properties") file is being loaded by the class loader, so put it in the "classes" folder of the web app. Then the contents of the file should be only two lines:
accessKey = UTZA...
secretKey = Alj...
enjoy
I'm using Play 2.3.7 with Scala 2.11.4, Java 7. I want to use Play WS to connect to an HTTPS endpoint, that requires client to present its certificate. To do it I create my own SSLContext:
val sslContext = {
val keyStore = KeyStore.getInstance("pkcs12")
keyStore.load(new FileInputStream(clientKey), clientKeyPass.to[Array])
val kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm)
kmf.init(keyStore, clientKeyPass.to[Array])
val trustStore = KeyStore.getInstance("jks")
trustStore.load(new FileInputStream(trustStoreFile), trustStorePass.to[Array])
val tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm)
tmf.init(trustStore)
val ctx = SSLContext.getInstance("TLSv1.2")
ctx.init(kmf.getKeyManagers, tmf.getTrustManagers, new SecureRandom())
ctx
}
I know, that the SSLContext is valid, because I can use it with URLConnection successfully:
def urlConnection = Action {
val conn = new URL(url).openConnection()
conn.asInstanceOf[HttpsURLConnection].setSSLSocketFactory(sslContext.getSocketFactory)
conn.connect()
Ok(scala.io.Source.fromInputStream(conn.getInputStream).getLines().mkString("\n"))
}
But when I try one of two ways below I get java.nio.channels.ClosedChannelException.
def ning = Action.async {
val builder = new AsyncHttpClientConfig.Builder()
builder.setSSLContext(sslContext)
val client = new NingWSClient(builder.build())
client.url(url).get() map { _ => Ok("ok") }
}
def asyncHttpClient = Action {
val builder = new AsyncHttpClientConfig.Builder()
builder.setSSLContext(sslContext)
val httpClient = new AsyncHttpClient(builder.build())
httpClient.prepareGet(url).execute().get(10, TimeUnit.SECONDS)
Ok("ok")
}
I also get the same exception when I go after suggestion of Will Sargent and use NingAsyncHttpClientConfigBuilder with parsed config (note, that config references exactly the same values, the hand-crafted sslContext does).
def ningFromConfig = Action.async {
val config = play.api.Configuration(ConfigFactory.parseString(
s"""
|ws.ssl {
| keyManager = {
| stores = [
| { type: "PKCS12", path: "$clientKey", password: "$clientKeyPass" }
| ]
| }
| trustManager = {
| stores = [
| { type: "JKS", path: "$trustStoreFile", password: "$trustStorePass" },
| ]
| }
|}
|# Without this one I get InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty
|ws.ssl.disabledKeyAlgorithms="RSA keySize < 1024"
""".stripMargin))
val parser = new DefaultWSConfigParser(config, play.api.Play.application.classloader)
val builder = new NingAsyncHttpClientConfigBuilder(parser.parse())
val client = new NingWSClient(builder.build())
client.url(url).get() map { _ => Ok("ok") }
}
How to make it work with Play WS?
You should use a client certificate from application.conf as defined in https://www.playframework.com/documentation/2.3.x/KeyStores and https://www.playframework.com/documentation/2.3.x/ExampleSSLConfig -- if you need to use a custom configuration, you should use the parser directly:
https://github.com/playframework/playframework/blob/2.3.x/framework/src/play-ws/src/test/scala/play/api/libs/ws/DefaultWSConfigParserSpec.scala#L14
to create a config, then the Ning builder:
https://github.com/playframework/playframework/blob/2.3.x/framework/src/play-ws/src/test/scala/play/api/libs/ws/ning/NingAsyncHttpClientConfigBuilderSpec.scala#L33
which will give you the AHCConfig object that you can pass in. There's examples in the "Using WSClient" section of https://www.playframework.com/documentation/2.3.x/ScalaWS.