I am trying to invoke a locally stored html file using the get() method of the HtmlUnitDriver, but the page is not getting loaded. I tried to get the page source and I got 404 not found as the response. If I use the chrome driver in headless mode I am able to invoke the file. Is it possible to do this using HtmlUnitDriver?
Below is a code snippet
HtmlUnitDriver unitDriver = new HtmlUnitDriver();
public class Test {
public void clickOn() {
String filePath =
"home/test-output/100071234.html";
try {
unitDriver.get(filePath);
WebElement ele = unitDriver.findElement(By.id("submitPayment"));
ele.click();
} catch (Exception ex) {
ex.printStackTrace();
}
}
If you need to open local file you have to adhere the URI format. So for Linux it would be (if home folder is under the root folder):
String filePath =
"file:///home/test-output/100071234.html";
Here you can find other examples (Windows, Mac OS): https://en.wikipedia.org/wiki/File_URI_scheme
I'm trying to crawl a GitHub Wiki with JGit.
When I try it with one URL, it worked perfectly fine. Then I tried it with another random URL and got an error.
Please see the extract of my code:
import java.io.File;
import java.io.IOException;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.GitAPIException;
public class Main {
// with this URL I get an error
String url = "https://github.com/radiant/radiant.wiki.git";
// this URL works
// String url = "https://github.com/WardCunningham/Smallest-Federated-Wiki.wiki.git";
public static void main(String[] args) {
Main m = new Main();
m.jgitTest();
System.out.println("Done!");
}
public void jgitTest() {
try {
File localPath = File.createTempFile("TestGitRepository", "");
localPath.delete();
Git.cloneRepository().setURI(url).setDirectory(localPath).call();
} catch (IOException | GitAPIException e) {
System.err.println("excepton: " + e.getMessage());
e.printStackTrace();
}
}
}
This is the stack trace:
Exception in thread "main" org.eclipse.jgit.dircache.InvalidPathException: Invalid path (contains separator ':'): How-To:-Create-an-Extension.textile
at org.eclipse.jgit.dircache.DirCacheCheckout.checkValidPathSegment(DirCacheCheckout.java:1243)
at org.eclipse.jgit.dircache.DirCacheCheckout.checkValidPathSegment(DirCacheCheckout.java:1225)
at org.eclipse.jgit.dircache.DirCacheCheckout.checkValidPath(DirCacheCheckout.java:1185)
at org.eclipse.jgit.dircache.DirCacheCheckout.processEntry(DirCacheCheckout.java:311)
at org.eclipse.jgit.dircache.DirCacheCheckout.prescanOneTree(DirCacheCheckout.java:290)
at org.eclipse.jgit.dircache.DirCacheCheckout.doCheckout(DirCacheCheckout.java:408)
at org.eclipse.jgit.dircache.DirCacheCheckout.checkout(DirCacheCheckout.java:393)
at org.eclipse.jgit.api.CloneCommand.checkout(CloneCommand.java:236)
at org.eclipse.jgit.api.CloneCommand.call(CloneCommand.java:127)
at Main.jgitTest(Main.java:21)
at Main.main(Main.java:13)
If you visit the wiki page of the URL that doesn't work (https://github.com/radiant/radiant/wiki), you will find this page: How To: Create an Extension.
The title of this page is the cause of the error: Invalid path (contains separator ':'): How-To:-Create-an-Extension.textile.
I assume I need to escape all output.
I suppose you are on windows. You can't create a file on windows having the ":" in the name. JGit should handle it somehow, so I suppose this is a bug in JGit.
I had the same problem with pure git, and this answer helped me:
git config core.protectNTFS false
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.
I'm new with webservices. I am trying to access a webservice in java using netbeans.
I followed some tutorials and created a web application project, then created a web service client. Netbeans created an index.jsp file, where I can access the webservice perfectly, but I want to access the webservice thru a java class.
I created a java class file where I put the same code I have in the jsp page and I get the error :
"Exception in thread "main" javax.xml.ws.WebServiceException: Failed to access the WSDL at: http://...... It failed with:
Invalid WSDL http://..... , expected {http:// schemas.xmlsoap. org/wsdl/}definitions found HTML at (lineLine number = 1"
If I debug the jsp page, I get no errors, but I can't compile in java class. I don't understand!
This is my jsp code that works perfectly:
<%-- start web service invocation --%>
<%
try {
com.epq.tipocambio.TipoCambio service = new com.epq.tipocambio.TipoCambio();
com.epq.tipocambio.TipoCambioSoap port = service.getTipoCambioSoap();
com.epq.tipocambio.InfoVariable result = port.tipoCambioDia();
Float cambio = result.getCambioDolar().getVarDolar().get(0).getReferencia();
out.println("Cambio = " + cambio);
} catch (Exception ex) {
//TODO handle custom exceptions here
System.out.println(ex);
}
%>
And this is my java class code that is giving me the errors:
package com.epq.tipocambio;
public class EPQTipoCambioDia {
private static InfoVariable tipoCambioDia() {
com.epq.tipocambio.TipoCambio service = new com.epq.tipocambio.TipoCambio();
com.epq.tipocambio.TipoCambioSoap port = service.getTipoCambioSoap();
return port.tipoCambioDia();
}
public static void main(String[] args){
InfoVariable c = EPQTipoCambioDia.tipoCambioDia();
Float cambio = c.getCambioDolar().getVarDolar().get(0).referencia;
System.out.print(cambio);
}
}
Any Ideas of what could be the problem?
Does anyone know how to use the "Controlled Embedded Browser" in SWT, which allows page manipulation? I can only find info on how to use the normal SWT browser, but I need to be able to interact with the loaded page. Thank you. Like this -
http://publib.boulder.ibm.com/infocenter/btt/v7r0/index.jsp?topic=%2Fcom.ibm.btt.application_presentation.doc_7.0%2Fdoc%2Freference%2Frichclient%2Fcontrolembededbrowser.html - but there is no instruction on how to initiate such a class.
Here is an example from Eclipse SWT snippets website
Also this post might give you some insight on this.
Using Java Objects in JavaScript in Eclipse SWT Browser Control
To expose Java Object from Eclipse to JavaScript, you need to create a class that extends BrowserFunction. The constructor of this class takes two arguments; the first one is Browser instance and second one is name of the the function that will be available in JavaScript code running the SWT browser control... ...
Code snippet
BrowserFunction:
import java.io.File;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.browser.BrowserFunction;
public class ListFilesFunction extends BrowserFunction {
Browser browser = null;
String functionName = null;
public ListFilesFunction(Browser browser, String name) {
super(browser, name);
this.browser = browser;
this.functionName = name;
}
public Object function (Object[] args)
{
if (args.length == 0)
browser.execute("alert('Function " +
functionName + " requires one argument - parent folder path');");
File file = new File(args[0].toString());
if (!file.exists())
browser.execute("alert('Folder " + args[0] +
" does not exist');");
if (!file.isDirectory())
browser.execute("alert('Path " + args[0] + " must be a folder');");
return file.list();
}
}
associate this function with the browser control
public class View extends ViewPart
{
Browser browserCtl = null;
...
public void createPartControl(Composite parent) {
...
browserCtl = new Browser(parent, SWT.None);
new ListFilesFunction(browserCtl, "getFiles");
...
}
...
}
invoke this function from JavaScript:
<html>
<head>
<script type='text/javascript'>
files = getFiles("c:/");
for (i = 0; i < files.length; i++)
{
document.writeln(files[i] + "<br>");
}
</script>
</head>
<body>
</body>
</html>