How to access ActionErrors programmatically? - struts

I know how to create ActionErrors, add some messages and display the messages in the JSP page.
I think ActionError is like a list of error message. Here is the method to threat error that my system uses:
My Action
ActionErrors errors = new ActionErrors();
errors.add("customerId", new ActionError("error.customerId.required"));
this.saveErrors(request, errors);
my current JSP
<html:errors />
suppose i want to create ArrayList (in Java) of the error message in the JSP page. How to do this without change anything in in my Action.
my proposed JSP
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<%
ArrayList<String> errMessage = new ArrayList<String>();
//foreach (ActionErrors.message as message){
// errMessage.add(message);
//}
%>
</body>
</html>
regards

Action
If you save the errors in the request scope, e.g.:
ActionErrors errors = new ActionErrors();
errors.add("usr", new ActionMessage("User required", false));
errors.add("pwd", new ActionMessage("errors.invalid", "Password"));
saveErrors(request, errors);
JSP
You can get the errors in your JSP in order to populate your array list in the following way:
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.Iterator"%>
<%#page import="org.apache.struts.Globals"%>
<%#page import="org.apache.struts.action.ActionErrors"%>
<%#page import="org.apache.struts.action.ActionMessage"%>
<%#page import="org.apache.struts.util.MessageResources"%>
<%
ArrayList<String> errMessage = new java.util.ArrayList<String>();
ActionErrors errors = (ActionErrors) request.getAttribute(Globals.ERROR_KEY);
Iterator<ActionMessage> iterator = errors.get();
MessageResources resources = (MessageResources) request.getAttribute(Globals.MESSAGES_KEY);
while (iterator.hasNext()) {
ActionMessage error = iterator.next();
if (error.isResource()) {
errMessage.add(resources.getMessage(error.getKey(), error.getValues()));
} else {
errMessage.add(error.getKey());
}
}
%>
NOTE: This code example use Struts 1.3.10.

Related

Unable to verify the first certificate with postman on new .Net 5 core project

i need an help.
So i've created a project .NET core 5 with HTTPS. The project is new new.
So added the TestController where on get request i will have:
// GET: api/<TestController>
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
So, if i call the api https://localhost:44310/api/test on the browser:
["value1","value2"]
//that works correctly
But if i call the url on postman i receive:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">
</HEAD>
<BODY>
<h2>Bad Request - Invalid Hostname</h2>
<hr>
<p>HTTP Error 400. The request hostname is invalid.</p>
</BODY>
</HTML>
My postman option:
and
and
and
where i'm wrong? I need to settings visual studio with other options? Maybe i need to use localhost certificate? Why i get this error only in postman and not by browser??

SolrJ CloudSolrClient connection error

I am struggling with indexing using Solrj.
I want to use SolrCloud and I set my connection like this :
SolrClient client = new CloudSolrClient.Builder().withSolrUrl("http://localhost:8983/solr/collectioname").build();
And I have this error. I checked evruwhere before posting here but I can't resolve it
Exception in thread "main" java.lang.RuntimeException: Couldn't initialize a HttpClusterStateProvider (is/are the Solr server(s), [http://localhost:8983/solr/collectioname], down?)
at org.apache.solr.client.solrj.impl.CloudSolrClient$Builder.build(CloudSolrClient.java:1496)
at indexsolr.<init>(indexsolr.java:29)
at LoadData.toIndex(LoadData.java:100)
at LoadData.loadDocuments(LoadData.java:72)
at IndexLaunch.main(IndexLaunch.java:12)
Caused by: org.apache.solr.client.solrj.impl.HttpSolrClient$RemoteSolrException: Error from server at http://localhost:8983/solr/collectioname: Expected mime type application/octet-stream but got text/html. <html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Error 404 Not Found</title>
</head>
<body><h2>HTTP ERROR 404</h2>
<p>Problem accessing /solr/collectioname/admin/collections. Reason:
<pre> Not Found</pre></p>
</body>
</html>
at org.apache.solr.client.solrj.impl.HttpSolrClient.executeMethod(HttpSolrClient.java:607)
at org.apache.solr.client.solrj.impl.HttpSolrClient.request(HttpSolrClient.java:255)
at org.apache.solr.client.solrj.impl.HttpSolrClient.request(HttpSolrClient.java:244)
at org.apache.solr.client.solrj.SolrClient.request(SolrClient.java:1219)
at org.apache.solr.client.solrj.impl.HttpClusterStateProvider.fetchLiveNodes(HttpClusterStateProvider.java:189)
at org.apache.solr.client.solrj.impl.HttpClusterStateProvider.<init>(HttpClusterStateProvider.java:64)
at org.apache.solr.client.solrj.impl.CloudSolrClient$Builder.build(CloudSolrClient.java:1494)
... 4 more
As mentioned in the previous answer, SolrJ uses the URL without the collection name in it (which I should have pointed out more directly):
final String solrUrl = "http://localhost:8983/solr";
return new HttpSolrClient.Builder(solrUrl)
.withConnectionTimeout(10000)
.withSocketTimeout(60000)
.build();
For SolrCloud you need to use CloudSolrClient. Depending on Solr version you are using you can create object of CloudSolrClient or you can use CloudSolrClient.Builder
This is how I did it.
Solr cloud just needs to take a list of urls as a parameter and not just a String url.
private static final String BASE_SOLR_URL = "http://localhost:8983/solr";
// or initialize a list of solr instances urls
#Bean(name = "solrCloudClient")
public static CloudSolrClient getCloudConnection() {
System.out.println("----Initializing cloud Solr Connection---");
List<String> solrCloudUrls = Arrays.asList(BASE_SOLR_URL); // or list of urls
CloudSolrClient client = new CloudSolrClient.Builder(solrCloudUrls).build();
client.setParser(new XMLResponseParser());
return client;
}

When I use forms authentication and add html attributes to html.beginfom and routeValue object I get nullRefrenceException

#using (Html.BeginForm("Login", "Account", new { returnUrl = #ViewContext.HttpContext.Request.UrlReferrer.PathAndQuery}, FormMethod.Post, new { #class = "loginForm" }))
{
#Html.ValidationSummary(false)
#Html.EditorForModel();
<input type="submit" value="Login" />
}
exception :
An exception of type 'System.NullReferenceException' occurred in
App_Web_qpa3itia.dll but was not handled in user code
Additional information: Object reference not set to an instance of an object.
UrlReferrer may be null. Need to handle that case.

Upload a file MVC 4 Web API .NET 4

I'm using the version of MVC that shipped with Visual Studio 2012 express. (Microsoft.AspNet.Mvc.4.0.20710.0)
I assume this is RTM version.
I've found plenty of examples online which all use this code:
public Task<HttpResponseMessage> PostFormData()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
// Read the form data and return an async task.
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
}
return Request.CreateResponse(HttpStatusCode.OK);
});
return task;
}
But this code always ends up in continueWith where t.IsFaulted == true. The exception reads:
Unexpected end of MIME multipart stream. MIME multipart message is not
complete.
Here is my client form. NOthing fancy, I want to do jquery form pluging for ajax upload, but I can't even get this way to work.
<form name="uploadForm" method="post" enctype="multipart/form-data" action="api/upload" >
<input type="file" />
<input type="submit" value="Upload" />
</form>
I've read that it is caused by the parser expecting /CR /LF at the end of each message, and that bug has been fixed in June.
What I cannot figure out is, if it was really fixed, why isn't it included this version of MVC 4? Why do so many examples on the internet tout that this code works when it does not in this version of MVC 4?
You are missing a name attribute on your file input.
<form name="uploadForm" method="post" enctype="multipart/form-data" action="api/upload" >
<input name="myFile" type="file" />
<input type="submit" value="Upload" />
</form>
Inputs without it will not get submitted by the browser. So your formdata is empty resulting in IsFaulted being asserted.

Jsp Connection Error

When im trying to run this code to establish a connection ...... this error is coming
Im using Apache-tomcat-7.0.8
org.apache.jasper.JasperException: Unable to compile class for JSP:
An error occurred at line: 1 in the jsp file: /test_conn.jsp
Connection cannot be resolved to a type
1: <% Connection connection = null; try { // Load the JDBC driver String driverName = "oracle.jdbc.driver.OracleDriver"; Class.forName(driverName);
2:
3: // Create a connection to the database
4: String serverName = "URL";
Code I've tried:
<%#page import="java.sql.*,java.io.*,java.text.*,java.util.*" %>
<%#page import="java.util.*" %>
<%
Connection connection = null;
out.println("Before try");
try {
String driverName = "oracle.jdbc.driver.OracleDriver";
Class.forName(driverName);
out.println("Entered try");
String url = "jdbc:oracle:thin:#:URL:port:sid";
String username = "usr";
String password = "pass";
connection = DriverManager.getConnection(url, username, password);
out.println("Successfully Connected");
}catch (SQLException e) {
out.println("Not Connected: "+ e.getMessage());
}
%>
You should have to use Servlet to write database code however you may import the java.sql package or use the Connection interface with fully qualified package name.
java.sql.Connection connection = null;
EDIT:
You need to copy the .jar (eg. for oracle 10g - ojdbc14.jar) into the WEB-INF/lib folder.
In JSP you forgot to include
<%#page import="java.sql.Connection"%>
Though, this is not good practice. You should write Servlet and DAO class to do this. JSP's are to write HTML.