Content type not working in struts - struts

This is written in my validate method. The check for size and empty upload is working but content type is not, am i missing something ?
public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
if(file1.getFileSize()==0)
{
errors.add("file1", new ActionMessage("error.file.required"));
}
else if(!file1.getContentType().equals("audio/mpeg"));
{
errors.add("file1",new ActionMessage("error.file.type"));
}
if(file1.getFileSize()>51200)
{
errors.add("file1",new ActionMessage("error.file.size"));
}
return errors;

I think your else if condition statement is missing because of ";" sign as the following :
else if(!file1.getContentType().equals("audio/mpeg"));
It should be as the following :
else if(!file1.getContentType().equals("audio/mpeg"))

done with:
else if(!file1.getContentType().equals("audio/mp3")) { ---- }
I checked the type of the the fileuploaded by: String ctype = file1.getContentType(); without puting any validation (i.e upload any file) and printed it on the jsp page. From there i came to know that its audio/mp3. Now all validations are working. /

Related

Use specific status code error page in area | Asp.net core

I manage status codes error using
app.UseStatusCodePagesWithRedirects("/StatusCodeError/{0}");
But when an error occurs in the area, the page is redirected out of the area and shows the general error page.
How do I make sure that an area-specific error page is displayed if an error occurs in the area?
There is no extensibility point to modify the behavior of app.UseStatusCodePagesWithRedirects, the location is formatted internally using string.Format and with only one argument passed in the placeholder {0} for the status code. So at the calling time (passing in the location format), we have no understanding about the area which is a route value available only in the context of a request processing. So you can refer to the source for StatusCodePagesExtensions and can see that UseStatusCodePagesWithRedirects just depends on an overload of the extension method StatusCodePagesExtensions.UseStatusCodePages, you can freely copy the code and modify it to make another version of UseStatusCodePagesWithRedirects that accepts a location format which supports some arguments from the route values.
Here I've made a simple one for you:
public static class StatusCodePagesApplicationBuilderExtensions
{
public static IApplicationBuilder UseStatusCodePagesWithRouteDataAndRedirects(this IApplicationBuilder app, string locationFormat)
{
if (app == null)
{
throw new ArgumentNullException(nameof(app));
}
var shouldPrependPathBase = locationFormat.StartsWith("~");
locationFormat = shouldPrependPathBase ? locationFormat.Substring(1) : locationFormat;
return app.UseStatusCodePages(context =>
{
//here is the point we can evaluate for the actual location
//by replacing the placeholders with route value
var location = Regex.Replace(locationFormat, #"\{[^}]+\}", m => {
//ignore the placeholder for status code
if (m.Value == "{0}") return m.Value;
var routeKey = m.Value.Trim('{', '}');
var routeValue = context.HttpContext.GetRouteValue(routeKey);
return routeValue?.ToString();
});
location = string.Format(CultureInfo.InvariantCulture, location, context.HttpContext.Response.StatusCode);
location = (shouldPrependPathBase ? context.HttpContext.Request.PathBase : PathString.Empty) + location;
context.HttpContext.Response.Redirect(location);
return Task.CompletedTask;
});
}
}
Now you can include any route data in the location format, in your case you just need the area, so the code will be like this:
app.UseStatusCodePagesWithRouteDataAndRedirects("/{area}/StatusCodeError/{0}");
NOTE: be careful with redirecting, you may encounter an error saying something like too many redirects, that's because of redirecting to a URL which in return causes a loop of redirects.

How do I display only one validation error in form?

I have several input fields in registration form.
For example, there are 5 fields. 'Email' and "Phone Number" fields are wrong, I do not want to display both validation errors. I only want to check "Email" field and display Email error, if it will be correctly written on second try, only then 'Password' error message can appear.
Can I accomplish it with server-side validation only?
Screenshot: Both validation errors are displayed at the same time.
You can dynamically modify the ModelState and check the errors :
if (ModelState.IsValid)
{
....
}
else
{
var flag = false;
foreach (var modelState in ViewData.ModelState.Values)
{
if (flag)
{
modelState.Errors.Clear();
}
if (modelState.Errors.Count >0)
{
flag = true;
}
if (modelState.Errors.Count>1)
{
var firstError = modelState.Errors.First();
modelState.Errors.Clear();
modelState.Errors.Add(firstError);
}
}
}
return View("index", movie);
Set maximum model validation errors to 1 in stratup, the validation process stops when max number is reached (200 by default):
services.AddMvc(options =>
{
options.MaxModelValidationErrors = 1;
})
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
but in this case it will stop on the first error even if there is more than one validation error on the same property (e.g. password length is not valid, password must contain upper case letter, etc...).
If you need to show all errors at once for each property you will need another solution.
ref: https://learn.microsoft.com/en-us/aspnet/core/mvc/models/validation?view=aspnetcore-2.2

YII2 problem with permissions and CAN function

