I have a preliminary MyService generated with the wsimport gradle task with provided wsdl location path file:/D:/someLocationWherePlacedMyWSDl.interface.v2.wsdl
public class MyService
extends Service
{
private final static URL MyService_WSDL_LOCATION;
private final static Logger logger = Logger.getLogger(com.google.services.MyService.class.getName());
static {
URL url = null;
try {
URL baseUrl;
baseUrl = com.google.services.MyService.class.getResource(".");
url = new URL(baseUrl, "file:/D:/someLocationWherePlacedMyWSDl.interface.v2.wsdl");
} catch (MalformedURLException e) {
logger.warning("Failed to create URL for the wsdl Location: 'file:/D:/someLocationWherePlacedMyWSDl.interface.v2.wsdl', retrying as a local file");
logger.warning(e.getMessage());
}
MyService_WSDL_LOCATION = url;
}
}
How can I change it? It happens because the file was generated in one environment and then the artifact (war) was moved to another server.
Any thoughts?
Yes, I get it. Locally everything works perfectly. But this file located inside war file and when Jenkins trying to get this file /var/distributives/myservice/tomcat-base/wsdl/someLocationWherePlacedMyWSDl.interface.v2.wsdl I get exception (No such file or directory). It looks like it could not see files inside war file. Any thoughts how can I handle this?
Use the constructor of your service class, MyService, to pass the wsdlLocation.
String WSDL_LOCATION = "http://server:port/localtionWSDL.interface.v2.wsdl";
try {
final URL url = new URL(WSDL_LOCATION);
final QName serviceName = new QName("http://mynamespace/", "MyService");
final MyService service = new MyService(url, serviceName);
port = service.getMyServicePort();
// Call some operation of WebService
} catch (final Exception e) {
// Handle the exception
}
I solved this problem with relative path. Here is the solution
#Value("classpath:com//google//resources//wsdl//myservice.interface.v2.wsdl")
public void setWsdlLocation(final Resource wsdlLocation)
{
m_wsdlLocation = wsdlLocation;
}
Related
I am using Grizzly to serve my REST service which can have multiple "modules". I'd like to be able to use the same base URL for the service and for static content so I can access all these urls:
http://host:port/index.html
http://host:port/module1/index.html
http://host:port/module1/resource
http://host:port/module2/index.html
http://host:port/module2/resource
The code I'm trying to set this up with looks like this:
private HttpServer createServer(String host, int port, ResourceConfig config)
{
HttpServer server = GrizzlyHttpServerFactory.createHttpServer(URI.create("http://" + host + ":" + port + "/"), config, false);
HttpHandler httpHandler = new CLStaticHttpHandler(HttpServer.class.getClassLoader(), "docs/");
server.getServerConfiguration().addHttpHandler(httpHandler, "/");
return server;
}
With this code, I am only able to see the html pages and I get a "Resource identified by path does not exist" response when I try to get my resources.
When I comment out the code to add the HttpHandler, then I am able to access my resources (but don't have the docs of course).
What do I need to do to access both my resources and my static content?
I ended up writing a service to handle static resources myself. I decided to serve my files from the file system, but this approach would also work for serving them from a jar - you'd just have to get the file as a resource instead of creating the File directly.
#Path("/")
public class StaticService
{
#GET
#Path("/{docPath:.*}.{ext}")
public Response getHtml(#PathParam("docPath") String docPath, #PathParam("ext") String ext, #HeaderParam("accept") String accept)
{
File file = new File(cleanDocPath(docPath) + "." + ext);
return Response.ok(file).build();
}
#GET
#Path("{docPath:.*}")
public Response getFolder(#PathParam("docPath") String docPath)
{
File file = null;
if ("".equals(docPath) || "/".equals(docPath))
{
file = new File("index.html");
}
else
{
file = new File(cleanDocPath(docPath) + "/index.html");
}
return Response.ok(file).build();
}
private String cleanDocPath(String docPath)
{
if (docPath.startsWith("/"))
{
return docPath.substring(1);
}
else
{
return docPath;
}
}
}
One thing you can do is run Grizzly as a servlet container. That way you can run Jersey as servlet filter, and add a default servlet to handle the static content. For example
public class Main {
public static HttpServer createServer() {
WebappContext context = new WebappContext("GrizzlyContext", "");
createJerseyFilter(context);
createDefaultServlet(context);
HttpServer server = GrizzlyHttpServerFactory
.createHttpServer(URI.create("http://localhost:8080/"));
context.deploy(server);
return server;
}
private static void createJerseyFilter(WebappContext context) {
ResourceConfig rc = new ResourceConfig().packages("com.grizzly.test");
// This causes Jersey to forward 404s to default servlet
// which will catch all the static content requests.
rc.property(ServletProperties.FILTER_FORWARD_ON_404, true);
FilterRegistration reg = context.addFilter("JerseyApp", new ServletContainer(rc));
reg.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), "/*");
}
private static void createDefaultServlet(WebappContext context) {
ArraySet<File> baseDir = new ArraySet<>(File.class);
baseDir.add(new File("."));
ServletRegistration defaultServletReg
= context.addServlet("DefaultServlet", new DefaultServlet(baseDir) {});
defaultServletReg.addMapping("/*");
}
public static void main(String[] args) throws IOException {
HttpServer server = createServer();
System.in.read();
server.stop();
}
}
You will need to add the Jersey Grizzly servlet dependency
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-grizzly2-servlet</artifactId>
<version>${jersey2.version}</version>
</dependency>
The only problem with this approach is that the default servlet is meant to serve files from the file system, not from the classpath, as you are currently trying to do. You can see in the createDefaultServlet method I just set the base directory to the current working directory. So that's where all your files would need to be. You can change it to "docs" so all your files would be in the docs folder, which would be in the current working directory.
If you want to read files from the classpath, you may need to implement your own servlet. You can look at the source code for DefaultServlet and try to modify it to serve from the classpath. You can also check out Dropwizard's AssetServlet, which already does serve content from the classpath.
Or you can just say forget it, and just serve from the file system :-)
i have placed the wsdl files in
E:/testworkspace/projectname/docroot
WEB-INF
src
com
test
wsdl
if i give the full path say wsdlLocation = "file:E:/testworkspace/projectname/docroot/WEB- INF/src/com/test/wsdl/some.wsdl" , it picks the WSDL file.
but i need to make generic something like directly fetching:
#WebServiceClient(name = "TestInterfaceService",
wsdlLocation = "WEB-INF/wsdl/some.wsdl",
targetNamespace = "http://www.google.com/job")
public class TestInterfaceService extends Service {
public final static URL WSDL_LOCATION;
public final static QName SERVICE = new QName("http://www.google.com/job", "TestInterfaceService");
public final static QName TestInterfaceSoapHttpPort = new QName("http://www.google.com/job", "TestInterfaceSoapHttpPort");
static {
URL url = null;
try {
url = new URL("WEB-INF/wsdl/some.wsdl");
} catch (MalformedURLException e) {
java.util.logging.Logger.getLogger(TestInterfaceService.class.getName())
.log(java.util.logging.Level.INFO,
"Can not initialize the default wsdl from {0}", "WEB-INF/wsdl/some.wsdl");
}
WSDL_LOCATION = url;
}
Can you please suggest how to pick WSDL files independently from that of my local system, currently it throws the error Can not initialize the default wsdl from WEB-INF/wsdl/some.wsdl
You need a valid URL string to be able to create a new URL. If your service does expose the URL, it might be an option to use that.
If your client is a web application, another option is to make the wsdl available via your application and reference it from there using http://localhost/app/some.wsdl
Hope that helps
Not sure what you are trying to achive here, the configuration: wsdlLocation = "WEB-INF/wsdl/some.wsdl" is perfectly fine as long as WSLD file is under WEB-INF/wsdl, if you placed the wsdl in WEB-INF/src/com/test/wsdl and specifying WSDL location like this: wsdlLocation = "WEB-INF/wsdl/some.wsdl - of course it won't work, add your WSDL in WEB-INF/wsdl and all will be fine.
I'm trying to use AntiSamy to prevent XSS attacks on my site. I downloaded the following jars and added them to "/WEB-INF/lib"
antisamy-1.5.3.jar
nekohtml.jar
xercesImpl-2.5.0.jar
along with a policy file antisamy-slashdot-1.4.4.xml in "/WEB-INF".
I tried to implement a filter through web.xml. A snippet of the servlet I'm using is
public class AntiSamyFilter implements Filter {
private static final Logger LOG = Logger.getLogger(AntiSamyFilter.class);
private final AntiSamy antiSamy;
public AntiSamyFilter() {
try {
URL url = this.getClass().getClassLoader().getResource("antisamy-slashdot-1.4.4.xml");
LOG.info("After getResource");
Policy policy = Policy.getInstance(url.getFile()); //Deployment fails
LOG.info("After Policy");
antiSamy = new AntiSamy(policy);
LOG.info("After antiSamy");
} catch (PolicyException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
The deployment fails after Policy policy = Policy.getInstance(url.getFile());. It's probably because of the path of the policy file.
Can someone please tell me where the policy file should be kept?
The url.getFile part fails because it couldn't find the antisamy-slashdot-1.4.4.xml file. I created a package in src/my/package and changed
URL url = this.getClass().getClassLoader().getResource("antisamy-slashdot-1.4.4.xml");
to
URL url = this.getClass().getClassLoader().getResource("/my/package/antisamy-slashdot-1.4.4.xml");
I also added batik.jar along with the other jar files. It solved my problem
I am using the following method to get a resource from WAR file in WildFly:
this.getClass().getResource(relativePath)
It works when the application is deployed as exploded WAR. It used to work with compressed WAR, too. Yesterday, I did a clean and rebuild of project in Eclipse, and it just stopped working.
When I check the resource root:
logger.info(this.getClass().getResource("/").toExternalForm());
I get this:
file:/C:/JBoss/wildfly8.1.0.CR1/modules/system/layers/base/org/jboss/as/ejb3/main/timers/
So, no wonder it doesn't work. It probably has something to do with JBoss module loading, but I don't know if this is a bug or normal behavior.
I found various similar problems on StackOverflow, but no applicable solution. One of the suggestions is to use ServletContext like so:
#Resource
private WebServiceContext wsContext;
...
ServletContext servletContext = (ServletContext)this.wsContext.getMessageContext()
.get(MessageContext.SERVLET_CONTEXT);
servletContext.getResource(resourcePath);
But, when I try to obtain MessageContext in this manner, I get an IllegalStateException. So I am basically stuck. Any ideas?
I ran into this same problem, and rather than define the resource as a shared module, I ended up working around this by using a ServletContextListener in my WAR.
In the contextInitialized method, I got the ServletContext from the ServletContextEvent and used its getResource("/WEB-INF/myResource") to get the URL to the resource inside my WAR file. It appears that in the ServletContextListener, the .getResource() method resolves as expected rather than to the "/modules/system/layers/base/org/jboss/as/ejb3/main/timers/" url. That URL can then be stored in the ServletContext for later use by your servlets or in an injected ApplicationScoped CDI bean.
#WebListener
public class ServletInitializer implements ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent sce) {
try {
final ServletContext context = sce.getServletContext();
final URL resourceUrl = context.getResource("/WEB-INF/myResource");
context.setAttribute("myResourceURL", resourceUrl);
} catch (final MalformedURLException e) {
throw new AssertionError("Resource not available in WAR file", e);
}
}
#Override
public void contextDestroyed(ServletContextEvent sce) {}
}
or
#WebListener
public class ServletInitializer implements ServletContextListener {
#Inject
private SomeApplicationScopedBean myBean;
#Override
public void contextInitialized(ServletContextEvent sce) {
try {
final ServletContext context = sce.getServletContext();
final URL resourceUrl = context.getResource("/WEB-INF/myResource");
myBean.setResourceUrl(resourceUrl);
} catch (final MalformedURLException e) {
throw new AssertionError("Resource not available in WAR file", e);
}
}
#Override
public void contextDestroyed(ServletContextEvent sce) {}
}
We had a similar problem and our fault was that we tried to access the static resource through the raw path instead of using the input stream the resource is providing - the following code works for us even when deploying a non-exploded .war-file.
final URL resource = this.getClass().getResource(FILE);
try (final InputStream inputStream = resource.openStream();
final InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
final BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
// Use bufferedReader to read the content
} catch (IOException e) {
// ...
}
I finally gave up and put my resource files in a new JBoss module, as described in this link.
https://community.jboss.org/wiki/HowToPutAnExternalFileInTheClasspath
It works, but the downside is that there are two deployment targets so things are more complicated. On the upside, the size of the WAR file is reduced, and I don't have to redeploy the application if only some of the resources have changed.
I was recently trying to figure out how to access a file within my own war in Java. The following is how the java classes and resources are packaged in the war file:
WAR
`-- WEB-INF
`-- classes (where all the java classes are)
`-- resourcefiles
`-- resourceFile1
My target file was resourceFile1. To get that file, I just did the following in code:
InputStream inStream = this.class.getClassLoader().getResourceAsStream("resourcefiles/resourceFile1");
In this case the resource files would need to be in the same folder as the classes folder containing the java classes. Hopefully others find this helpful.
This sample code works for wildfly deployed and tested on openshift.
I think it is a wildfly problem I downland wildfly and tried on local I also get the error.
Check sample project on github
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLConnection;
#Controller
#RequestMapping
public class FileDownloadController {
private static final Logger logger = LoggerFactory.getLogger(FileDownloadController.class);
private static final String DOC_FILE = "file/ibrahim-karayel.docx";
private static final String PDF_FILE = "file/ibrahim-karayel.pdf";
#RequestMapping(value = "/download/{type}", method = RequestMethod.GET)
public void downloadFile(HttpServletRequest request, HttpServletResponse response,
#PathVariable("type") String type) throws IOException {
File file = null;
InputStream inputStream;
if (type.equalsIgnoreCase("doc")) {
inputStream = getClass().getClassLoader().getResourceAsStream(DOC_FILE);
file = new File(Thread.currentThread().getContextClassLoader().getResource(DOC_FILE).getFile());
} else if (type.equalsIgnoreCase("pdf")) {
inputStream = getClass().getClassLoader().getResourceAsStream(PDF_FILE);
file = new File(Thread.currentThread().getContextClassLoader().getResource(PDF_FILE).getFile());
} else{
throw new FileNotFoundException();
}
if (file == null && file.getName() == null) {
logger.error("File Not Found -> " + file);
throw new FileNotFoundException();
}
String mimeType = URLConnection.guessContentTypeFromName(file.getName());
if (mimeType == null) {
System.out.println("mimetype is not detectable, will take default");
mimeType = "application/octet-stream";
}
System.out.println("mimetype : " + mimeType);
response.setContentType(mimeType);
/* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser
while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/
response.setHeader("Content-Disposition", String.format("inline; filename=\"" + file.getName() + "\""));
/* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*/
//response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
response.setContentLength(inputStream.available());
IOUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
inputStream.close();
}
}
Had the same issue with Wildfly and not-exploded WAR and using Spring and ServletContextResource I have got around it like this:
[org.springframework.core.io.]Resource resource = new ServletContextResource(servletContext, "WEB-INF/classes/resource.png");
In the same #Service class I also had:
#Inject
private ServletContext servletContext;
I decided so:
#Autowired
private final ApplicationContext ctx;
private final Path path = Paths.get("testfiles/load")
ctx.getRosource("classpath:" + path);
I read this solution, that lead us to use getResourceAsStream(...) instead of getResource() inside Wildfly. I just test it on Wildfly 19 with myApp.ear deployed from console.
first post here, I am creating a webservice client on Netbeans 7.0, followed all the steps and got the generated code (java-ws), I built the project (.WAR) on Windows and copied it to my testing server (JBOSS on Unix), when I run the client (Through my web browser) it generates the following error:
2011-05-25 13:20:31,272 WARN [org.jboss.ws.core.jaxws.spi.ServiceDelegateImpl] Cannot access wsdlURL: file:/C:/Documents%20and%20Settings/FRGHOSN/Desktop/pp.wsdl
2011-05-25 13:20:31,276 WARN [org.jboss.ws.core.jaxws.spi.ServiceDelegateImpl] Cannot get port meta data for: {http://77.246.32.166/}CuWebServiceSoap
Now I checked for solutions and someone suggested changing the generated WebService class
here is the part I was supposed to change:
#WebServiceClient(name = "CuWebService", targetNamespace = "http://xxx", wsdlLocation = "file:/C:/Documents%20and%20Settings/FRGHOSN/Desktop/pp.wsdl")
public class CuWebService
extends Service
{
private final static URL CUWEBSERVICE_WSDL_LOCATION;
private final static WebServiceException CUWEBSERVICE_EXCEPTION;
private final static QName CUWEBSERVICE_QNAME = new QName("http://xxx/", "CuWebService");
static {
URL url = null;
WebServiceException e = null;
try {
url = new URL("file:/C:/Documents%20and%20Settings/FRGHOSN/Desktop/pp.wsdl");
} catch (MalformedURLException ex) {
e = new WebServiceException(ex);
}
CUWEBSERVICE_WSDL_LOCATION = url;
CUWEBSERVICE_EXCEPTION = e;
}
I edited the URL to url= client.CuWebservice.class.getResource("/WEB-INF/wsdl/pp.wsdl")
and it's not working
Any suggestions? Thanks in advance