I'm using RESTEasy to write a example of WebService, and set the root resource path.But I find that even no root path in the url, I still can get the right resource.
Main function Code:
NettyJaxrsServer netty = new NettyJaxrsServer();
ResteasyDeployment deploy = new ResteasyDeployment();
List<Object> resources = new ArrayList<Object>();
resources.add(new UserService());
deploy.setResources(resources);
netty.setDeployment(deploy);
netty.setPort(8180);
netty.setRootResourcePath("/hello/");
netty.setSecurityDomain(null);
netty.start();
Service Code:
#Path("user")
#Produces(MediaType.APPLICATION_JSON)
public class UserService {
For the code, url /user can work normal, no need to add root path of /hello. I checked the source code; it adds the root path by itself.
source code:
public static String getEncodedPathInfo(String path, String contextPath)
{
if(contextPath != null && !"".equals(contextPath) && path.startsWith(contextPath))
path = path.substring(contextPath.length());
return path;
}
My question is why RESTEasy do this? I can't understand.
Related
I an creating an endpoint with spring boot...i can upload image to folder and save it via postman everythink works good.
i have a problem with get method when i am adding the value #RequestMapping value = "getImage/{imageName:.+}" in postman i add http://localhost:8080/api/images/getImage/{burger+png}
is that corect ???
#RequestMapping(value = "api/images")
public class ImageController {
#Autowired
public ImageService imageService;
#PostMapping(value ="upload")
public ResponseEntity uploadImage(#RequestParam MultipartFile file){
return this.imageService.uploadToLocalFileSystem(file);
}
#GetMapping(
value = "getImage/{imageName:.+}",
produces = {MediaType.IMAGE_JPEG_VALUE,MediaType.IMAGE_GIF_VALUE,MediaType.IMAGE_PNG_VALUE}
)
public #ResponseBody byte[] getImageWithMediaType(#PathVariable(name = "imageName") String fileName) throws IOException {
return this.imageService.getImageWithMediaType(fileName);
}
}
what should be the correct request url ???
It seems like it's reaching the backend fine, but failing to find path. Usually API endpoints end with parameters with a slug or query param. You can try either of the following to see if it works:
http://localhost:8080/api/images/getImage/burger.png
http://localhost:8080/api/images/getImage?imageName=burger.png
Keep in mind, you want to make sure that file exists at the path it's mentioning at the very top of the trace in the JSON response. This may depend on how you uploaded the file and with what name.
I am new to the game of web-service clients, and have generated code using the wsdl2java maven dependency.
I am packaging this project as a .war file.
My issue is that I do not know how to make the autogenerated client reach an endpoint across domains, and I also do not know how to set the client's wsdlLocation properly.
Starting with the latter:
Inside of the autogenerated service class, I found a static URL WSDL_LOCATION attribute, as well as 'parameters?' to a WebServiceClient annotation.
#WebServiceClient(name = "my_service",
wsdlLocation = "file:/c:/tmp/my_service.wsdl",
targetNamespace = "someAutoGenTargetNS/wsdl")
public class my_service_Service extends Service {
public final static URL WSDL_LOCATION;
public final static QName SERVICE = new QName("someAutoGenTargetNS/wsdl", "my_service");
public final static QName my_service = new QName("http://someAtuoGenTargetNS/wsdl", "my_service");
static {
URL url = null;
try {
url = new URL("file:/c:/tmp/my_service.wsdl");
} catch (MalformedURLException e) {
java.util.logging.Logger.getLogger(my_service_Service.class.getName())
.log(java.util.logging.Level.INFO,
"Can not initialize the default wsdl from {0}", "file:/c:/tmp/my_service.wsdl");
}
WSDL_LOCATION = url;
}
Currently, the WSDL_LOCATION url is always set to null, as it can not find the filepath specified (which is expected). I have the wsdl and xsd stored in the resources folder, but do not know how to specify the path to reach that. I have tried
new URL("file:/resources/my_service.wsdl")
new URL("file:/src/main/java/resources/my_service.wsdl")
new URL("classpath:my_service.wsdl")
and quite a few others. What is the correct way to do this, and if it requires an xml-catalog, where can I find documentation about where to put the catalog.xml file.
And now the former:
I believe my implementation to change the endpoint to the location I want is correct, and it is the wsdlLocation issue that is giving me a headache. Here is my implementation to change the endpoints. If this does not look right, simply point me in the direction of what to use, no need for a full implementation.
private static final QName SERVICE_NAME = new QName(""someAutoGenTargetNS/wsdl"", "my_service");
private URL wsdlURL = my_service_Service.WSDL_LOCATION;
my_service_Service ss;
my_service port;
public my_service_client()
{
//Redacted code for trusting all SSL Certs and hostnameVerifiers as it is not needed for the scope of this question
this.ss = new my_service_Service(this.wsdlURL,SERVICE_NAME);
this.port = ss.getMy_Service();
BindingProvider bp = (BindingProvider) this.port;
Map<String,Object> clientRequestContext = bp.getRequestContext();
clientRequestContext.put(BindingProvider.ENDPOINT_ADDRESS_PROPERTY, "https://New_Endpoint_IP");
//Basic auth header credentials
clientRequestContext.put(BindingProvider.USERNAME_PROPERTY,"username");
clientRequestContext.put(BindingProvider.PASSWORD_PROPERTY,"password");
}
Resources I attempted to understand prior to asking this question:
1
2
3
4
5
6
7+
8
Conclusively, I am coming to the realization I would much rather work with HTTP than SOAP, but legacy systems require legacy interaction.
Error's received that lead me to believe this is a wsdlURL issue:
javax.xml.ws.soap.SOAPFaultException: Internal Error (from client)
org.apache.cxf.binding.soap.SoapFault: Internal Error (from client)
Figured out the issue (4 days of tracking the problem later, and i can solve it shortly after asking the question here...)
This is indeed a valid way of setting the endpoint URL. That answers that question.
I adopted the classLoader.getResource approach from this reference to set the wsdlLocation
My new code became:
#WebServiceClient(name = "my_service",
wsdlLocation = "classpath:my_service.wsdl",
targetNamespace = "someAutoGenTargetNS/wsdl")
public class my_service_Service extends Service {
public final static URL WSDL_LOCATION;
public final static QName SERVICE = new QName("someAutoGenTargetNS/wsdl", "my_service");
public final static QName my_service = new QName("http://someAtuoGenTargetNS/wsdl", "my_service");
static {
URL url = null;
url = my_service.class.getClassLoader().getResource("my_service.wsdl");
WSDL_LOCATION = url;
}
Lastly I realized that the most basic web-service call I was trying to utilize was incorrectly setting the request body. I had set the request_body to null, in stead of instantiation a new instance of the request class that was autogenerated. This is what was throwing these two errors, but I am sure fixing the above helped lead me to the solution by enforcing my understanding of how these pieces work together.
I have an application running on embedded Tomcat and using Jersey. There is a resource class that exposes some endpoints, written like in this tutorial: http://www.sortedset.com/embedded-tomcat-jersey/. Everything is working fine, now I would like one of the endpoint methods to output formatted text.
My method in the resource looks like this:
#Path("/res")
#GET
#Produces("text/html")
public String get(){
return "<html><head><link rel='stylesheet' href='/style.css'></head><body>some text</body></html>";
}
}
I put the style.css in the WebContent folder.
When I access the resource, the text is displaying as expected, but the link to the .css file seams to have no effect.
What could be the problem?
Update
After Paul's suggestions in the comments, I tried to add the servlet context path the URL path, but it still is not working
1)
#Path("/res")
#GET
#Produces("text/html")
public String get(#Context ServletContext ctx) {
String ctxPath = ctx.getContextPath();
return "<html><head><link rel='stylesheet' href='+"ctxPath"+/style.css'></head><body>some text</body></html>";
}
}
2)
String ctxPath = ctx.getRealPath("/");
return "<html><head><link rel='stylesheet' href='+"ctxPath"+style.css'></head><body>some text</body></html>";
Update
Since the problem could be somewhere here, this is the part of the Main class, where I start the embedded Tomcat and set up the web application
public void start() {
String webappDirLocation = "WebContent/"
Tomcat tomcat = new Tomcat();
tomcat.setPort(0);
Context ctx = tomcat.addWebApp("", new File(webappDirLocation).getAbsolutePath());
Tomcat.addServlet(ctx, "jersey-container-servlet", resourceConfig()).addMapping("/*");
//start tomcat
}
private ServletContainer resourceConfig() {
return new ServletContainer(new ResourceConfig(new ResourceLoader().getClasses()));
}
i want to read file from controller like this:
#Controller
public class HomeController {
#RequestMapping(value = {"/"}, method = RequestMethod.GET)
public String showHomePage(ModelMap model) throws IOException, SAXException, ParserConfigurationException {
List<User> users = XmlParser.parse("Sum_and_clients.xml");
return "home";
}
But when I start the server it wants download it from apache-tomcat\bin. Despite the fact that Sum_and_clients.xml is located near the HomeController.java. How change this absoulte tomcat path, to path in my project?
I solved my problem.
URL url = HomeController.class.getResource("Sum_and_clients.xml");
File file = new File(url.getPath())
This file should be placed into [{Your project name}\target\ {Your project name} \WEB-INF\classes\ {Your package to HomeController}
I'm building a web service that's supposed to register on another server by sending its wsdl URL to that server.
I built a very basic web service in Netbeans,
#WebService
public class RegisterTest{
#WebMethod(operationName = "emphasize")
public String emphasize(#WebParam(name = "inputStr") String input){
return input + "!!!";
}
}
and Netbeans automatically directs me to localhost:8080/RegisterTest/RegisterTestService?Tester, and naturally, the wsdl can be found at localhost:8080/RegisterTest/RegisterTestService?wsdl.
How would I programmatically get this URL?
Edit:
I've noticed that the only place that seems to store this URL is the glassfish server itself. The context-root seems to only be found in glassfish/domain//config/domain.xml.
Is there a nice way of accessing the glassfish server APIs? I can easily get the endpoint address through the UI in applications > serviceName > View Endpoint, is there a programmatic way of doing this?
I've tried looking through asadmin commands, but can't seem to find anything there that gets the context-root or the endpoint URL either.
Untested, but should be pretty close to what you're looking for:
#WebService
public class RegisterTest
{
#Resource
private WebServiceContext context;
#WebMethod(operationName = "emphasize")
public String emphasize(#WebParam(name = "inputStr") String input)
{
return input + "!!!";
}
#WebMethod(operationName = "getWsdlUrl")
public String getWsdlUrl()
{
final ServletContext sContext = (ServletContext)
this.context.getMessageContext().get(MessageContext.SERVLET_CONTEXT);
final HttpServletRequest req = (HttpServletRequest)
this.context.getMessageContext().get(MessageContext.SERVLET_REQUEST);
final StringBuilder sb = new StringBuilder();
sb.append(req.isSecure() ? "https" : "http");
sb.append("://");
sb.append(req.getLocalName());
if ((req.isSecure() && req.getLocalPort() != 443) ||
(!req.isSecure() && req.getLocalPort() != 80))
{
sb.append(":");
sb.append(req.getLocalPort());
}
sb.append(sContext.getContextPath());
sb.append(RegisterTest.class.getSimpleName());
sb.append("Service?wsdl");
return sb.toString();
}
}