I have a YII2 advanced template application with a function:
public function isVisible()
{
if ($return = \Yii::$app->getUser()->can($this->getWidgetPermission())) {
return true;
} else {
return false;
}
}
This function is not behaving the expected way with a specific permission, if I add the following code to print all user permissions and the involved permission:
public function isVisible()
{
if ($return = \Yii::$app->getUser()->can($this->getWidgetPermission())) {
return true;
} else {
pr($this->getWidgetPermission() ,'NON ALLOWED!');
pr(\Yii::$app->authManager->getPermissionsByUser(\Yii::$app->getUser()->getId()));
return false;
}
}
I get the name of the permission with the first pr() and an array of permissions with the second pr().
What is odd: the array of permissions INCLUDES the first one.
For example:
output of first pr():
backend\modules\m3p2\widgets\icons\WidgetIconProjects
output of second pr():
[
..,
[name] => backend\modules\m3p2\widgets\icons\WidgetIconProjects
..,
]
So IN THEORY:
\Yii::$app->getUser()->can($this->getWidgetPermission()
should return TRUE, but it's not!
Am I missing something obvious here?
BTW: I flushed permissions and nothing changed
Turned out the problem was in the cache.
I don't know why but both:
php yii cache/flush rbacCache and
php yii cache/flush-all
didn't clean the cache at all.
I had to manually delete the Cache files (in my case inside /runtime/rbacCache/rb/)

How to upload file in jhipster form?

I am just starting to use jhipster 5 and angular 5. I have a form and in that form in addition to few regular fields, I have a file input.
I could not find any documentation on how to file in jhipster.
EDIT 1:
I could somehow managed to upload file and send to server. Below is my server method to handle the form submission.
#PostMapping("/email-jobs")
#Timed
public ResponseEntity<EmailJobDTO> createEmailJob(MultipartFile file, #Valid #RequestBody EmailJobDTO emailJobDTO) throws URISyntaxException {
log.debug("REST request to save EmailJob : {}", emailJobDTO);
if (emailJobDTO.getId() != null) {
throw new BadRequestAlertException("A new emailJob cannot already have an ID", ENTITY_NAME, "idexists");
}
System.out.println(file.getName() + " File Name ");
EmailJobDTO result = emailJobService.save(emailJobDTO);
return ResponseEntity.created(new URI("/api/email-jobs/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
Here i get following exception,
Unsupported Media Type: Content type 'multipart/form-data;boundary=----WebKitFormBoundary73sdwuJtdeRk6xsO;charset=UTF-8' not supported
If I remove #RequestBody from method signature then I dont get above exception but then I start getting 400 bad request exception saying my form fields can not be null.
You must define MultipartFile is #RequestParam and declare produces = MediaType.APPLICATION_JSON_VALUE in post mapping, like:
#PostMapping("/email-jobs", produces = MediaType.APPLICATION_JSON_VALUE)
Client side, you can try send request as this:
Upload.upload({
url: 'api/path',
data: {
file: yourdatafile
},
headers: {'Content-Type': 'multipart/form-data'}
}).progress(function (evt) {
// handle progress
}).success(function (data, status, headers, config) {
// handle success
});
Instead of uploading a file, create a field type as a BLOB and then in your business logic, make a file if u need or else do your.

Understanding seam filter url-pattern and possible conflicts

I made a custom editor plugin, in a Seam 2.2.2 project, which makes file upload this way:
1) config the editor to load my specific xhtml upload page;
2) call the following method inside this page, and return a javascript callback;
public String sendImageToServer()
{
HttpServletRequest request = ServletContexts.instance().getRequest();
try
{
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
processItems(items);//set the file data to specific att
saveOpenAttachment();//save the file to disk
}
//build callback
For this to work I have to put this inside components.xml:
<web:multipart-filter create-temp-files="false"
max-request-size="1024000" url-pattern="*"/>
The attribute create-temp-files do not seems to matter whatever its value.
But url-pattern has to be "" or "/myUploadPage.seam", any other value makes the item list returns empty. Does Anyone know why?
This turns into a problem because when I use a url-pattern that work to this case, every form with enctype="multipart/form-data" in my application stops to submit data. So I end up with other parts of the system crashing.
Could someone help me?
To solve my problem, I changed the solution to be like Seam multipart filter handle requests:
ServletRequest request = (ServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
try
{
if (!(request instanceof MultipartRequest))
{
request = unwrapMultipartRequest(request);
}
if (request instanceof MultipartRequest)
{
MultipartRequest multipartRequest = (MultipartRequest) request;
String clientId = "upload";
setFileData(multipartRequest.getFileBytes(clientId));
setFileContentType(multipartRequest.getFileContentType(clientId));
setFileName(multipartRequest.getFileName(clientId));
saveOpenAttachment();
}
}
Now I handle the request like Seam do, and do not need the web:multipart-filter config that was breaking other types of request.