refactor: refactor the iCalendar tools

BREAKING CHANGES: The java classes just created, but not implemented yet, DO NOT USE THIS COMMIT TO BUILD!

[skip ci]
This commit is contained in:
Zihlu Wang
2024-05-08 10:47:33 +08:00
parent 163d8d3811
commit 77cc93405a
45 changed files with 921 additions and 769 deletions
@@ -0,0 +1,15 @@
package com.onixbyte.icalendar;
/**
* CalendarUtil
*
* @author Zihlu WANG
*/
public final class CalendarUtil {
private CalendarUtil() {
}
}
@@ -0,0 +1,113 @@
/*
* Copyright (C) 2023-2024 OnixByte.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.onixbyte.icalendar.component;
import com.onixbyte.icalendar.property.calendar.CalendarScale;
import com.onixbyte.icalendar.property.calendar.Method;
import com.onixbyte.icalendar.property.calendar.ProductIdentifier;
import com.onixbyte.icalendar.property.calendar.Version;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
/**
* {@code WebCalendar} class represents a web calendar in iCalendar format.
* <p>
* It allows users to create and customise calendar components and events and
* generate an <b>iCalendar</b> string containing all the calendar information.
* <p>
* Usage Example:
* <pre>
* WebCalendar calendar = new WebCalendar()
* .setName("My Web Calendar")
* .setCompanyName("CodeCrafters Inc.")
* .setProductName("WebCal")
* .setDomainName("codecrafters.org.cn")
* .setMethod("PUBLISH")
* .addEvent(event1)
* .addEvent(event2);
* String iCalendarString = calendar.resolve();
* </pre>
* <p>
* The {@code WebCalendar} class is designed to generate an iCalendar string
* conforming to the iCalendar specification, which can be used to share
* calendar data with other calendar applications or services.
*
* @author Zihlu Wang
* @version 1.1.0
* @since 1.0.0
*/
public final class Calendar {
private static final String COMPONENT_NAME = "VCALENDAR";
/**
* This property are OPTIONAL, but MUST NOT occur more than once.
*/
private CalendarScale scale;
/**
* This property are OPTIONAL, but MUST NOT occur more than once.
*/
private Method method;
/**
* This property are REQUIRED, but MUST NOT occur more than once.
*/
private ProductIdentifier productIdentifier;
/**
* This property are REQUIRED, but MUST NOT occur more than once.
*/
private final Version version = Version.VERSION_2_0;
private String calendarName;
private final List<CalendarComponent> components = new ArrayList<>();
/**
* Generate and resolve the iCalendar string for the web calendar.
*
* @return the resolved iCalendar string
*/
public String resolve() {
var calendarBuilder = new StringBuilder();
calendarBuilder.append("BEGIN:").append(COMPONENT_NAME).append('\n');
calendarBuilder.append(version.resolve()).append('\n');
calendarBuilder.append(productIdentifier.resolve()).append('\n');
calendarBuilder.append("X-WR-CALNAME:").append(calendarName).append('\n');
Optional.ofNullable(scale)
.ifPresent((_scale) -> calendarBuilder.append(_scale.resolve()).append('\n'));
Optional.ofNullable(method)
.ifPresent((_method) -> calendarBuilder.append(_method.resolve()).append('\n'));
if (!components.isEmpty()) {
for (var component : components) {
calendarBuilder.append(component.resolve()).append('\n');
}
}
calendarBuilder.append("END:").append(COMPONENT_NAME).append('\n');
return calendarBuilder.toString();
}
}
@@ -0,0 +1,35 @@
/*
* Copyright (C) 2023 CodeCraftersCN.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.onixbyte.icalendar.component;
/**
* The abstract sealed class {@code WebCalendarNode} represents a node in a web calendar, such as an <a href="">event</a>, a to-do
* item, or an alarm. It provides common properties and methods for all calendar components and events.
* <p>
* Subclasses of {@code WebCalendarNode} should implement the {@link #resolve()} method to generate the corresponding iCalendar content for the specific calendar component or event.
*
* @author Zihlu Wang
* @version 1.1.0
* @since 1.0.0
*/
public abstract class CalendarComponent {
public abstract String resolve();
}
@@ -0,0 +1,23 @@
package com.onixbyte.icalendar.component;
import com.onixbyte.icalendar.property.component.DateTimeStamp;
import com.onixbyte.icalendar.property.component.UniqueIdentifier;
/**
* Event
*
* @author Zihlu WANG
*/
public class Event extends CalendarComponent {
private DateTimeStamp dtStamp;
private UniqueIdentifier uid;
@Override
public String resolve() {
return "";
}
}
@@ -15,7 +15,7 @@
* limitations under the License. * limitations under the License.
*/ */
package com.onixbyte.webcal.config; package com.onixbyte.icalendar.config;
import java.time.ZoneOffset; import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter; import java.time.format.DateTimeFormatter;
@@ -23,11 +23,11 @@
* <p>The classes in this package include:</p> * <p>The classes in this package include:</p>
* <ul> * <ul>
* <li> * <li>
* {@link com.onixbyte.webcal.config.Classification}: An enum * {@link com.onixbyte.icalendar.config.Classification}: An enum
* representing the classification of events in the web calendar. * representing the classification of events in the web calendar.
* </li> * </li>
* </ul> * </ul>
* *
* @since 1.0.0 * @since 1.0.0
*/ */
package com.onixbyte.webcal.config; package com.onixbyte.icalendar.config;
@@ -0,0 +1,16 @@
package com.onixbyte.icalendar.constant;
public enum CalendarUserType {
INDIVIDUAL,
GROUP,
RESOURCE,
ROOM,
UNKNOWN,
;
@Override
public String toString() {
return name();
}
}
@@ -0,0 +1,36 @@
package com.onixbyte.icalendar.constant;
/**
* This property defines the access classification for a calendar component.
* <p>
* The property can be specified once in a {@link CalendarEvent CalEvent}, {@link
* com.onixbyte.icalendar.impl.CalTodo CalTodo}, or {@link com.onixbyte.icalendar.impl.CalJournal CalJournal}
* calendar properties.
*/
public enum Classification {
/**
* Public events mean that anyone can view and access their detailed information. These events are typically used
* in public calendars such as holiday calendars or company-wide event calendars. For public events, anyone with
* access to the calendar can see all the event details.
*/
PUBLIC,
/**
* Private events mean that only invited or specifically authorized individuals can view and access their detailed
* information. Private events are visible to the owner of the calendar but not to others. This classification is
* commonly used for personal appointments, private meetings, etc.
*/
PRIVATE,
/**
* Confidential events have detailed information that is not visible to anyone, including the owner of the calendar.
* Only individuals who have been granted specific permissions can access the detailed information of confidential
* events. This classification is typically used for sensitive business meetings, personal privacy matters, etc.
*/
CONFIDENTIAL,
;
@Override
public String toString() {
return name();
}
}
@@ -23,16 +23,16 @@
* The main classes and modules in this package include: * The main classes and modules in this package include:
* <ul> * <ul>
* <li> * <li>
* {@link com.onixbyte.webcal.WebCalendar}: A class for * {@link com.onixbyte.icalendar.component.Calendar}: A class for
* generating web calendars with customisable settings and events. * generating web calendars with customisable settings and events.
* </li> * </li>
* <li> * <li>
* {@link com.onixbyte.webcal.impl.WebCalendarEvent}: A class * {@link com.onixbyte.icalendar.impl.CalendarEvent}: A class
* representing a single event in a web calendar with various * representing a single event in a web calendar with various
* attributes and options. * attributes and options.
* </li> * </li>
* <li> * <li>
* {@link com.onixbyte.webcal.WebCalendarNode}: An abstract * {@link com.onixbyte.icalendar.component.CalendarComponent}: An abstract
* class serving as the base class for web calendar nodes, providing * class serving as the base class for web calendar nodes, providing
* common attributes and functionality for events. * common attributes and functionality for events.
* </li> * </li>
@@ -40,4 +40,4 @@
* *
* @since 1.0.0 * @since 1.0.0
*/ */
package com.onixbyte.webcal; package com.onixbyte.icalendar;
@@ -0,0 +1,7 @@
package com.onixbyte.icalendar.property;
public interface Prop {
String resolve();
}
@@ -0,0 +1,22 @@
package com.onixbyte.icalendar.property.calendar;
import com.onixbyte.icalendar.property.Prop;
/**
* CalendarScale
*
* @author Zihlu WANG
*/
public enum CalendarScale implements Prop {
GREGORIAN,
;
private static final String PROPERTY_NAME = "CALSCALE";
@Override
public String resolve() {
return PROPERTY_NAME + ':' + this.name();
}
}
@@ -0,0 +1,35 @@
package com.onixbyte.icalendar.property.calendar;
import com.onixbyte.icalendar.property.Prop;
public enum Method implements Prop {
PUBLISH("PUBLISH"),
REQUEST("REQUEST"),
REPLY("REPLY"),
ADD("ADD"),
CANCEL("CANCEL"),
REFRESH("REFRESH"),
COUNTER("COUNTER"),
DECLINE_COUNTER("DECLINECOUNTER"),
;
private final String label;
private static final String PROPERTY_NAME = "METHOD";
Method(String label) {
this.label = label;
}
@Override
public String toString() {
return label;
}
@Override
public String resolve() {
return PROPERTY_NAME + ":" + label;
}
}
@@ -0,0 +1,54 @@
package com.onixbyte.icalendar.property.calendar;
import com.onixbyte.icalendar.property.Prop;
/**
* ProductIdentifier
*
* @author Zihlu WANG
*/
public final class ProductIdentifier implements Prop {
private String value;
@Override
public String resolve() {
return PROPERTY_NAME + ":" + value + '\n';
}
public static class Builder {
private final ProductIdentifier productIdentifier;
private Builder() {
this.productIdentifier = new ProductIdentifier();
}
public Builder productIdentifier(String productIdentifier) {
this.productIdentifier.value = productIdentifier;
return this;
}
public Builder productIdentifier(String companyName, String productName) {
this.productIdentifier.value = "-//" + companyName + "//" + productName + "//EN";
return this;
}
public Builder productIdentifier(String companyName, String productName, String languageTag) {
this.productIdentifier.value = "-//" + companyName + "//" + productName + "//" + languageTag;
return this;
}
public ProductIdentifier build() {
return productIdentifier;
}
}
public static Builder builder() {
return new Builder();
}
private static final String PROPERTY_NAME = "PRODID";
private ProductIdentifier() {
}
}
@@ -0,0 +1,21 @@
package com.onixbyte.icalendar.property.calendar;
import com.onixbyte.icalendar.property.Prop;
/**
* Version
*
* @author Zihlu WANG
*/
public enum Version implements Prop {
VERSION_2_0,
;
@Override
public String resolve() {
return "VERSION:" + switch (this) {
case VERSION_2_0 -> "2.0";
};
}
}
@@ -0,0 +1,23 @@
package com.onixbyte.icalendar.property.component;
import com.onixbyte.icalendar.property.Prop;
import com.onixbyte.icalendar.property.parameter.FormatType;
import java.net.URI;
/**
* Attach
*
* @author Zihlu WANG
*/
public final class Attach implements Prop {
private FormatType formatType;
private URI uri;
@Override
public String resolve() {
return "";
}
}
@@ -0,0 +1,9 @@
package com.onixbyte.icalendar.property.component;
/**
* DateTimeCreated
*
* @author Zihlu WANG
*/
public final class DateTimeCreated {
}
@@ -0,0 +1,70 @@
package com.onixbyte.icalendar.property.component;
import com.onixbyte.icalendar.config.Formatters;
import com.onixbyte.icalendar.property.Prop;
import java.time.LocalDateTime;
/**
* In the case of an {@link com.onixbyte.icalendar.component.Calendar iCalendar} object that specifies a "{@link
* com.onixbyte.icalendar.property.calendar.Method Method}" property, this property specifies the date and time that
* the instance of the {@link com.onixbyte.icalendar.component.Calendar iCalendar} object was created. In the case of
* an {@link com.onixbyte.icalendar.component.Calendar iCalendar} object that doesn't specify a "{@link
* com.onixbyte.icalendar.property.calendar.Method Method}" property, this property specifies the date and time that
* the information associated with the calendar component was last revised in the calendar store.
* <p>
* The value MUST be specified in the UTC time format.
* <p>
* This property is also useful to protocols such as [2447bis] that have inherent latency issues with the delivery of
* content. This property will assist in the proper sequencing of messages containing {@link
* com.onixbyte.icalendar.component.Calendar iCalendar} objects.
* <p>
* In the case of an {@link com.onixbyte.icalendar.component.Calendar iCalendar} object that specifies a "{@link
* com.onixbyte.icalendar.property.calendar.Method Method}" property, this property differs from the "{@link
* DateTimeCreated CREATED}" and "{@link LastModified LAST-MODIFIED}" properties. These two properties are used to
* specify when the particular calendar data in the calendar store was created and last modified. This is different
* from when the {@link com.onixbyte.icalendar.component.Calendar iCalendar} object representation of the calendar
* service information was created or last modified.
* <p>
* In the case of an {@link com.onixbyte.icalendar.component.Calendar iCalendar} object that specifies a "{@link
* com.onixbyte.icalendar.property.calendar.Method METHOD}" property, this property is equivalent to the "{@link
* LastModified LAST-MODIFIED}" property.
*
* @author Zihlu WANG
*/
public final class DateTimeStamp implements Prop {
private static final String PROPERTY_NAME = "DTSTAMP";
private LocalDateTime value;
public DateTimeStamp(LocalDateTime value) {
this.value = value;
}
public DateTimeStamp() {
this.value = LocalDateTime.now();
}
@Override
public String resolve() {
return PROPERTY_NAME + ":" + Formatters.getUtcDatetimeFormatter().format(value) + '\n';
}
public static class Builder {
private final DateTimeStamp dateTimeStamp = new DateTimeStamp();
public Builder dateTimeStamp(LocalDateTime dateTime) {
this.dateTimeStamp.value = dateTime;
return this;
}
public DateTimeStamp build() {
return dateTimeStamp;
}
}
public static Builder builder() {
return new Builder();
}
}
@@ -0,0 +1,9 @@
package com.onixbyte.icalendar.property.component;
/**
* LastModified
*
* @author Zihlu WANG
*/
public final class LastModified {
}
@@ -0,0 +1,51 @@
package com.onixbyte.icalendar.property.component;
import com.onixbyte.icalendar.property.Prop;
/**
* UniqueIdentifier
*
* @author Zihlu WANG
*/
public final class UniqueIdentifier implements Prop {
private String value;
private UniqueIdentifier() {
}
private void setValue(String value) {
this.value = value;
}
public static class Builder {
private final UniqueIdentifier uniqueIdentifier;
private Builder() {
this.uniqueIdentifier = new UniqueIdentifier();
}
public Builder uniqueIdentifier(String uniqueIdentifier) {
this.uniqueIdentifier.value = uniqueIdentifier;
return this;
}
public Builder uniqueIdentifier(String uniqueIdentifier, String domainName) {
this.uniqueIdentifier.value = uniqueIdentifier + "@" + domainName;
return this;
}
public UniqueIdentifier build() {
return uniqueIdentifier;
}
}
public static Builder builder() {
return new Builder();
}
@Override
public String resolve() {
return "uid:" + this.value + '\n';
}
}
@@ -0,0 +1,9 @@
package com.onixbyte.icalendar.property.parameter;
/**
* AlarmTriggerRelationship
*
* @author Zihlu WANG
*/
public class AlarmTriggerRelationship {
}
@@ -0,0 +1,48 @@
package com.onixbyte.icalendar.property.parameter;
import com.onixbyte.icalendar.property.Prop;
import java.net.URI;
/**
* Alternate Text Representation specifies a URI that points to an alternate representation for a
* textual property value. A property specifying this parameter MUST also include a value that
* reflects the default representation of the text value. The URI parameter value MUST be specified
* in a quoted-string.
* <p>
* <b>Note</b>: While there is no restriction imposed on the URI schemes allowed for this
* parameter, Content Identifier (CID) [RFC 2392], HTTP [RFC 2616], and HTTPS [RFC 2818] are the
* URI schemes most commonly used by current implementations.
*
* @author Zihlu Wang
*/
public final class AlternateRepresentation implements Prop {
private static final String PROPERTY_NAME = "ALTREP";
private URI uri;
private AlternateRepresentation() {
}
public AlternateRepresentation setUri(String uri) {
this.uri = URI.create(uri);
return this;
}
public AlternateRepresentation setUri(URI uri) {
this.uri = uri;
return this;
}
public static AlternateRepresentation createInstance(String uri) {
var instance = new AlternateRepresentation();
instance.uri = URI.create(uri);
return instance;
}
@Override
public String resolve() {
return PROPERTY_NAME + "=\"" + uri.toString() + "\"";
}
}
@@ -0,0 +1,44 @@
package com.onixbyte.icalendar.property.parameter;
import com.onixbyte.icalendar.property.Prop;
/**
* CalendarUserType
*
* @author Zihlu WANG
*/
public enum CalendarUserType implements Prop {
/**
* An individual.
*/
INDIVIDUAL,
/**
* A group of individuals.
*/
GROUP,
/**
* A physical resource.
*/
RESOURCE,
/**
* A room resource.
*/
ROOM,
/**
* Otherwise not known.
*/
UNKNOWN,
;
private static final String PROPERTY_NAME = "CUTYPE";
@Override
public String resolve() {
return PROPERTY_NAME + "=" + this.name();
}
}
@@ -0,0 +1,35 @@
package com.onixbyte.icalendar.property.parameter;
import com.onixbyte.icalendar.property.Prop;
/**
* Common Name can be specified on properties with a CAL-ADDRESS value type. The parameter
* specifies the common name to be associated with the calendar user specified by the property.
* The parameter value is text. The parameter value can be used for display text to be associated
* with the calendar address specified by the property.
*
* @author Zihlu Wang
*/
public final class CommonName implements Prop {
private String value;
private CommonName() {
}
public CommonName setValue(String value) {
this.value = value;
return this;
}
public static CommonName createInstance(String commonName) {
var instance = new CommonName();
instance.value = commonName;
return instance;
}
@Override
public String resolve() {
return "CN=\"" + this.value + "\"";
}
}
@@ -0,0 +1,9 @@
package com.onixbyte.icalendar.property.parameter;
/**
* Delegate
*
* @author Zihlu WANG
*/
public class Delegatee {
}
@@ -0,0 +1,47 @@
package com.onixbyte.icalendar.property.parameter;
import com.onixbyte.icalendar.property.Prop;
import java.net.URI;
/**
* Delegator
*
* @author Zihlu WANG
*/
public final class Delegator implements Prop {
private static final String PROPERTY_NAME = "DELEGATED-FROM";
private URI calendarUserAddress;
private Delegator() {
}
private Delegator setCalendarUserAddress(String calendarUserAddress) {
this.calendarUserAddress = URI.create(calendarUserAddress);
return this;
}
private Delegator setCalendarUserAddress(URI calendarUserAddress) {
this.calendarUserAddress = calendarUserAddress;
return this;
}
private static Delegator initialiseInstance() {
return new Delegator();
}
public static Delegator createInstance(String calendarUserAddress) {
return initialiseInstance().setCalendarUserAddress(calendarUserAddress);
}
public static Delegator createInstance(URI calendarUserAddress) {
return initialiseInstance().setCalendarUserAddress(calendarUserAddress);
}
@Override
public String resolve() {
return PROPERTY_NAME + "=\"" + calendarUserAddress + "\"";
}
}
@@ -0,0 +1,9 @@
package com.onixbyte.icalendar.property.parameter;
/**
* DirectoryEntryReference
*
* @author Zihlu WANG
*/
public class DirectoryEntryReference {
}
@@ -0,0 +1,26 @@
package com.onixbyte.icalendar.property.parameter;
import com.onixbyte.icalendar.property.Prop;
/**
* FormatType
*
* @author Zihlu WANG
*/
public enum FormatType implements Prop {
JSON("application/json"),
;
private final String ianaRegistry;
FormatType(String ianaRegistry) {
this.ianaRegistry = ianaRegistry;
}
@Override
public String resolve() {
return "FMTTYPE:" + this.ianaRegistry;
}
}
@@ -0,0 +1,9 @@
package com.onixbyte.icalendar.property.parameter;
/**
* FreeBusyTimeType
*
* @author Zihlu WANG
*/
public class FreeBusyTimeType {
}
@@ -0,0 +1,9 @@
package com.onixbyte.icalendar.property.parameter;
/**
* GroupOrListMembership
*
* @author Zihlu WANG
*/
public class GroupOrListMembership {
}
@@ -0,0 +1,9 @@
package com.onixbyte.icalendar.property.parameter;
/**
* InlineEncoding
*
* @author Zihlu WANG
*/
public class InlineEncoding {
}
@@ -0,0 +1,9 @@
package com.onixbyte.icalendar.property.parameter;
/**
* Language
*
* @author Zihlu WANG
*/
public class Language {
}
@@ -0,0 +1,9 @@
package com.onixbyte.icalendar.property.parameter;
/**
* ParticipationRole
*
* @author Zihlu WANG
*/
public class ParticipationRole {
}
@@ -0,0 +1,9 @@
package com.onixbyte.icalendar.property.parameter;
/**
* ParticipationStatus
*
* @author Zihlu WANG
*/
public class ParticipationStatus {
}
@@ -0,0 +1,9 @@
package com.onixbyte.icalendar.property.parameter;
/**
* RecurrenceIdentifierRange
*
* @author Zihlu WANG
*/
public class RecurrenceIdentifierRange {
}
@@ -0,0 +1,9 @@
package com.onixbyte.icalendar.property.parameter;
/**
* RelationshipType
*
* @author Zihlu WANG
*/
public class RelationshipType {
}
@@ -0,0 +1,9 @@
package com.onixbyte.icalendar.property.parameter;
/**
* RsvpExpectation
*
* @author Zihlu WANG
*/
public class RsvpExpectation {
}
@@ -0,0 +1,9 @@
package com.onixbyte.icalendar.property.parameter;
/**
* SentBy
*
* @author Zihlu WANG
*/
public class SentBy {
}
@@ -0,0 +1,9 @@
package com.onixbyte.icalendar.property.parameter;
/**
* TimeZoneIdentifier
*
* @author Zihlu WANG
*/
public class TimeZoneIdentifier {
}
@@ -0,0 +1,9 @@
package com.onixbyte.icalendar.property.parameter;
/**
* ValueDataType
*
* @author Zihlu WANG
*/
public class ValueDataType {
}
@@ -1,215 +0,0 @@
/*
* Copyright (C) 2023 CodeCraftersCN.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.onixbyte.webcal;
import com.onixbyte.webcal.impl.WebCalendarEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
/**
* {@code WebCalendar} class represents a web calendar in iCalendar format.
* <p>
* It allows users to create and customise calendar components and events and
* generate an <b>iCalendar</b> string containing all the calendar information.
* <p>
* Usage Example:
* <pre>
* WebCalendar calendar = new WebCalendar()
* .setName("My Web Calendar")
* .setCompanyName("CodeCrafters Inc.")
* .setProductName("WebCal")
* .setDomainName("codecrafters.org.cn")
* .setMethod("PUBLISH")
* .addEvent(event1)
* .addEvent(event2);
* String iCalendarString = calendar.resolve();
* </pre>
* <p>
* The {@code WebCalendar} class is designed to generate an iCalendar string
* conforming to the iCalendar specification, which can be used to share
* calendar data with other calendar applications or services.
*
* @author Zihlu Wang
* @version 1.1.0
* @since 1.0.0
*/
public final class WebCalendar {
/**
* Constructor for WebCalendar class, initializes the list of calendar
* components and events.
*/
public WebCalendar() {
this.nodes = new ArrayList<>();
}
/**
* Set the name of the web calendar.
*
* @param name the name of the web calendar
* @return the WebCalendar object
*/
public WebCalendar setName(String name) {
this.name = name;
return this;
}
/**
* Set the company name associated with the web calendar.
*
* @param companyName the company name
* @return the WebCalendar object
*/
public WebCalendar setCompanyName(String companyName) {
this.companyName = companyName;
return this;
}
/**
* Set the domain name associated with the web calendar.
*
* @param domainName the domain name
* @return the WebCalendar object
*/
public WebCalendar setDomainName(String domainName) {
this.domainName = domainName;
return this;
}
/**
* Set the product name of the web calendar.
*
* @param productName the product name
* @return the WebCalendar object
*/
public WebCalendar setProductName(String productName) {
this.productName = productName;
return this;
}
/**
* Set the method for publishing the web calendar.
*
* @param method the publishing method
* @return the WebCalendar object
*/
public WebCalendar setMethod(String method) {
this.method = method;
return this;
}
/**
* Add an node to the web calendar.
*
* @param node the calendar component or event to be added
* @return the WebCalendar object
*/
public WebCalendar addNode(WebCalendarNode node) {
this.nodes.add(node);
return this;
}
/**
* Add an event to the web calendar.
*
* @param event the calendar component or event to be added
* @return the WebCalendar object
*/
public WebCalendar addEvent(WebCalendarEvent event) {
this.nodes.add(event);
return this;
}
/**
* Generate and resolve the iCalendar string for the web calendar.
*
* @return the resolved iCalendar string
*/
public String resolve() {
var eventBuilder = new StringBuilder();
if (!nodes.isEmpty()) {
for (var node : nodes) {
if (Objects.isNull(node.getDomainName()) || node.getDomainName().isBlank()) {
node.setDomainName(this.domainName);
}
eventBuilder.append(node.resolve());
}
}
return "BEGIN:" + TAG + "\n" +
"PRODID:-//" + companyName + "//" + productName + "//EN\n" +
"VERSION:" + version + "\n" +
"X-WR-CALNAME:" + name + "\n" +
eventBuilder + "\n" +
"END:" + TAG;
}
/**
* The {@code VCALENDAR} tag for iCalendar format
*/
private final static String TAG = "VCALENDAR";
/**
* The name of this calendar.
*/
private String name;
/**
* The company who produces this calendar.
* <p>
* This property will be used in {@code PRODID}.
*/
private String companyName;
/**
* The product name.
* <p>
* This property will be used in {@code PRODID}
*/
private String productName;
/**
* The producer's domain name.
*/
private String domainName;
/**
* Scale of this calendar.
*/
private final String scale = "GREGORIAN";
/**
* The method of this calendar.
*/
private String method;
/**
* The version of this calendar.
*/
private final String version = "2.0";
/**
* List of calendar components and events
*/
private final List<WebCalendarNode> nodes;
}
@@ -1,124 +0,0 @@
/*
* Copyright (C) 2023 CodeCraftersCN.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.onixbyte.webcal;
import com.onixbyte.webcal.config.Classification;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* The abstract sealed class {@code WebCalendarNode} represents a node in the
* web calendar, such as an event, a to-do item, or an alarm. It provides
* common properties and methods for all calendar components and events.
* <p>
* Subclasses of {@code WebCalendarNode} should implement the {@link
* #resolve()} method to generate the corresponding iCalendar content for the
* specific calendar component or event.
*
* @author Zihlu Wang
* @version 1.1.0
* @since 1.0.0
*/
public abstract class WebCalendarNode {
// Common properties for all calendar components and events
protected List<String> categories;
protected Classification classification;
protected String comment;
protected String description;
protected String location;
protected Integer percentComplete;
protected Integer priority;
protected String summary;
protected LocalDateTime end;
protected LocalDateTime start;
protected Duration duration;
protected String url;
protected String uid;
protected String domainName;
protected String timezone;
/**
* Constructor for WebCalendarNode class, initializes the list of
* categories associated with the calendar component or event.
*/
protected WebCalendarNode() {
this.categories = new ArrayList<>();
}
/**
* Set the domain name associated with the calendar component or event.
*
* @param domainName the domain name
* @return the WebCalendarNode object
*/
public WebCalendarNode setDomainName(String domainName) {
this.domainName = domainName;
return this;
}
/**
* Get the domain name.
*
* @return the domain name of this event
*/
public String getDomainName() {
return this.domainName;
}
/**
* Resolve the list of categories into a comma-separated string.
*
* @return the comma-separated string of categories
*/
protected String resolveCategories() {
var builder = new StringBuilder();
if (categories != null && !categories.isEmpty()) {
categories.forEach(item -> builder.append(item).append(","));
return builder.substring(0, builder.length() - 1);
}
return builder.toString();
}
/**
* Generate and resolve the iCalendar content for the calendar component or
* event.
*
* @return the resolved iCalendar content
*/
public abstract String resolve();
}
@@ -1,74 +0,0 @@
/*
* Copyright (C) 2023 CodeCraftersCN.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.onixbyte.webcal.config;
import lombok.Getter;
/**
* The {@code Classification} enum represents the classification levels of
* calendar content based on <b>RFC-5545</b>.
* <p>
* Calendar events or components can be classified as one of the following
* levels:
* <ul>
* <li>
* {@link #PUBLIC}: Indicates that the calendar content is public and
* can be freely distributed.
* </li>
* <li>
* {@link #PRIVATE}: Indicates that the calendar content is private and
* should not be shared with others.
* </li>
* <li>
* {@link #CONFIDENTIAL}: Indicates that the calendar content is
* confidential and should be kept strictly private.
* </li>
* </ul>
*
* @author Zihlu Wang
* @version 1.1.0
* @since 1.0.0
*/
public enum Classification {
/**
* Public classification level.
* <p>
* Indicates that the calendar content is public and can be freely
* distributed.
*/
PUBLIC,
/**
* Private classification level.
* <p>
* Indicates that the calendar content is private and should not be shared
* with others.
*/
PRIVATE,
/**
* Confidential classification level.
* <p>
* Indicates that the calendar content is confidential and should be kept
* strictly private.
*/
CONFIDENTIAL,
;
}
@@ -1,293 +0,0 @@
/*
* Copyright (C) 2023 CodeCraftersCN.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.onixbyte.webcal.impl;
import com.onixbyte.webcal.WebCalendarNode;
import com.onixbyte.webcal.config.Classification;
import com.onixbyte.webcal.config.Formatters;
import java.text.MessageFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Collection;
import java.util.Optional;
import java.util.UUID;
/**
* The {@code WebCalendarEvent} class represents an event in the web calendar.
* It extends the abstract class WebCalendarNode and provides additional
* methods to set properties specific to events.
* <p>
* Users can use the methods in this class to add categories, set the
* classification, add comments, descriptions, locations, set percent
* complete, set priority, set summary, set start time, set end time, set
* duration, set URL, set UID, and set timezone for the event. After setting
* the properties, users can call the {@link #resolve()} method to generate the
* corresponding iCalendar content for the event.
*
* @author Zihlu Wang
* @version 1.1.0
* @since 1.0.0
*/
public final class WebCalendarEvent extends WebCalendarNode {
/**
* Add categories to the event.
*
* @param categories the categories to add
* @return the WebCalendarEvent object
*/
public WebCalendarEvent addCategories(String... categories) {
this.categories.addAll(Arrays.asList(categories));
return this;
}
/**
* Add a collection of categories to the event.
*
* @param categories the collection of categories to add
* @return the WebCalendarEvent object
*/
public WebCalendarEvent addCategories(Collection<String> categories) {
this.categories.addAll(categories);
return this;
}
/**
* Add a single category to the event.
*
* @param category the category to add
* @return the WebCalendarEvent object
*/
public WebCalendarEvent addCategory(String category) {
this.categories.add(category);
return this;
}
/**
* Set the classification of the event.
*
* @param classification the classification to set
* @return the WebCalendarEvent object
*/
public WebCalendarEvent setClassification(Classification classification) {
this.classification = classification;
return this;
}
/**
* Set the comment for the event.
*
* @param comment the comment to set
* @return the WebCalendarEvent object
*/
public WebCalendarEvent setComment(String comment) {
this.comment = comment;
return this;
}
/**
* Set the description for the event.
*
* @param description the description to set
* @return the WebCalendarEvent object
*/
public WebCalendarEvent setDescription(String description) {
this.description = description;
return this;
}
/**
* Set the location for the event.
*
* @param location the location to set
* @return the WebCalendarEvent object
*/
public WebCalendarEvent setLocation(String location) {
this.location = location;
return this;
}
/**
* Set the percent complete for the event.
*
* @param percentComplete the percent complete to set
* @return the WebCalendarEvent object
* @throws IllegalArgumentException if the percent complete is out of range (0 ~ 100)
*/
public WebCalendarEvent setPercentComplete(Integer percentComplete) {
if (percentComplete < 0 || percentComplete > 100) {
throw new IllegalArgumentException("Percent out of range (0 ~ 100)");
}
this.percentComplete = percentComplete;
return this;
}
/**
* Set the priority for the event.
*
* @param priority the priority to set
* @return the WebCalendarEvent object
* @throws IllegalArgumentException if the priority is out of range (0 ~ 9)
*/
public WebCalendarEvent setPriority(Integer priority) {
if (priority < 0 || priority > 9) {
throw new IllegalArgumentException("The priority you provide is out of range (0 ~ 9).");
}
this.priority = priority;
return this;
}
/**
* Set the summary for the event.
*
* @param summary the summary to set
* @return the WebCalendarEvent object
*/
public WebCalendarEvent setSummary(String summary) {
this.summary = summary;
return this;
}
/**
* Set the end time for the event.
*
* @param end the end time to set
* @return the WebCalendarEvent object
* @throws IllegalStateException if the field DURATION has been set before
*/
public WebCalendarEvent setEnd(LocalDateTime end) {
if (this.duration != null) {
throw new IllegalStateException("You have set the field DURATION before, please remove it or remove setEnd.");
}
this.end = end;
return this;
}
/**
* Set the start time for the event.
*
* @param start the start time to set
* @return the WebCalendarEvent object
*/
public WebCalendarEvent setStart(LocalDateTime start) {
this.start = start;
return this;
}
/**
* Set the duration for the event.
*
* @param duration the duration to set
* @return the WebCalendarEvent object
* @throws IllegalStateException if the field END has been set before
*/
public WebCalendarEvent setDuration(Duration duration) {
if (this.end != null) {
throw new IllegalStateException("You have set the field END before, please remove it or remove setDuration.");
}
this.duration = duration;
return this;
}
/**
* Set the URL for the event.
*
* @param url the URL to set
* @return the WebCalendarEvent object
*/
public WebCalendarEvent setUrl(String url) {
this.url = url;
return this;
}
/**
* Set the UID for the event.
*
* @param uid the UID to set
* @return the WebCalendarEvent object
*/
public WebCalendarEvent setUid(String uid) {
this.uid = uid;
return this;
}
/**
* Set the domain name for the event.
*
* @param domainName the domain name to set
* @return the WebCalendarEvent object
*/
public WebCalendarEvent setDomainName(String domainName) {
this.domainName = domainName;
return this;
}
/**
* Set the timezone for the event.
*
* @param timezone the timezone to set
* @return the WebCalendarEvent object
*/
public WebCalendarEvent setTimezone(String timezone) {
this.timezone = timezone;
return this;
}
/**
* Generate and resolve the iCalendar content for the event.
*
* @return the resolved iCalendar content for the event
*/
@Override
public String resolve() {
var now = LocalDateTime.now().atZone(ZoneId.systemDefault());
return MessageFormat.format("""
BEGIN:{0}
UID:{1}
DTSTAMP:{2}
DTSTART:{3}
DURATION:PT{6}S
{4}{5}{7}{8}{9}{10}{11}{12}
END:{0}""",
/* 0 - tag */TAG,
/* 1 - uid */ Optional.ofNullable(uid).orElse(UUID.randomUUID().toString()) + "@" + domainName,
/* 2 - dtstamp */ now.format(Formatters.getUtcDatetimeFormatter()),
/* 3 - start time */ start.atZone(ZoneId.systemDefault()).format(Formatters.getUtcDatetimeFormatter()),
/* 4 - summary */ Optional.ofNullable(summary).map((item) -> "\nSUMMARY:" + item).orElse(""),
/* 5 - categories */ Optional.ofNullable(categories)
.map((item) -> !item.isEmpty() ? "\nCATEGORIES:" + resolveCategories() : null).orElse(""),
/* 6 - duration */ Optional.ofNullable(duration)
.map((_duration) -> String.valueOf(_duration.getSeconds()))
.orElse(Optional.ofNullable(end)
.map((_end) -> String.valueOf(Duration.between(_end, start).getSeconds()))
.orElse("0")),
/* 7 - classification */ Optional.ofNullable(classification).map((_classification) -> "\nCLASS:" + _classification + "\n").orElse(""),
/* 8 - comment */ Optional.ofNullable(comment).map((_comment) -> "\nCOMMENT:" + _comment + "\n").orElse(""),
/* 9 - location */ Optional.ofNullable(location).map((_location) -> "\nLOCATION:" + _location).orElse(""),
/* 10 = percentComplete */ Optional.ofNullable(percentComplete).map((_percentComplete) -> "\nPERCENT-COMPLETE:" + _percentComplete).orElse(""),
/* 11 - description */ Optional.ofNullable(description).map((_description) -> "\nDESCRIPTION:" + _description).orElse(""),
/* 12 - priority */ Optional.ofNullable(priority).map((_priority) -> "\nPRIORITY:" + _priority).orElse("")
);
}
private final static String TAG = "VEVENT";
}
@@ -0,0 +1,40 @@
/*
* Copyright (C) 2023 CodeCraftersCN.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.onixbyte.icalendar.test;
import com.onixbyte.icalendar.component.Calendar;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
import java.util.UUID;
/**
* TestWebCalendar
*
* @author Zihlu Wang
*/
@Slf4j
public class TestCalendar {
@Test
void testWebCalendar() {
}
}
@@ -1,56 +0,0 @@
/*
* Copyright (C) 2023 CodeCraftersCN.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.onixbyte.webcal.test;
import com.onixbyte.webcal.WebCalendar;
import com.onixbyte.webcal.impl.WebCalendarEvent;
import com.onixbyte.webcal.config.Classification;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import java.time.LocalDateTime;
import java.util.UUID;
/**
* TestWebCalendar
*
* @author Zihlu Wang
*/
@Slf4j
public class TestWebCalendar {
@Test
void testWebCalendar() {
var calendar = new WebCalendar();
calendar.setCompanyName("Code Crafters")
.setDomainName("codecrafters.org.cn")
.setName("Code Crafters SPECIAL EVENT")
.setProductName("Code Crafters SPECIAL EVENT");
calendar.addEvent(new WebCalendarEvent()
.setClassification(Classification.PUBLIC)
.setStart(LocalDateTime.of(2023, 8, 6, 0, 0, 0))
.setEnd(LocalDateTime.of(2023, 8, 6, 8, 0, 0))
.setLocation("Hong Kong University, Pokfulam, Central West, Hong Kong S.A.R")
.setUid(UUID.randomUUID().toString())
.setTimezone("Asia/Hong_Kong"));
System.out.println(calendar.resolve());
}
}