001/* 002 * Copyright 2020 Anyware Services 003 * 004 * Licensed under the Apache License, Version 2.0 (the "License"); 005 * you may not use this file except in compliance with the License. 006 * You may obtain a copy of the License at 007 * 008 * http://www.apache.org/licenses/LICENSE-2.0 009 * 010 * Unless required by applicable law or agreed to in writing, software 011 * distributed under the License is distributed on an "AS IS" BASIS, 012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 013 * See the License for the specific language governing permissions and 014 * limitations under the License. 015 */ 016package org.ametys.plugins.contentio.archive; 017 018import java.time.LocalDate; 019import java.time.LocalDateTime; 020import java.time.format.DateTimeFormatter; 021import java.util.Date; 022import java.util.Optional; 023import java.util.stream.IntStream; 024 025import javax.xml.transform.TransformerException; 026 027import org.apache.commons.lang3.StringUtils; 028import org.apache.xpath.XPathAPI; 029import org.apache.xpath.objects.XObject; 030import org.w3c.dom.Node; 031import org.w3c.dom.NodeList; 032 033import org.ametys.core.util.DateUtils; 034 035final class DomNodeHelper 036{ 037 private DomNodeHelper() 038 { } 039 040 static String nullableStringValue(Node node, String xpath) throws TransformerException 041 { 042 XObject xObject = XPathAPI.eval(node, xpath); 043 return xObject.getType() == XObject.CLASS_NULL ? null : xObject.str(); 044 } 045 046 private static Optional<String> _nonEmptyValue(Node node, String xpath) throws TransformerException 047 { 048 XObject xObject = XPathAPI.eval(node, xpath); 049 return Optional.of(xObject) 050 .filter(o -> XObject.CLASS_NULL != o.getType()) 051 .map(XObject::str) 052 .filter(StringUtils::isNotBlank); 053 } 054 055 static Date nullableDateValue(Node node, String xpath) throws TransformerException 056 { 057 return _nonEmptyValue(node, xpath) 058 .map(dateStr -> DateTimeFormatter.ISO_LOCAL_DATE.parse(dateStr, LocalDate::from)) 059 .map(DateUtils::asDate) 060 .orElse(null); 061 } 062 063 static Date nullableDatetimeValue(Node node, String xpath) throws TransformerException 064 { 065 return _nonEmptyValue(node, xpath) 066 .map(dateStr -> DateUtils.getISODateTimeFormatter().parse(dateStr, LocalDateTime::from)) 067 .map(DateUtils::asDate) 068 .orElse(null); 069 } 070 071 static String[] stringValues(Node node, String xpath) throws TransformerException 072 { 073 NodeList nodeList = XPathAPI.selectNodeList(node, xpath); 074 return IntStream.range(0, nodeList.getLength()) 075 .mapToObj(nodeList::item) 076 .map(Node::getTextContent) 077 .toArray(String[]::new); 078 } 079}