Setting a JCR Date property - java

I'm having some trouble writing properties of a cq:PageContent. releaseDate (type Date) is giving me some trouble. The following method is from a sling-junit test where I'm calling from a #Before method.
private void setNewsReleaseDate(Resource res, int month)
throws InvalidDateException {
String date = "2014-%sT11:31:00.000-04:00"; //07-23
Calendar rd = DateUtil.parseISO8601(String.format(date, "0"+month+"-23")); //iso8601Date
ModifiableValueMap modMap = res.adaptTo(ModifiableValueMap.class);
if (modMap != null) {
modMap.put("releaseDate", rd); // this is a Date property
/* also tried below, which also fails
modMap.put("releaseDate", String.format(date, "0"+month+"-23"));
*/
}
}
I get this error...
Value for key releaseDate can't be put into node:java.util.GregorianCalendar[time=1406129460000,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="GMT-04:00",offset=-14400000,dstSavings=0,useDaylight=false,transitions=0,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2014,MONTH=6,WEEK_OF_.... ]

I changed the method by passing in the page, and then get the /jcr:content below the page that I wanted to edit the properties of...
private void setNewsReleaseDate(Page page, int month) throws InvalidDateException{
LOGGER.info("change prop at page path "+page.getPath());
Resource res = rr.getResource(page.getPath()+"/jcr:content");
String date = "2014-%sT11:31:00.000-04:00"; //07-23
Calendar rd = DateUtil.parseISO8601(String.format(date, "0"+month+"-23")); //iso8601Date
ModifiableValueMap modMap = res.adaptTo(ModifiableValueMap.class);
if (modMap != null) {
modMap.put("releaseDate", rd); // this is a Date property
modMap.put("notes", "hello"); // a string property
}
}

Related

Unparsable Date despite perfect format

