I have a Joda-DateTime field in my model and want to display it formatted in a JSP view. I have annotated it with the new #DateTimeFormat annotation:
public class Customer {
private DateTime dateOfBirth;
#DateTimeFormat(style="M-")
public DateTime getDateOfBirth() {
return dateOfBirth;
}
}
Now I want to display the dateOfBirth in my JSP:
Date of birth: ${customer.dateOfBirth}
But the result is unformatted:
Date of birth: 2010-08-11T11:23:30.148+02:00
After some research I found out, that I have to use the spring:bind-tag:
<spring:bind path="customer.dateOfBirth">
Date of birth: ${status.value}
</spring:bind>
With this it works. But it seems too complicated for this simple task. And using this method on lists is even more complicated since you have to integrate the list-index into the binding-path.
So my question is: Is there a simpler way to display a formatted value using the spring formatting-annotations?
Use the spring:eval tag which understands the #DateTimeFormat rule:
<spring:eval expression="customer.dateOfBirth" />
Alternatively, you can remove the #DateTimeFormat rule from your model all-together and use Joda's formatDate tag as Naikus illustrates.
In a future release, Spring plans to support plugging in "SpEL", which is the "Spring Expression Language" invoked by spring:eval, as the default Unified EL implementation for your JSP pages. This would allow in-line expressions like ${customer.dateOfBirth} to be routed through SpEL as well. You can vote up this enhancement request here: https://jira.spring.io/browse/SPR-7459.
Because its a joda datetime object, and not a Date object, you will have to write your own formatting function or a custom tag.
If you can convert it to java.util.Date somehow, then you can use the built in jstl's fmt taglibrary.
<fmt:formatDate value="${customer.dateOfBirth}" type="both"
pattern="MM-dd-yyyy" />
But the latest jsp quickly allows you to create custom tags.
Spring gives us the option to set global date-time formats via the application properties file. Just add this config to application.properties:
spring.mvc.format.date=yyyy-MM-dd
spring.mvc.format.date-time=yyyy-MM-dd HH:mm:ss
spring.mvc.format.time=HH:mm:ss
Related
My mongodb collection has startedAt and endedAt fields which are of Date data type. I want to find documents which has startedAt>endedAt.
To get the documents whose startedAt>endedAt I've written the below code snippet using Kotlin by using Ktor framework and KMongo
suspend fun findDataByStartedAt(): List<BatchScheduler> {
return batchDataCollection.find("{'startedAt':{${MongoOperator.gte}:new ISODate('endedAt')}}").toList()
}
But this is not returning me the document whose startedAt<endedAt.How should I achieve it?
i'm a kind of newbie using Apache Solr, and i'm indexing a document witch has list of complex objectslike this:
{
PropA: AnyValue,
PropB: [{p1:'v1', p2:'v2'}, {p1:'v3', p2:'v4'}],
PropC: [{p1:'v1', p2:'v2'}, {p1:'v3', p2:'v4'}]
}
When i send it to solr it will get tha same data but on a different format:
{
PropA: AnyValue,
PropB.p1: ['v1','v3']
PropB.p2: ['v2','v4']
PropC.p1: ['v1','v3']
PropC.p2: ['v2','v4']
}
This format is causing me problems on deserializing, is it possible or what can i do to to get Solr to return the object on the original format?
Do i have to specify something special at the schema level to support Subdocuments? i'm kinda lost on this.
Any ideas?
To get well formatted document from SOLR you can use carrot framework.
It easy to implement and you can generate XML or JSON format as par your custom requirement using XSLT.
I'm migrating a Subsonic project over to PetaPoco. When Subsonic pulls DateTime columns from the database, it's returning DateTime as DateTimeKind.Unspecified. When PetaPoco hydrates a POCO, it's setting DateTimes as UTC.
TopTen Software's website actually has a blog post mentioning this exact issue:
http://www.toptensoftware.com/Articles/84/PetaPoco-Value-Conversions-and-UTC-Times
But there is an annotation stating the solution outlined is obsolete, and links to another article mentioning mappers. I can't figure out how to add mappers to my solution to resolve this issue.
If you add this attribute to your POCO Object's DateTime Properties it will set the DateTimeKind to UTC for you (It doesn't do any conversions though).
[Column(ForceToUtc=true)]
Had to dig through the source to find this
To do the actual conversion to UTC, I modified PetaPoco:
PetaPoco.cs - Ln 3738
Change This:
return delegate(object src) { return new DateTime(((DateTime)src).Ticks, DateTimeKind.Utc); };
To This:
return delegate(object src) { return new DateTime(((DateTime)src).ToUniversalTime().Ticks, DateTimeKind.Utc); };
Just realized you were asking the opposite. I had to make these changes to get it to return proper UTC dates. You can modify PetaPoco to do the opposite with this code:
return delegate(object src) { return new DateTime(((DateTime)src).Ticks, DateTimeKind.Unspecified); };
I am a new to using Mongo DB and exploring the frameworks around for migrating from mysql to mongodb. So far from my findings I have been able to figure out SpringMongo as the best solution to my requirements.
The only problem is that instead of using a DSL based or abstract querying mechanism, I wished the framework allowed me to pass plain json string as arguments to the different methods exposed by the API(find, findOne) so that the query parameters can be written out to an external file (using a key to refer) and passed to the methods by reading and parsing at run time. But the framework should be capable of mapping the results to the domain objects.
Is there a way in spring-mongo to achieve this? Or is there any other frameworks on the same lines
You could use Spring Data to do that, just use the BasicQuery class instead of Query class. Your code will look like the following:
/* Any arbitrary string that could to parsed to DBObject */
Query q = new BasicQuery("{ filter : true }");
List<Entity> entities = this.template.find(q, Entity.class);
If you want more details:
http://static.springsource.org/spring-data/data-mongo/docs/current/reference/html/#mongo.query
http://static.springsource.org/spring-data/data-mongodb/docs/current/api/org/springframework/data/mongodb/core/query/BasicQuery.html
Well I got to find this one in the Spring data MongoOperations...
String jsonCommand = "{username: 'mickey'}";
MongoOperations mongoOps = //get mongooperations implemantation
mongoOps.executeCommand(jsonCommand)
It returns an instance of CommandResult that encapsulates the result.
I'm developing some RESTful services in WCF 4.0. I've got a method as below:
[OperationContract]
[WebGet(UriTemplate = "Test?format=XML&records={records}", ResponseFormat=WebMessageFormat.Xml)]
public string TestXml(string records)
{
return "Hello XML";
}
So if i navigate my browser to http://localhost:8000/Service/Test?format=XML&records=10, then everything works as exepcted.
HOWEVER, i want to be able to navigate to http://localhost:8000/Service/Test?format=XML and leave off the "&records=10" portion of the URL. But now, I get a service error since the URI doesn't match the expected URI template.
So how do I implement defaults for some of my query string parameters? I want to default the "records" to 10 for instance if that part is left off the query string.
Note: This question is out of date, please see the other answers.
This does not appear to be supported.
However, Microsoft has been made aware of this issue and there is a work-around:
You can get the desired effect by
omitting the Query string from the
UriTemplate on your WebGet or
WebInvoke attribute, and using
WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters
from within your handlers to inspect,
set defaults, etc. on the query
parameters.
https://connect.microsoft.com/VisualStudio/feedback/details/451296/
According to this answer this is fixed in .NET 4.0. Failing to supply the query string parameter seems to result in its being given the default value for the type.
Check this blog post out. Makes sense to me, and comes with a class to parse out the query string parameters.
http://blogs.msdn.com/b/rjacobs/archive/2009/02/10/ambiguous-uritemplates-query-parameters-and-integration-testing.aspx
Basically don't define the query string parameters in the UriTemplate so it matches with/without the parameters, and use the sample class to retrieve them if they're there in the method implementation.
This seems to work in WCF 4.0.
Just make sure to set your default value in your "Service1.svc.cs"
public string TestXml(string records)
{
if (records == null)
records = "10";
//... rest of the code
}
While this is an old question, we still come to this scenario from time to time in recent projects.
To send optional query parameters, I created WCF Web Extensions nuget package.
After installation, you can use the package like this:
using (var factory = new WebChannelFactory<IQueryParametersTestService>(new WebHttpBinding()))
{
factory.Endpoint.Address = new EndpointAddress(ServiceUri);
factory.Endpoint.EndpointBehaviors.Add(new QueryParametersServiceBehavior());
using (var client = factory.CreateWebChannel())
{
client.AddQueryParameter("format", "xml");
client.AddQueryParameter("version", "2");
var result = client.Channel.GetReport();
}
}
Server side you can retrieve the parameters using WebOperationContext:
WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters;