Angular2 HttpClient to consume Rest API - java

Using Angular2, I have developed the example given in the tutorial (The Hero Editor).
https://angular.io/tutorial/toh-pt6
By default, it calls a self-in-memory-store with the data that is accessible through the Http Client created in the same example.
All this run perfectly in localhost:3000 (the port given by default).
Now I have developed a rest api server in Java which runs perfectly in localhost:8080 using this tutorial:
http://spring.io/guides/gs/rest-service/
Nevertheless, when I switch the URL where Angular service has to get the data from, I get the following error:
ERROR Error: Uncaught (in promise): Response with status: 404 Not Found for URL: http://localhost:8080/heroes
at resolvePromise (zone.js:769)
at resolvePromise (zone.js:740)
at zone.js:817
at ZoneDelegate.invokeTask (zone.js:424)
at Object.onInvokeTask (ng_zone.ts:253)
at ZoneDelegate.invokeTask (zone.js:423)
at Zone.runTask (zone.js:191)
at drainMicroTaskQueue (zone.js:584)
at XMLHttpRequest.ZoneTask.invoke (zone.js:490)
Complete http Response:
But I check the url and it works perfectly.
Do I have to tell anything else to the Service?
This is the point where all should be done.
//private heroesUrl = 'api/heroes'; // Old URL (to get the own data storage)
private heroesUrl = `http://localhost:8080/heroes`; // New URL to get the data from working local Rest API running in other port.
constructor (private http: Http) { }
getHeroes(): Promise<Hero[]> {
//return Promise.resolve(HEROES);
return this.http.get(this.heroesUrl)
.toPromise()
.then(response => response.json().data as Hero[])
.catch(this.handleError)
} // stub
Edit: answering a comment, I show below the app module code. By the way, it is an exact copy of the app.module.ts from the Hero Editor Angular tutorial I linked at the beginning of the question.
import { NgModule } from '#angular/core';
import { BrowserModule } from '#angular/platform-browser';
import { FormsModule } from '#angular/forms';
import { HttpModule } from '#angular/http';
import { AppRoutingModule } from './app-routing.module';
// Imports for loading & configuring the in-memory web api
import { InMemoryWebApiModule } from 'angular-in-memory-web-api';
import { InMemoryDataService } from './in-memory-data.service';
import { AppComponent } from './app.component';
import { DashboardComponent} from './dashboard.component'
import { HeroDetailComponent } from './hero-detail.component';
import { HeroSearchComponent } from './hero-search.component';
import { HeroesComponent } from './heroes.component';
import { HeroService } from './hero.service';
#NgModule({
imports: [
BrowserModule,
FormsModule,
HttpModule,
InMemoryWebApiModule.forRoot(InMemoryDataService),
AppRoutingModule
],
declarations: [
AppComponent,
HeroDetailComponent,
HeroesComponent,
DashboardComponent,
HeroSearchComponent
],
providers: [ HeroService ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
Any idea anyone? I have seen some examples where they are adding some more information to the headers. Is that necessary? Any issue about security?

I got the solution.
#AJT_82 gave me the main clue.
As It was said in the app module (app.module.js) file, my app was taking the data from an InMemory storage system.
When I commented this line:
//InMemoryWebApiModule.forRoot(InMemoryDataService)
it just started to get the data from the URL provided to the localhost:8080/heroes Rest API.
Sorry for making you waste your time.

Related

SnapStart function priming - Doesn't seem to be working

I’m somewhat new to Kotlin/Java, but I have been using AWS Lambda for several years now (all Python and Node). I’ve been trying to “successfully” enable SnapStart on a SpringBoot Lambda using Kotlin running on java11 corretto (the only runtime supported currently), but it doesn’t seem to be working as I would have expected.
I have hooked into the CRaC lifecycle methods beforeCheckpoint and afterRestore. In beforeCheckpoint I’ve initialized the SpringBoot application and I can see it in the deployment logs (AWS creates log streams for the deployment phase with SnapStart lambdas).
However, the concerning thing is I’m also seeing the SpringBoot app get initialized in the function invocation logs too. I would have expected that to only happen during the deployment/initialization phase when the snapshot is being created. As a result I’m not really seeing a tremendous improvement on latency or overall.
Any ideas why this is happening?
I ran into essentially the same issue (with Java instead of Kotlin) and the solution was to switch the runtime->handler from
org.springframework.cloud.function.adapter.aws.SpringBootStreamHandler
to
org.springframework.cloud.function.adapter.aws.FunctionInvoker::handleRequest
It would probably be worth mentioning that as of 2023-02-20 SnapStart isn't engaged for $LATEST version of an AWS Lambda function, i.e. make sure you are invoking a particular published version. Otherwise, Best practices for working with Lambda SnapStart article says that the main performance killers are dynamically loaded classes, and network connections that need to be re-established from time to time.
From Snapstart Integration issue raised for Spring Cloud Function on GitHub I tend to think that switching to org.springframework.cloud.function.adapter.aws.FunctionInvoker probably somewhat helps, but doesn't address the performance challenges mentioned above. I'm not sure if I'm interpreting olegz's advice correctly, but what worked best so far for my AWS lambda function built with Spring Boot/Spring Cloud Function is a "warm-up" config. It hooks into the CRaC lifecycle via beforeCheckpoint() and issues dummy requests to S3 and DynamoDB before the VM snapshot is made. This way most dynamically-loaded classes are pre-loaded, and network connections are pre-established, before any subsequent function invocation takes place.
package eu.mycompany.mysamplesystem.attachmentstore.configuration;
import com.amazonaws.services.lambda.runtime.events.S3Event;
import eu.mycompany.mysamplesystem.attachmentstore.handlers.MainEventHandler;
import lombok.extern.slf4j.Slf4j;
import org.crac.Core;
import org.crac.Resource;
import org.springframework.context.annotation.Configuration;
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
import java.util.ArrayList;
import java.util.List;
#Configuration
#Slf4j
public class WarmUpConfig implements Resource {
private final MainEventHandler mainEventHandler;
public WarmUpConfig(final MainEventHandler mainEventHandler) {
Core.getGlobalContext().register(this);
this.mainEventHandler = mainEventHandler;
}
#Override
public void beforeCheckpoint(org.crac.Context<? extends Resource> context) {
log.debug("Warm-up MainEventHandler by issuing dummy requests");
dummyS3Invocation();
dummyDynamoDbInvocation();
}
#Override
public void afterRestore(org.crac.Context<? extends Resource> context) {
}
public void dummyS3Invocation() {
S3Event s3Event = generateWarmUpEvent("ObjectCreated:Put");
try {
mainEventHandler.handleRequest(s3Event, null);
throw new IllegalStateException("Warm-up event processing should have reached S3 and failed with S3Exception");
} catch (NoSuchKeyException e) {
log.debug("S3Exception is expected, since it is a warm-up");
}
}
public void dummyDynamoDbInvocation() {
S3Event s3Event = generateWarmUpEvent("ObjectRemoved:Delete");
mainEventHandler.handleRequest(s3Event, null);
}
private S3Event generateWarmUpEvent(String eventName) {
S3Event.S3BucketEntity s3BucketEntity = new S3Event.S3BucketEntity("hopefully_non_existing_bucket", null, null);
S3Event.S3ObjectEntity s3ObjectEntity = new S3Event.S3ObjectEntity("hopefully/non/existing.key", 0L, null, null, null);
S3Event.S3Entity s3Entity = new S3Event.S3Entity(null, s3BucketEntity, s3ObjectEntity, null);
List<S3Event.S3EventNotificationRecord> records = new ArrayList<>();
records.add(new S3Event.S3EventNotificationRecord(null, eventName, null, null, null, null, null, s3Entity, null));
return new S3Event(records);
}
}
P.S.: The MainEventHandler is basically the entry point to all the business logic exposed by the Function.
#SpringBootApplication
#RequiredArgsConstructor
public class Lambda {
private final MainEventHandler mainEventHandler;
public static void main(String... args) {
SpringApplication.run(Lambda.class, args);
}
#Bean
public Function<Message<S3Event>, String> defaultFunctionLambda() {
return message -> {
Context context = message.getHeaders().get("aws-context", Context.class);
return mainEventHandler.handleRequest(message.getPayload(), context);
};
}
}

Broadleaf Commerce Embedded Solr cannot run with root user

I download a fresh 6.1 broadleaf-commerce and run my local machine via java -javaagent:./admin/target/agents/spring-instrument.jar -jar admin/target/admin.jar successfully on mine macbook. But in my centos 7 I run sudo java -javaagent:./admin/target/agents/spring-instrument.jar -jar admin/target/admin.jar with following error
2020-10-12 13:20:10.838 INFO 2481 --- [ main] c.b.solr.autoconfigure.SolrServer : Syncing solr config file: jar:file:/home/mynewuser/seafood-broadleaf/admin/target/admin.jar!/BOOT-INF/lib/broadleaf-boot-starter-solr-2.2.1-GA.jar!/solr/standalone/solrhome/configsets/fulfillment_order/conf/solrconfig.xml to: /tmp/solr-7.7.2/solr-7.7.2/server/solr/configsets/fulfillment_order/conf/solrconfig.xml
*** [WARN] *** Your Max Processes Limit is currently 62383.
It should be set to 65000 to avoid operational disruption.
If you no longer wish to see this warning, set SOLR_ULIMIT_CHECKS to false in your profile or solr.in.sh
WARNING: Starting Solr as the root user is a security risk and not considered best practice. Exiting.
Please consult the Reference Guide. To override this check, start with argument '-force'
2020-10-12 13:20:11.021 ERROR 2481 --- [ main] c.b.solr.autoconfigure.SolrServer : Problem starting Solr
Here is the source code of solr configuration, I believe it is the place to change the configuration to run with the argument -force in programming way.
package com.community.core.config;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.broadleafcommerce.core.search.service.SearchService;
import org.broadleafcommerce.core.search.service.solr.SolrConfiguration;
import org.broadleafcommerce.core.search.service.solr.SolrSearchServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
/**
*
*
* #author Phillip Verheyden (phillipuniverse)
*/
#Component
public class ApplicationSolrConfiguration {
#Value("${solr.url.primary}")
protected String primaryCatalogSolrUrl;
#Value("${solr.url.reindex}")
protected String reindexCatalogSolrUrl;
#Value("${solr.url.admin}")
protected String adminCatalogSolrUrl;
#Bean
public SolrClient primaryCatalogSolrClient() {
return new HttpSolrClient.Builder(primaryCatalogSolrUrl).build();
}
#Bean
public SolrClient reindexCatalogSolrClient() {
return new HttpSolrClient.Builder(reindexCatalogSolrUrl).build();
}
#Bean
public SolrClient adminCatalogSolrClient() {
return new HttpSolrClient.Builder(adminCatalogSolrUrl).build();
}
#Bean
public SolrConfiguration blCatalogSolrConfiguration() throws IllegalStateException {
return new SolrConfiguration(primaryCatalogSolrClient(), reindexCatalogSolrClient(), adminCatalogSolrClient());
}
#Bean
protected SearchService blSearchService() {
return new SolrSearchServiceImpl();
}
}
Let me preface this by saying you would be better off simply not starting the application as root. If you are in Docker, you can use the USER command to switch to a non-root user.
The Solr server startup in Broadleaf Community is done programmatically via the broadleaf-boot-starter-solr dependency. This is the wrapper around Solr that ties it to the Spring lifecycle. All of the real magic happens in the com.broadleafcommerce.solr.autoconfigure.SolrServer class.
In that class, you will see a startSolr() method. This method is what adds startup arguments to Solr.
In your case, you will need to mostly copy this method wholesale and use cmdLine.addArgument(...) to add additional arguments. Example:
class ForceStartupSolrServer extends SolrServer {
public ForceStartupSolrServer(SolrProperties props) {
super(props);
}
protected void startSolr() {
if (!isRunning()) {
if (!downloadSolrIfApplicable()) {
throw new IllegalStateException("Could not download or expand Solr, see previous logs for more information");
}
stopSolr();
synchConfig();
{
CommandLine cmdLine = new CommandLine(getSolrCommand());
cmdLine.addArgument("start");
cmdLine.addArgument("-p");
cmdLine.addArgument(Integer.toString(props.getPort()));
// START MODIFICATION
cmdLine.addArgument("-force");
// END MODIFICATION
Executor executor = new DefaultExecutor();
PumpStreamHandler streamHandler = new PumpStreamHandler(System.out);
streamHandler.setStopTimeout(1000);
executor.setStreamHandler(streamHandler);
try {
executor.execute(cmdLine);
created = true;
checkCoreStatus();
} catch (IOException e) {
LOG.error("Problem starting Solr", e);
}
}
}
}
}
Then create an #Configuration class to override the blAutoSolrServer bean created by SolrAutoConfiguration (note the specific package requirement for org.broadleafoverrides.config):
package org.broadleafoverrides.config;
public class OverrideConfiguration {
#Bean
public ForceStartupSolrServer blAutoSolrServer(SolrProperties props) {
return new ForceStartupSolrServer(props);
}
}

JBPM6 Service task to execute java code

I am new in JBPM6. My scenario is like this that i want to execute some java code using JBPM service task.From documentation i am not able to understand how to use domain specific process and Work Item Handler in this type of code.
If someone have sample example of it please share.That will be very much helpful.
Thank you in advance.
Here is how to add a handler inside a Eclipse maven project. I call it the Awesome handler, but your should pick a more specific name.
1) First create a work item definition file in src/main/resources/WorkItemDefinitions.wid. My icon file is located in src/main/resources.
import org.drools.core.process.core.datatype.impl.type.StringDataType;
[
[
"name" : "Awesome",
"parameters" : [
"Message1" : new StringDataType(),
"Message2" : new StringDataType()
],
"displayName" : "Awesome",
"icon" : "icon-info.gif"
]
]
2) Create a Work Item Handler Config file in src/main/resources/META-INF/CustomWorkItemHandlers.conf
[
"Awesome": new org.jbpm.examples.util.handler.AwesomeHandler()
]
3) Create a drools session config file: src/main/resources/META-INF/drools.session.conf
drools.workItemHandlers = CustomWorkItemHandlers.conf
4) Create your Handler so that it matches the class you defined in step 2
public class AwesomeHandler implements WorkItemHandler {
public AwesomeHandler() {
super();
}
public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
System.out.println("Executing Awesome handler");
manager.completeWorkItem(workItem.getId(), null);
}
public void abortWorkItem(WorkItem workItem, WorkItemManager manager) {
System.out.println("Aborting");
}
}
5) After you establish the handler, you must register it with your session.
//Get session
KieSession ksession = runtime.getKieSession();
//Register handlers
ksession.getWorkItemManager().registerWorkItemHandler("Awesome", new AwesomeHandler());
At this point you should restart eclipse. When eclipse opens, there should be a 'Custom Tasks' tab in the palette. It should contain an entry labeled 'Awesome' with the specified icon.
I know the question is already answered, but I wanted to do the same (execute java code in service task) without creating work item definition (I did't want to use a custom task but a service task as it is). This is how I solved it:
here I read about the ServiceTaskHandler but I couldn't find very good info about the usage.
I read the ServiceTaskHandler code, it uses reflection to run your java code.
I found this (it says jbpm5-samples but I tested with jbpm 6.3), it uses a service task, the service task executes method "hello" from a Class (HelloService) you create:
package com.test;
import java.util.HashMap;
import java.util.Map;
public class HelloService {
public DataOutput hello(com.test.DataInput name) {
Map<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("s", "Hello " + name.getDataMap().get("s") + "!");
DataOutput output = new DataOutput(dataMap);
return output;
}
}
The ServiceTaskHandler is registered the same way as the step (5) in the answer marked correct:
//Get session
KieSession ksession = runtime.getKieSession();
//Register handlers
ksession.getWorkItemManager().registerWorkItemHandler("Service Task", new ServiceTaskHandler());
After that I associated the service task with the java class (HelloService - method hello).
To do that I used the eclipse bpmn modeler but I didn't find it very intuitive, so I opened the sample's bpmn file (BPMN2-ServiceProcess.bpmn2) with the modeler and filled my service task with the same stuff I read there.
#mike i really hope you see my comment and willing to help me. so i followed everysteps that you mentioned but i still never see my customtask.
enter image description here
this is my project directory and i think everything is right, but to make sure ill just posts my code here
WorkItemDefinitions.wid:
import org.drools.core.process.core.datatype.impl.type.StringDataType;
[
[
"name" : "Awesome",
"parameters" : [
"Message1" : new StringDataType(),
"Message2" : new StringDataType()
],
"displayName" : "Awesome",
"icon" : "ezgif.com-apng-to-gif.gif"
]
]
drools.session.conf:
drools.workItemHandlers = CustomWorkItemHandlers.conf
CustomWorkItemHandlers.conf:
[
"Awesome": new com.sample.AwesomeHandler()
]
AwsomeHandler.java:
package com.sample;
import org.kie.api.runtime.process.WorkItem;
import org.kie.api.runtime.process.WorkItemHandler;
import org.kie.api.runtime.process.WorkItemManager;
public class AwesomeHandler implements WorkItemHandler{
public AwesomeHandler() {
super();
}
#Override
public void executeWorkItem(WorkItem workItem, WorkItemManager manager) {
// TODO Auto-generated method stub
System.out.println("Executing Awesome handler");
manager.completeWorkItem(workItem.getId(), null);
}
#Override
public void abortWorkItem(WorkItem workItem, WorkItemManager manager) {
// TODO Auto-generated method stub
System.out.println("Aborting");
}
}
in main:
TaskService taskService = engine.getTaskService();
ksession.getWorkItemManager().registerWorkItemHandler("Awesome", new AwesomeHandler());
I really don't know what i did wrong and i need this for my unis. i really hope i will get a reply and wish you a very good day ;)
Apart from the (excellent) example provided by Mike, if your only goal is to execute some Java code, you can consider using a Script task instead (and just embed the Java code in your process) or reuse the already existing Service Task that can invoke an operation on a Java class.

JSON Parsing Error - Unable to update core database values

I am using JAX-RS over AngularJS, but I have hit a stumbling block due to json parsing errors.
Using jsonlint I can see the issues, but as I cannot update the underlying database values which are causing the issue to correct the characters (corporate data warehouse)...I am now in trouble as I can't return any data at all into the application because just a small handful of records have non compliant characters in them.
What is the general approach for dealing with these kind of issues? Is it to search and replace for non ascii- characters at the java end in the setter?
Update:
Error from Chrome:
SyntaxError: Unexpected token
at Object.parse (native)
at ub (http://localhost:8080/misf-web/lib/angular/angular.min.js:13:122)
at e.defaults.transformResponse (http://localhost:8080/misf-web/lib/angular/angular.min.js:98:83)
at http://localhost:8080/misf-web/lib/angular/angular.min.js:97:347
at Array.forEach (native)
at n (http://localhost:8080/misf-web/lib/angular/angular.min.js:6:470)
at Yb (http://localhost:8080/misf-web/lib/angular/angular.min.js:97:329)
at c (http://localhost:8080/misf-web/lib/angular/angular.min.js:99:14)
at i (http://localhost:8080/misf-web/lib/angular/angular.min.js:79:437)
at http://localhost:8080/misf-web/lib/angular/angular.min.js:80:485 angular.min.js:63
(anonymous function)
Sample JSON output - just one example which is causing me issues...it is not always "umlauts"...
{
"approvedPriority": "Approved",
"disease": "primary Sj�grens Syndrome",
"diseaseArea": "Inflammation",
"projectType": "NME",
"therapyArea": "RI"
}
In the database this disease appears as "primary Sjögren’s Syndrome"
jsonlint reports:
Parse error on line 3: ...ed", "disease": "primary Sj�grens S
----------------------^ Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['
It is not always "umlauts" causing me issues, sometimes it is a non printable charachter it seems, and one odd error I hunted down due to what appears to be a slightly wider hyphen than normal.
Update:
As far as I am aware I am requesting UTF-8 via JAX-RS.
#GET
#Path("/projects")
#Produces(MediaType.APPLICATION_JSON + "; charset=UTF-8")
public List<Project> getAllProjects() {
logger.debug("GET: list all projects");
return projectService.getAllProjects();
}
I am developing on Tomcat 7 on Windows using Eclipse.
Seems #PRODUCES and adding charset=utf-8 doesn't work.
In the end I created a filter which added charset=utf=8 to the response header before it was sent and registered it as a provider to jersey through the application config class.
Now it works and data is being returned perfectly.
Why #PRODUCES doesn't work is a mystery.
package com.mycompany.misf.filters;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MediaType;
public class HeaderResponseFilter implements ContainerResponseFilter {
public void filter(ContainerRequestContext request, ContainerResponseContext response) {
MediaType type = response.getMediaType();
if (type != null) {
String contentType = type.toString();
if (!contentType.contains("charset")) {
contentType = contentType + ";charset=utf-8";
response.getHeaders().putSingle("Content-Type", contentType);
}
}
}
}
Register the filter as a provider.
#ApplicationPath("resources")
public class RestApplication extends ResourceConfig {
public RestApplication() {
HashSet<Class<?>> c = new HashSet<Class<?>>();
c.add(PersonsRestService.class);
c.add(ProjectsRestService.class);
//add this
c.add(HeaderResponseFilter.class);
Set<Class<?>> classes = Collections.unmodifiableSet(c);
registerClasses(classes);
property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);
}
}

How to call a web service (described by a wsdl) from java

Knowing nothing of web services, I'm just trying to call some "isAlive" service that is described by a wsdl.
This seems to me like something that should take no more than 2-5 lines of code but I can't seem to find anything but huge long examples involving 3rd party packages etc.
Anyone has any ideas? If it is always suppose to be long maybe a good explanation as to why it has to be so complicated will also be appreciated.
I'm using Eclipse and the wsdl is SOAP.
JDK 6 comes with jax-ws, everything you need to develop a client for a web service.
I'm unable to find some simple enough examples to post , but start at https://jax-ws.dev.java.net/
Edit: here's a simple example - a client for this web service: http://xmethods.com/ve2/ViewListing.po?key=427565
C:\temp> md generated
C:\temp>"c:\Program Files\Java\jdk1.6.0_17"\bin\wsimport -keep -d generated http://www50.brinkster.com/vbfacileinpt/np.asmx?wsdl
Create PrimeClient.java which look like:
import javax.xml.ws.WebServiceRef;
import com.microsoft.webservices.*;
//the above namespace is from the generated code from the wsdl.
public class PrimeClient {
//Cant get this to work.. #WebServiceRef(wsdlLocation="http://www50.brinkster.com/vbfacileinpt/np.asmx?wsdl")
static PrimeNumbers service;
public static void main(String[] args) {
try {
service = new PrimeNumbers();
PrimeClient client = new PrimeClient();
client.doTest(args);
} catch(Exception e) {
e.printStackTrace();
}
}
public void doTest(String[] args) {
try {
System.out.println("Retrieving the port from the following service: " + service);
PrimeNumbersSoap pm = service.getPrimeNumbersSoap();
System.out.println("Invoking the getPrimeNumbersSoap operation ");
System.out.println(pm.getPrimeNumbers(100));
} catch(Exception e) {
e.printStackTrace();
}
}
}
Compile and run:
C:\temp>"c:\Program Files\Java\jdk1.6.0_17"\bin\javac -cp generated PrimeClient.java
C:\temp>"c:\Program Files\Java\jdk1.6.0_17"\bin\java -cp .;generated PrimeClient
Retrieving the port from the following service: com.microsoft.webservices.PrimeN
umbers#19b5393
Invoking the getPrimeNumbersSoap operation
1,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97
There are plugins for IDE's which generate the needed code to consume a web service for you.
After the plugin generates you the base methods you simply call a web service like that:
TransportServiceSoap service = new TransportServiceLocator().getTransportServiceSoap();
service.getCities();
Have a look at http://urbas.tk/index.php/2009/02/20/eclipse-plug-in-as-a-web-service-client/
There are three ways to write a web service client
Dynamic proxy
Dynamic invocation interface (DII)
Application client
Example for Dynamic Proxy Client
import java.net.URL;
import javax.xml.rpc.Service;
import javax.xml.rpc.JAXRPCException;
import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceFactory;
import dynamicproxy.HelloIF;
public class HelloClient {
public static void main(String[] args) {
try {
String UrlString = "Your WSDL URL"; //
String nameSpaceUri = "urn:Foo";
String serviceName = "MyHelloService";
String portName = "HelloIFPort";
System.out.println("UrlString = " + UrlString);
URL helloWsdlUrl = new URL(UrlString);
ServiceFactory serviceFactory =
ServiceFactory.newInstance();
Service helloService =
serviceFactory.createService(helloWsdlUrl,
new QName(nameSpaceUri, serviceName));
dynamicproxy.HelloIF myProxy =
(dynamicproxy.HelloIF)
helloService.getPort(
new QName(nameSpaceUri, portName),
dynamicproxy.HelloIF.class);
System.out.println(myProxy.sayHello("Buzz"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
I hope , this would solve your question.
The easiest I've found so far to use is the Idea IntelliJ wizard which - using Metro libraries - generate a very small code snippet which works fine with Java 6.

Categories

Resources