I'm trying to parse a date departureTime:
String departureTime2, departureTime;
departureTime2 = departureTime = "2018-01-01 11:11:11.1";
Using the JUnit when method
when(bookingController.booking( departureTime, departureTime2).thenAnswer(new Answer<MockHttpSession>()
{
#Override
public MockHttpSession answer(InvocationOnMock invocation) throws Throwable
{
Object[] args = invocation.getArguments();
return (MockHttpSession) args[0];
}
});
My booking method in BookingController
#RequestMapping(value = "/bookingsingle", method = RequestMethod.POST)
public String bookingSingle(#RequestParam String departureTime,..)'
formats the date using
Date departureTimeAsDate = null;
DateFormat df = new SimpleDateFormat("yyyy-MM-dd kk:mm:ss.S", Locale.ENGLISH);
try { departureTimeAsDate = df.parse(departureTime); } catch (ParseException e) { e.printStackTrace(); }
However I receive the error
java.text.ParseException: Unparseable date: "2018-01-01 11:11:11.1"
The date appears to be in the perfect format, and upon using the same code in a Java fiddle tool it compiles, however in intellij it runs into the error. Any suggestions would be appreciated.
EDIT:
I believe the problem may lie somewhere in the passing of the String in the when() method. Note that booking() has many irrelevant parameters I have excluded.

How to implement triple or more segment navigation in OData 4

I'm working on rest serivce with OData v4 protocol using olingo. I got stack on navigation when i'v got let's say:
Company.svc/Departaments(x)/Employees(x)/BussinesTrips
In Olingo's tutorial there is an example where is 2 segments navigation. Where first segment is UriResourceEntitySet and second is UriResourceNavigation.
In the example, these two (especialy entitySet) are needed as parameters in method which gets related entity collection from storage.
In my example there is Company.svc/UriResourceEntitySet/UriResourceNavigation/UriResourceNavigation, what i can say from UriInfo parameter.
I'v no clue how to do that. Should i change the method or somehow force the penulimate segment to be EntitySet.
Thanks for intrest, and im wait for callback.
#Override
public void readEntityCollection(ODataRequest request, ODataResponse response, UriInfo uriInfo, ContentType responseFormat)
throws ODataApplicationException, ODataLibraryException {
String lastUri = "lastUriResource";
String sourceNavigationUri = "sourceUriResource";
EdmEntitySet responseEntitySet = null;
EntityCollection responseEntityCollection = null;
List<UriResource> resourcePaths = uriInfo.getUriResourceParts();
UriResource uriResource = resourcePaths.get(0);
if (!(uriResource instanceof UriResourceEntitySet)) {
throw new ODataApplicationException("Only EntitySet is supported", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ENGLISH);
}
UriResourceEntitySet uriResourceEntitySet = (UriResourceEntitySet) uriResource;
EdmEntitySet startEntitySet = uriResourceEntitySet.getEntitySet();
if (resourcePaths.size() == 1) {
responseEntitySet = startEntitySet;
responseEntityCollection = storage.readEntitySetData(responseEntitySet);
} else {
startEntitySet = Util.getNavigationTargetEntitySet(uriInfo);
HashMap<String, UriResource> uriResourceHashMap = Util.getLastNavigationAndItsSource(uriInfo);
UriResource lastUriResource = uriResourceHashMap.get(lastUri);
UriResource sourceUriResource = uriResourceHashMap.get(sourceNavigationUri);
EdmNavigationProperty edmNavigationProperty = null;
if (!(lastUriResource instanceof UriResourceNavigation)) {
throw new ODataApplicationException("Only navigation is supported", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ENGLISH);
}
edmNavigationProperty = ((UriResourceNavigation) lastUriResource).getProperty();
if (!(sourceUriResource instanceof UriResourceEntitySet)) {
throw new ODataApplicationException("Only Entity Set is supported", HttpStatusCode.NOT_IMPLEMENTED.getStatusCode(), Locale.ENGLISH);
}
uriResourceEntitySet = (UriResourceEntitySet) sourceUriResource;
startEntitySet = uriResourceEntitySet.getEntitySet();
responseEntitySet = Util.getNavigationTargetEntitySet(uriInfo);
EdmEntityType targetEntityType = edmNavigationProperty.getType();
List<UriParameter> keyParameters = uriResourceEntitySet.getKeyPredicates();
Entity sourceEntity = storage.readEntityData(startEntitySet, keyParameters);
if (sourceEntity == null) {
throw new ODataApplicationException("Entity not found", HttpStatusCode.NOT_FOUND.getStatusCode(), Locale.ROOT);
}
responseEntityCollection = storage.getRelatedEntityCollection(sourceEntity, targetEntityType);
}
ContextURL contextUrl = ContextURL.with().entitySet(responseEntitySet).build();
final String id = request.getRawBaseUri() + "/" + responseEntitySet.getName();
EntityCollectionSerializerOptions options = EntityCollectionSerializerOptions.with().id(id).contextURL(contextUrl).build();
EdmEntityType edmEntityType = responseEntitySet.getEntityType();
ODataSerializer serializer = odata.createSerializer(responseFormat);
SerializerResult serializerResult = serializer.entityCollection(serviceMetaData, edmEntityType, responseEntityCollection, options);
InputStream inputStream = serializerResult.getContent();
response.setContent(inputStream);
response.setHeader(HttpHeader.CONTENT_TYPE, responseFormat.toContentTypeString());
response.setStatusCode(HttpStatusCode.OK.getStatusCode());
}
}
Departaments(x) is UriResourceEntitySet. You probably got its EdmEntitySet. Let's say it is stored in prevEdmEntitySet variable.
Employees(x) is UriResourceNavigation. You should take its name and use it with the variable mentioned above:
String propName = uriResourceNavigation.getProperty().getName();
EdmEntitySet currEdmEntitySet = (EdmEntitySet) startEdmEntitySet.getRelatedBindingTarget(propName);
Then you should start the next iteration with prevEdmEntitySet=currEdmEntitySet and repeat for all the UriResourceNavigations (just one more time in your example).

After set the location, timezone can't convert

Below is my coding:
private final String TIME_ZONE_ID_TRKD_DEFAULT = "Etc/GMT";
private XMLGregorianCalendar getStartDateTime(boolean startFromZeroHour) {
XMLGregorianCalendar xmlCal = null;
try {
xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendar();
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
}
Calendar now = Calendar.getInstance(TimeZone.getTimeZone("Asia/Singapore"));
now.setTimeZone(TimeZone.getTimeZone(TIME_ZONE_ID_TRKD_DEFAULT));
xmlCal.setDay(now.get(Calendar.DAY_OF_MONTH));
xmlCal.setMonth(now.get(Calendar.MONTH) + 1);
xmlCal.setYear(now.get(Calendar.YEAR));
xmlCal.setTime(now.get(Calendar.HOUR_OF_DAY), now.get(Calendar.MINUTE), now.get(Calendar.SECOND));
please kindly advice why it can't convert, and how should i do..
The code cannot be compiled because of an error on the line, where you get the instance of the calendar. I believe you wanted to do this (probably just copy/paste error?):
Calendar now = Calendar.getInstance(TimeZone.getTimeZone("Asia/Singapore"));
A better approach might be the following:
private final String TIME_ZONE_ID_TRKD_DEFAULT = "Etc/GMT";
private XMLGregorianCalendar getStartDateTime(boolean startFromZeroHour) {
XMLGregorianCalendar xmlCal = null;
try {
xmlCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(new GregorianCalendar(TimeZone.getTimeZone(TIME_ZONE_ID_TRKD_DEFAULT)));
} catch (DatatypeConfigurationException e) {
e.printStackTrace();
}
xmlCal.setMillisecond(DatatypeConstants.FIELD_UNDEFINED);
xmlCal.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
if(startFromZeroHour){
xmlCal.setHour(0);
}
return xmlCal;
}
public static void main(String[] args) {
Bug b = new Bug();
XMLGregorianCalendar startDateTime = b.getStartDateTime(true);
System.out.println(startDateTime);
XMLGregorianCalendar startDateTime2 = b.getStartDateTime(false);
System.out.println(startDateTime2);
}
First we create a GregorianCalendar instance using your timezone constant. It represents the current time (now) if the default constructor is used.
Then we use it to initialize the XMLGregorianCalendar.
You don't want to have the milliseconds and the timezone part, so we just unset them using DatatypeConstants.FIELD_UNDEFINED as stated in the JavaDoc https://docs.oracle.com/javase/7/docs/api/javax/xml/datatype/XMLGregorianCalendar.html#setMillisecond(int) .
I added a part setting the hour to zero if startFromZeroHour is set to true. It was not part of your code so you might want to remove or change it.

Solrj Date request

How to request by date using SolrJ?
I get as a parameter a date in this format '01/10/2014'. Then I convert this format to a Date object and convert the object to a UTC format. Here is a code example of what I am doing :
public class DateHelper {
public static final String DD_MM_YYYY_FORMAT = "dd/MM/yyyy";
public static final String SOLR_DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss'Z'";
public static Date getDateFromString(String date, String format) {
if (StringUtils.isNotEmpty(date)) {
try {
return FastDateFormat.getInstance(format).parse(date);
} catch (ParseException e) {
LOGGER.error(e.getMessage());
}
}
return null;
}
public static String getStringFromDate(Date date, String format) {
if (date != null) {
try {
return FastDateFormat.getInstance(format).format(date);
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
}
return "";
}
public static void main(String...args){
Date dateFromString = DateHelper.getDateFromString('01/10/2014', DateHelper.DD_MM_YYYY_FORMAT);
String date = DateHelper.getStringFromDate(dateFromString, DateHelper.SOLR_DATE_FORMAT);
System.out.println(date);
}
}
This small program displays '2014-10-01T00:00:00Z'. When I try to submit this date in Solr using a filter query, I receive this error from Sorl :
org.apache.solr.client.solrj.impl.HttpSolrServer$RemoteSolrException: Invalid Date String:'2014-10-01T00'
Here is my Solr query :
SolrQuery solrQuery = new SolrQuery("*:*");
String date = String.format( "date:%s",dateInput);
query.addFilterQuery(date);
getSolrServer().query(solrQuery, METHOD.POST);
How can I solve this problem? THx for your help.
P.S : The class FastDateFormat is from Apache Commons Lang 3. I am using solr version 4.8.1.
This happens because of the way filterQuery is created:
String date = String.format( "date:%s",dateInput);
query.addFilterQuery(date);
That way the solr gets:
date:2014-10-01T00:00:00Z
And the exception is thrown because of the multiple : symbols that the Query Parser cannot parse correctly.
In order to fix it the special characters that are part of Query Syntax should be escaped.
From the java side it can be done this way (using ClientUtils.escapeQueryChars from SolrJ):
String date = String.format( "date:%s", ClientUtils.escapeQueryChars(dateInput));
query.addFilterQuery(date);
Syntax to query solr date field -- Date:[YYYY-MM-DDTHH:mm:ssZ]

PropertyNotFoundException occurs even when the getter is present

I am working on a small messaging web application to learn jsp's and servlets. I have a MessageModel class with the following properties :
String toAddress ;
String fromAddress;
String messageSubject;
String messageContent;
Timestamp messageTime;
int messageDraft;
And their corresponding setters for a jsp to access.
I have a method which queries a database with all the messages for the messages received to a particular address to display. It then creates a new MessageModel object and stores it in a ArrayList.
public static ArrayList<MessageModel> getReceivedMessages(String toAddress) throws SQLException, ClassNotFoundException{
// creates a arraylist.
ArrayList<MessageModel> msgList = new ArrayList<MessageModel>();
// Database connection code..
// The query which gets the required messages from the database and adds them to the list.
String query = "SELECT * FROM messages WHERE msg_to='" + toAddress +"' ORDER BY msg_date DESC";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if(rs.next()){
while(rs.next()){
String msgTo = rs.getString("msg_to");
String msgFrom = rs.getString("msg_from");
String msgSub = rs.getString("msg_subject");
String msgCnt = rs.getString("msg_matter");
Timestamp msgTime = rs.getTimestamp("msg_date");
MessageModel model = new MessageModel(msgTo,msgFrom,msgSub,msgCnt,msgTime);
msgList.add(model);
}
}
return msgList;
}
I call this method from the jsp and save the list as an attribute by using
String userName = (String) session.getAttribute("userId");
ArrayList<MessageModel> list = MessageModel.getReceivedMessages(userName);
pageContext.setAttribute("messageList", list);
But when I access the fromAddress property of the MesasgeModel objects in the list through a <c:forEach> tag, I get the following error :
javax.el.PropertyNotFoundException: Property 'fromAddress' not found on type com.email.system.MessageModel
This is the part of the HTML which access prints out the contents of each MessageModel object.
<c:forEach items="${messageList}" var="message">
<li><c:out value="${message.toAddress}"/>
<c:out value="${message.messageSubject}"/> <c:out value="${message.messageTime}"/>
<c:out value="${message.messageContent}"/> <c:out value="${message.fromAddress}"/> </li>
</c:forEach>
The error occurs whenever I try to access the toAddress field. The toAddress property is being stored int the messageSubject field even though when I try the same query in the mySql console I get the proper fields in their respective columns.
An exapmle result to the query where I removed the content column,
msg_id msg_to msg_from msg_subject msg_date msg_is_draft
4 bigb remember *subject* 2014-10-07 11:01:53 0
2 bigb remember *subject* 2014-10-07 10:48:43 0
1 bigb remember *subject* 2014-10-07 10:48:31 0
EDIT: This is the MessageModel class I have.
public class MessageModel {
String toAddress ;
String fromAddress;
String messageSubject;
String messageContent;
Timestamp messageTime;
int messageDraft;
public String getToAddress() {
return toAddress;
}
public String getFromAddress() {
return fromAddress;
}
public String getMessageSubject() {
return messageSubject;
}
public String getMessageContent() {
return messageContent;
}
public Timestamp getMessageTime() {
return messageTime;
}
public int getMessageDraft() {
return messageDraft;
}
public MessageModel(String toAddress,String fromAddress, String messageSubject, String messageContent,Timestamp messageTime){
this.toAddress = toAddress;
this.messageSubject = messageSubject;
this.messageContent = messageContent;
this.messageTime = messageTime;
this.fromAddress = fromAddress;
}
public void sendMessage(MessageModel model){
//Gets the related properties from the objects and stores it in the database
}
public static ArrayList<MessageModel> getReceivedMessages(String toAddress){
//Gets the messages sent to 'toAddress'
}
}
Turns out if you make some changes to any java source file which you use in you application you have to do a full rebuild and redeploy for the changes to take place.
There wasn't anything wrong in my code when I asked my question, instead of redeploying I was just updating resources. That only updates changes made to the JSP's not the java sources.

Categories

Resources