I have a servlet which is supposed to process uploaded file. Apache common file upload library is used for that.
The problem is that file comes corrupted. Looks like symbols "~" are replaced on "?" in the file.
Here my html form is:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
</head>
<body>
<FORM action="http://localhost:8081/wihome-connector-bpm/bpmFileUpload"
enctype="multipart/form-data"
method="post">
What files are you sending?
<INPUT type="file" name="uploadedFiles"><BR>
<INPUT type="submit" value="Send">
<INPUT type="reset">
</FORM>
</body>
</html>
And that is the servlet:
public class FileUploadServlet extends HttpServlet {
private static final Log LOG = LogFactory.getLog(FileUploadServlet.class);
/**
* {#inheritDoc}
*/
#Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
try {
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
LOG.info("Uploading file: " + item.getName());
byte[] fileContents = IOUtils.toByteArray(item.getInputStream());
//...
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
I am trying to upload image
But instead I get that:
Can you please help me? What can be the problem?
Ok, there was a problem with filters. Project had a filter that currupted request before it rich servlet.
Related
I am try to test the login function using selenium but I get this exception :
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//input[#name='Guichet']"}
this my code :
public class LoginTest {
public static WebDriver driver;
#BeforeClass
public void testSetup() {
System.setProperty("webdriver.chrome.driver", "C:\\driver\\chromedriver.exe");
driver=new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
//driver.manage().window().maximize();
}
#BeforeMethod
public void openBrowser() {
driver.get("http:url");
System.out.println("We are currently on the following URL" +driver.getCurrentUrl());
}
#Test(description="This method validates the login functionality")
public void loginFunction() {
//WebDriverWait gui = new WebDriverWait(driver,100);
//Locating the email field element via Name tag and storing it in the webelement
WebElement guichet = driver.findElement(By.xpath("//input[#name='Guichet']"));
WebElement matricule = driver.findElement(By.name("Matricule"));
WebElement password = driver.findElement(By.name("Mot_de_passe"));
WebElement save = driver.findElement(By.name("Valider"));
//Entering text into the email field
guichet.sendKeys("0000");
matricule.sendKeys("login");
password.sendKeys("password");
save.click();
}
#AfterMethod
public void postLogin(){
System.out.println(driver.getCurrentUrl());
Assert.assertEquals(driver.getCurrentUrl(), "http:url.html");
}
#AfterClass
public void afterClass(){
//driver.quit();
}
}
NB : I tried to use the and xpath but still does not work also I try to using some solution in this Post but no result
This the Html page Using the frame for menu and other form login pages
SCT
:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<META name="GENERATOR" content="">
<META http-equiv="Content-Style-Type" content="text/css">
<TITLE>
</TITLE>
<LINK href="Master.css" rel="stylesheet" type="text/css">
</HEAD>
<FRAMESET rows="14%,78%" frameborder="NO" border="0">
<FRAME src="menu.html" scrolling="NO" name="entete">
<FRAME src="SCT.html">
<NOFRAMES>
<BODY BGCOLOR="#FFFFFF">
<P>L'affichage de cette page requiert un navigateur prenant en charge les
cadres.</P>
</BODY>
</NOFRAMES>
</FRAMESET>
</HTML>
driver.switchTo().frame(0);
WebElement guichet = driver.findElement(By.xpath("//input[#name='Guichet']"));
WebElement matricule = driver.findElement(By.name("Matricule"));
WebElement password = driver.findElement(By.name("Mot_de_passe"));
WebElement save = driver.findElement(By.name("Valider"));
//Entering text into the email field
guichet.sendKeys("0000");
matricule.sendKeys("login");
password.sendKeys("password");
save.click();
driver.switchTo().defaultContent();
In my .NET Core 2.2 website, I have a controller method within my BlogController that generates a sitemap.xml file:
public ActionResult SiteMap()
{
// logic here
return Content("<sitemap>...</sitemap>", "text/xml");
}
I have this route set up so that the sitemap will be output at https://mysite/sitemap
routes.MapRoute(
name: "sitemap",
template: "sitemap",
defaults: new { controller = "Blog", action = "SiteMap" });
That works, in that accessing /sitemap results in the XML content being served up.
However, when I access https://mysite/sitemap.xml, I get a 404 error.
I'm pretty sure this is something to do with static file handling, but I'm not sure how to set it up so that /sitemap.xml works.
You could try to dynamtically build xml like this
[Route("/sitemap.xml")]
public void SitemapXml()
{
string host = Request.Scheme + "://" + Request.Host;
Response.ContentType = "application/xml";
using (var xml = XmlWriter.Create(Response.Body, new XmlWriterSettings { Indent = true }))
{
xml.WriteStartDocument();
xml.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");
xml.WriteStartElement("url");
xml.WriteElementString("loc", host);
xml.WriteElementString("changefreq", "daily");
xml.WriteElementString("lastmod", DateTime.Now.ToString("yyyy-MM-dd"));
xml.WriteEndElement();
var categories = _categoryService.GetAllCategories(inclTopMenu: true);
foreach (var c in categories)
BuildXml(xml, c.GetSeName(), host);
xml.WriteEndElement();
}
}
private void BuildXml(XmlWriter xml, string url, string host)
{
xml.WriteStartElement("url");
xml.WriteElementString("loc", host + "/" + url);
xml.WriteElementString("changefreq", "weekly");
xml.WriteElementString("lastmod", DateTime.Now.ToString("yyyy-MM-dd"));
xml.WriteEndElement();
}
or create a page like https://forums.asp.net/t/2160949.aspx?Create+Robots+txt+and+sitemap+xml+dynamically+in+asp+net+core
Here is a simple demo about how to generate xml file to server and show xml file by using url like https://mysite/sitemap.xml:
1.View:
<form asp-action="Create" enctype="multipart/form-data">
<div class="form-group">
<input type="file" name="file" id="file" class="form-control" />
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
2.Controller:
public class UsersController : Controller
{
private IHostingEnvironment _env;
public UsersController(IHostingEnvironment env)
{
_env = env;
}
[HttpGet]
public IActionResult Create()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Create(IFormFile file)
{
var fileName = System.IO.Path.GetFileName(file.FileName);
var filePath = System.IO.Path.Combine(_env.WebRootPath, fileName);
if (file.Length > 0)
{
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
return View("Index");
}
}
3.Be sure to add app.UseStaticFiles(); like below,then you could access https://mysite/sitemap.xml:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//...
app.UseStaticFiles();
//...
}
4.Result:
This perplexes me. In the following code not even "1" is being printed out in the console. If i place a breakpoint (using eclipse) in the first system.out line, the debugger never exits it. No exceptions thrown. I also tried passing a null argument to SFU's constructor to force it to throw an exception, but nothing happened.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("1");
try {
ServletFileUpload upload = new ServletFileUpload();
} catch (Throwable e) {
throw new ServletException(e);
}
System.out.println("2");
}
And the html
<!DOCTYPE html>
<html lang="en">
<head>
<title>File Upload</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form method="POST" action="loadFile" enctype="multipart/form-data" >
<input type="file" name="myFile" id="myFile" /> <br/>
<input type="submit" value="Upload" name="upload" id="upload" />
</form>
</body>
</html>
try remove "throws ServletException, IOException" from
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
and change
try {
ServletFileUpload upload = new ServletFileUpload();
} catch (Throwable e) {
throw new ServletException(e);
}
to:
try {
ServletFileUpload upload = new ServletFileUpload();
//... rest of code
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
Add any other exceptions to the catch clause, don't throw them. That's why you don't see what the error is about
Also noticed that the name of your form action is loadFile
does this correspond to your Servlet name? Servlets usually have a capitalized first letter ! My suspicion is that this is the real problem, you're sending a post request to a servlet the server can't find.
So this is my first time building an Java EE application. I watched a lot of tutorials but most of them are using eclipse.
So the problem is this:
<h:panelGroup layout="block">
<p:commandButton ajax="false" action="#{loginBean.login()}"
styleClass="btn btn-info" value="Login" />
</h:panelGroup>
When I start Wildfly server and try to access the login page. If there are no
brackets after the login method I get:
The class 'LoginBean' does not have the property login.
If I try it with the brackets. The method is invoked when page is initialized and I get exception that the values for username and pass are null.
When I commented the method content I got the page to initialize properly, but another issue occured.
The JSF components like:
<h:panelGroup>
<h3 class="loginTitle">#{msgs['default.title']}</h3>
</h:panelGroup>
Are rendered correctly, but the Primefaces components
<h:panelGroup layout="block">
<p:inputText value="#{loginBean.username}" id="username"
styleClass="loginInputField" required="true"
requiredMessage="Username is required field">
<p:watermark for="username" value="Username" />
</p:inputText>
</h:panelGroup>
Are rendered with 0px height and width.
Here is my LoginBean.java
public class LoginBean implements Serializable {
private static final String SUCCESS_LOGIN_REDIRECT = "/pages/success?faces-redirect=true";
private static final String LOGIN_PAGE_REDIRECT = "/pages/login?faces-redirect=true";
private static final long serialVersionUID = 1L;
#Inject
private HttpServletRequest request;
private String username;
private String password;
#PostConstruct
public void init() {
//TODO
}
public String login() {
username = "";
password = "";
if(StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Invalid Credentials"));
return "";
} else if ("admin".equals(username) && "123".equals(password)) {
request.getSession().setAttribute("LOGGED_USER", username);
return SUCCESS_LOGIN_REDIRECT;
}
MessageUtils.addErrorMessage("login.error.invalid.credentials");
return "";
}
public String logout() {
request.getSession().invalidate();
return LOGIN_PAGE_REDIRECT;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
And last here is my project structure https://github.com/M-Veselinov/Java-EE
I think that I'm doing something wrong with web.xml or other config files, but I have no idea what.
I'll appreciate some help. Thanks.
Client Source:
<p:inputtext id="username" styleclass="loginInputField" required="true" requiredmessage="Username is required field">
<p:watermark for="username" value="Username"></p:watermark>
</p:inputtext>
I use the :contains() method but I get the error below:
Test Name: TheMahler3Test
Test FullName: TestingCssSelector.Mahler3.TheMahler3Test
Test Source: c:\Users\amahallati\Desktop\TestContainsSelector\TestingCssSelector\Mahler3.cs : line 50
Test Outcome: Failed
Test Duration: 0:00:05.135
Result Message: System.InvalidOperationException : An invalid or illegal string was specified
Result StackTrace:
at OpenQA.Selenium.Support.UI.DefaultWait1.PropagateExceptionIfNotIgnored(Exception e)
at OpenQA.Selenium.Support.UI.DefaultWait1.Until[TResult](Func`2 condition)
at TestingCssSelector.Mahler3.TheMahler3Test() in c:\Users\amahallati\Desktop\TestContainsSelector\TestingCssSelector\Mahler3.cs:line 59
This is the page's source code:
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<div id="myDiv">
<select name="mySelectInput">
<option value="">Select one...</option>
<option value="1">AT&T</option>
<option value="2">TMobile</option>
</select>
</div>
</div>
</body>
</html>
And this is the WebDriver C# code:
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
using OpenQA.Selenium.Support.UI;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Interactions;
namespace TestingCssSelector
{
[TestFixture]
public class Mahler3
{
private IWebDriver driver;
private StringBuilder verificationErrors;
private string baseURL;
private bool acceptNextAlert = true;
[SetUp]
public void SetupTest()
{
driver = new FirefoxDriver();
baseURL = "http://localhost:49638/";
verificationErrors = new StringBuilder();
}
[TearDown]
public void TeardownTest()
{
try
{
driver.Quit();
}
catch (Exception)
{
// Ignore errors if unable to close the browser
}
Assert.AreEqual("", verificationErrors.ToString());
}
[Test]
public void TheMahler3Test()
{
driver.Navigate().GoToUrl(baseURL + "/");
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(40));
wait.Until(d =>
{
return driver.FindElement(By.XPath("/html/body/div/div/select"));
});
driver.FindElement(By.XPath("/html/body/div/div/select")).Click();
wait.Until(d =>
{
return driver.FindElement(By.CssSelector("option:contains('AT&T')"));
});
driver.FindElement(By.CssSelector("option:contains('AT&T')")).Click();
// ERROR: Caught exception [ReferenceError: selectLocator is not defined]
}
private bool IsElementPresent(By by)
{
try
{
driver.FindElement(by);
return true;
}
catch (NoSuchElementException)
{
return false;
}
}
private bool IsAlertPresent()
{
try
{
driver.SwitchTo().Alert();
return true;
}
catch (NoAlertPresentException)
{
return false;
}
}
private string CloseAlertAndGetItsText()
{
try
{
IAlert alert = driver.SwitchTo().Alert();
string alertText = alert.Text;
if (acceptNextAlert)
{
alert.Accept();
}
else
{
alert.Dismiss();
}
return alertText;
}
finally
{
acceptNextAlert = true;
}
}
}
}
contains is not part of the CSS selector specification and is therefore not going to work.
The contains selector we all know and love comes from Sizzle, the CSS-selector engine behind jQuery. Unless you wish to physically load Sizzle or jQuery into your page, then you are not going to be able to use your current solution.
The only real way of doing text-based searching is using XPath, or find a list of elements (using anyway you like) and filtering them within code.
For your basic page, it's easy enough to simply select it by ID, so simply:
Select select = new Select(driver.FindElement(By.Id("mySelectInput")));
You would then select it by using:
select.SelectByVisibleText("AT&T");