index
int64
0
0
repo_id
stringlengths
9
205
file_path
stringlengths
31
246
content
stringlengths
1
12.2M
__index_level_0__
int64
0
10k
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/writer/WriterOptions.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.writer; import org.apache.abdera.i18n.text.io.CompressionUtil.CompressionCodec; public interface WriterOptions extends Cloneable { /** * When writing, use the specified compression codecs */ CompressionCodec[] getCompressionCodecs(); /** * When writing, use the specified compression codecs */ WriterOptions setCompressionCodecs(CompressionCodec... codecs); Object clone() throws CloneNotSupportedException; /** * The character encoding to use for the output */ String getCharset(); /** * The character encoding to use for the output */ WriterOptions setCharset(String charset); /** * True if the writer should close the output stream or writer when finished */ boolean getAutoClose(); /** * True if the writer should close the output stream or writer when finished */ WriterOptions setAutoClose(boolean autoclose); }
7,200
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/Feed.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import java.util.Comparator; import java.util.List; import org.apache.abdera.i18n.iri.IRISyntaxException; /** * <p> * Represents an Atom Feed Element * </p> * <p> * Per RFC4287: * </p> * * <pre> * The "atom:feed" element is the document (i.e., top-level) element of * an Atom Feed Document, acting as a container for metadata and data * associated with the feed. Its element children consist of metadata * elements followed by zero or more atom:entry child elements. * * atomFeed = * element atom:feed { * atomCommonAttributes, * (atomAuthor* * &amp; atomCategory* * &amp; atomContributor* * &amp; atomGenerator? * &amp; atomIcon? * &amp; atomId * &amp; atomLink* * &amp; atomLogo? * &amp; atomRights? * &amp; atomSubtitle? * &amp; atomTitle * &amp; atomUpdated * &amp; extensionElement*), * atomEntry* * } * * This specification assigns no significance to the order of atom:entry * elements within the feed. * * The following child elements are defined by this specification (note * that the presence of some of these elements is required): * * o atom:feed elements MUST contain one or more atom:author elements, * unless all of the atom:feed element's child atom:entry elements * contain at least one atom:author element. * o atom:feed elements MAY contain any number of atom:category * elements. * o atom:feed elements MAY contain any number of atom:contributor * elements. * o atom:feed elements MUST NOT contain more than one atom:generator * element. * o atom:feed elements MUST NOT contain more than one atom:icon * element. * o atom:feed elements MUST NOT contain more than one atom:logo * element. * o atom:feed elements MUST contain exactly one atom:id element. * o atom:feed elements SHOULD contain one atom:link element with a rel * attribute value of "self". This is the preferred URI for * retrieving Atom Feed Documents representing this Atom feed. * o atom:feed elements MUST NOT contain more than one atom:link * element with a rel attribute value of "alternate" that has the * same combination of type and hreflang attribute values. * o atom:feed elements MAY contain additional atom:link elements * beyond those described above. * o atom:feed elements MUST NOT contain more than one atom:rights * element. * o atom:feed elements MUST NOT contain more than one atom:subtitle * element. * o atom:feed elements MUST contain exactly one atom:title element. * o atom:feed elements MUST contain exactly one atom:updated element. * * If multiple atom:entry elements with the same atom:id value appear in * an Atom Feed Document, they represent the same entry. Their * atom:updated timestamps SHOULD be different. If an Atom Feed * Document contains multiple entries with the same atom:id, Atom * Processors MAY choose to display all of them or some subset of them. * One typical behavior would be to display only the entry with the * latest atom:updated timestamp. * </pre> */ public interface Feed extends Source { /** * Returns the complete set of entries contained in this feed * * @return A listing of atom:entry elements */ List<Entry> getEntries(); /** * Adds a new Entry to the <i>end</i> of the Feeds collection of entries * * @param entry Add an entry */ Feed addEntry(Entry entry); /** * Adds a new Entry to the <i>end</i> of the Feeds collection of entries * * @return A newly created atom:entry */ Entry addEntry(); /** * Adds a new Entry to the <i>start</i> of the Feeds collection of entries * * @param entry An atom:entry to insert */ Feed insertEntry(Entry entry); /** * Adds a new Entry to the <i>start</i> of the Feeds collection of entries * * @return A newly created atom:entry */ Entry insertEntry(); /** * Creates a Source element from this Feed * * @return Returns a copy of this atom:feed as a atom:source element */ Source getAsSource(); /** * Sorts entries by the atom:updated property * * @param new_first If true, entries with newer atom:updated values will come first */ Feed sortEntriesByUpdated(boolean new_first); /** * Sorts entries by the app:edited property. if app:edited is null, use app:updated */ Feed sortEntriesByEdited(boolean new_first); /** * Sorts entries using the given comparator * * @param comparator Sort the entries using the comparator */ Feed sortEntries(Comparator<Entry> comparator); /** * Retrieves the first entry in the feed with the given atom:id value * * @param id The id to retrieve * @return The matching atom:entry * @throws IRISyntaxException if the id is malformed */ Entry getEntry(String id); }
7,201
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/Element.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import java.util.List; import java.util.Locale; import java.util.Map; import javax.activation.DataHandler; import javax.xml.namespace.QName; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.iri.IRISyntaxException; import org.apache.abdera.i18n.rfc4646.Lang; /** * Root interface for all elements in the Feed Object Model */ public interface Element extends Base, Iterable<Element> { /** * Return this Element's parent element or document * * @return The parent */ <T extends Base> T getParentElement(); /** * @deprecated This method will cause corruption of the object model because the parent of an * element cannot be set without adding that element as a child. */ <T extends Element> T setParentElement(Element parent); /** * Get the element preceding this one * * @return The preceding sibling */ <T extends Element> T getPreviousSibling(); /** * Get the element following this one * * @return The following sibling */ <T extends Element> T getNextSibling(); /** * Get the first child element * * @return The first child */ <T extends Element> T getFirstChild(); /** * Get the first previous sibling with the specified QName * * @param qname The XML QName of the sibling to find * @return The matching element */ <T extends Element> T getPreviousSibling(QName qname); /** * Get the first following sibling with the specified QName * * @param qname The XML QName of the sibling to find * @return The matching element */ <T extends Element> T getNextSibling(QName qname); /** * Get the first child element with the given QName * * @param qname The XML QName of the sibling to find * @return The matching element */ <T extends Element> T getFirstChild(QName qname); /** * Return the XML QName of this element * * @return The QName of the element */ QName getQName(); /** * Returns the value of this elements <code>xml:lang</code> attribute or null if <code>xml:lang</code> is undefined. * * @return The xml:lang value */ String getLanguage(); /** * Returns the value of the xml:lang attribute as a Lang object */ Lang getLanguageTag(); /** * Returns a Locale object created from the <code>xml:lang</code> attribute * * @return A Locale appropriate for the Language (xml:lang) */ Locale getLocale(); /** * Sets the value of this elements <code>xml:lang</code> attribute. * * @param language the value of the xml:lang element */ <T extends Element> T setLanguage(String language); /** * Returns the value of this element's <code>xml:base</code> attribute or null if <code>xml:base</code> is * undefined. * * @return The Base URI * @throws IRISyntaxException if the Base URI is malformed */ IRI getBaseUri(); /** * Returns the current in-scope, fully qualified Base URI for this element. * * @throws IRISyntaxException if the Base URI is malformed */ IRI getResolvedBaseUri(); /** * Sets the value of this element's <code>xml:base</code> attribute. * * @param base The IRI base value */ <T extends Element> T setBaseUri(IRI base); /** * Sets the value of this element's <code>xml:base</code> attribute. * * @param base The Base IRI * @throws IRISyntaxException if the base URI is malformed */ <T extends Element> T setBaseUri(String base); /** * Returns the document to which this element belongs * * @return The Document to which this element belongs */ <T extends Element> Document<T> getDocument(); /** * Returns the value of the named attribute * * @param name The name of the attribute * @return The value of the attribute */ String getAttributeValue(String name); /** * Returns the value of the named attribute * * @param qname The XML QName of the attribute * @return The value of the attribute */ String getAttributeValue(QName qname); /** * Returns a listing of all attributes on this element * * @return The listing of attributes for this element */ List<QName> getAttributes(); /** * Returns a listing of extension attributes on this element (extension attributes are attributes whose namespace * URI is different than the elements) * * @return The listing non-Atom attributes */ List<QName> getExtensionAttributes(); /** * Remove the named Attribute * * @param qname The XML QName of the attribute to remove */ <T extends Element> T removeAttribute(QName qname); /** * Remove the named attribute * * @param name The name of the attribute to remove */ <T extends Element> T removeAttribute(String name); /** * Sets the value of the named attribute * * @param name The name of the attribute * @param value The value of the attribute */ <T extends Element> T setAttributeValue(String name, String value); /** * Sets the value of the named attribute * * @param qname The XML QName of the attribute * @param value The value of the attribute */ <T extends Element> T setAttributeValue(QName qname, String value); /** * Removes this element from its current document */ void discard(); /** * Returns the Text value of this element * * @return The text value */ String getText(); /** * Set the Text value of this element * * @param text The text value */ void setText(String text); /** * Set the Text value of this element using the data handler */ <T extends Element> T setText(DataHandler dataHandler); /** * Declare a namespace */ <T extends Element> T declareNS(String uri, String prefix); /** * Return a map listing the xml namespaces declared for this element */ Map<String, String> getNamespaces(); /** * Return a listing of this elements child elements */ <T extends Element> List<T> getElements(); /** * Return true if insignificant whitespace must be preserved */ boolean getMustPreserveWhitespace(); /** * Set to true to preserve insignificant whitespace */ <T extends Element> T setMustPreserveWhitespace(boolean preserve); }
7,202
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/Text.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; /** * <p> * Represents an Atom Text Contruct. * </p> * <p> * Atom allows three kinds of Text constructs: * </p> * <ul> * <li>Text, consisting of content that is to be interpreted as plain text with no markup. For instance, * <code>&lt;title type="text">&amp;lt;title&amp;gt;&lt;/title></code> is interpreted as literal characer "&lt;" * followed by the word "content", followed by the literal character "&gt;".</li> * <li>HTML, consisting of content that is to be interpreted as escaped HTML markup. For instance, * <code>&lt;title type="html">&amp;lt;b&amp;gt;title&amp;lt;/b&amp;gt;&lt;/title></code> is interpreted as the word * "content" surrounded by the HTML <code>&lt;b&gt;</code> and <code>&lt;/b&gt;</code> tags.</li> * <li>XHTML, consisting of well-formed XHTML content wrapped in an XHTML div element. For instance, * <code>&lt;title type="xhtml">&lt;div xmlns="http://www.w3.org/1999/xhtml">&lt;b>Title&lt;/b>&lt;/div>&lt;/title></code> * .</li> * </ul> * <p> * Per RFC4287: * </p> * * <pre> * A Text construct contains human-readable text, usually in small * quantities. The content of Text constructs is Language-Sensitive. * * atomPlainTextConstruct = * atomCommonAttributes, * attribute type { "text" | "html" }?, * text * * atomXHTMLTextConstruct = * atomCommonAttributes, * attribute type { "xhtml" }, * xhtmlDiv * * atomTextConstruct = atomPlainTextConstruct | atomXHTMLTextConstruct * </pre> */ public interface Text extends Element { /** * Text Constructs can be either Text, HTML or XHTML */ public static enum Type { /** Plain Text **/ TEXT, /** Escaped HTML **/ HTML, /** Welformed XHTML **/ XHTML; /** * Return the text type */ public static Type typeFromString(String val) { Type type = TEXT; if (val != null) { if (val.equalsIgnoreCase("text")) type = TEXT; else if (val.equalsIgnoreCase("html")) type = HTML; else if (val.equalsIgnoreCase("xhtml")) type = XHTML; else type = null; } return type; } }; /** * Return the Text.Type * * @return The Text.Type */ Type getTextType(); /** * Set the Text.Type * * @param type The Text.Type */ Text setTextType(Type type); /** * Return the text value element * * @return A xhtml:div */ Div getValueElement(); /** * Set the text value element * * @param value The xhtml:div */ Text setValueElement(Div value); /** * Return the text value * * @return The text value */ String getValue(); /** * Set the text value * * @param value The text value */ Text setValue(String value); /** * Return the wrapped value * * @return The text value wrapped in a xhtml:div */ String getWrappedValue(); /** * Set the wrapped value * * @param wrappedValue The text value wrapped in a xhtml:div */ Text setWrappedValue(String wrappedValue); }
7,203
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/Link.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import javax.activation.MimeType; import org.apache.abdera.i18n.iri.IRI; /** * <p> * Represents an Atom Link element. * </p> * <p> * Per RFC4287: * </p> * * <pre> * The "atom:link" element defines a reference from an entry or feed to * a Web resource. This specification assigns no meaning to the content * (if any) of this element. * * atomLink = * element atom:link { * atomCommonAttributes, * attribute href { atomUri }, * attribute rel { atomNCName | atomUri }?, * attribute type { atomMediaType }?, * attribute hreflang { atomLanguageTag }?, * attribute title { text }?, * attribute length { text }?, * undefinedContent * } * </pre> */ public interface Link extends ExtensibleElement { public static final String REL_ALTERNATE = "alternate"; public static final String REL_CURRENT = "current"; public static final String REL_ENCLOSURE = "enclosure"; public static final String REL_FIRST = "first"; public static final String REL_LAST = "last"; public static final String REL_NEXT = "next"; public static final String REL_PAYMENT = "payment"; public static final String REL_PREVIOUS = "previous"; public static final String REL_RELATED = "related"; public static final String REL_SELF = "self"; public static final String REL_VIA = "via"; public static final String REL_REPLIES = "replies"; public static final String REL_LICENSE = "license"; public static final String REL_EDIT = "edit"; public static final String REL_EDIT_MEDIA = "edit-media"; public static final String REL_SERVICE = "service"; public static final String IANA_BASE = "http://www.iana.org/assignments/relation/"; public static final String REL_ALTERNATE_IANA = IANA_BASE + REL_ALTERNATE; public static final String REL_CURRENT_IANA = IANA_BASE + REL_CURRENT; public static final String REL_ENCLOSURE_IANA = IANA_BASE + REL_ENCLOSURE; public static final String REL_FIRST_IANA = IANA_BASE + REL_FIRST; public static final String REL_LAST_IANA = IANA_BASE + REL_LAST; public static final String REL_NEXT_IANA = IANA_BASE + REL_NEXT; public static final String REL_PAYMENT_IANA = IANA_BASE + REL_PAYMENT; public static final String REL_PREVIOUS_IANA = IANA_BASE + REL_PREVIOUS; public static final String REL_RELATED_IANA = IANA_BASE + REL_RELATED; public static final String REL_SELF_IANA = IANA_BASE + REL_SELF; public static final String REL_VIA_IANA = IANA_BASE + REL_VIA; public static final String REL_REPLIES_IANA = IANA_BASE + REL_REPLIES; public static final String REL_LICENSE_IANA = IANA_BASE + REL_LICENSE; public static final String REL_EDIT_IANA = IANA_BASE + REL_EDIT; public static final String REL_EDIT_MEDIA_IANA = IANA_BASE + REL_EDIT_MEDIA; public static final String REL_SERVICE_IANA = IANA_BASE + REL_SERVICE; /** * RFC4287: The "href" attribute contains the link's IRI. atom:link elements MUST have an href attribute, whose * value MUST be a IRI reference [RFC3987]. * * @return The href IRI value * @throws IRISyntaxException if the href is malformed */ IRI getHref(); /** * Returns the value of the link's href attribute resolved against the in-scope Base IRI * * @return The href IRI value * @throws IRISyntaxException if the href is malformed */ IRI getResolvedHref(); /** * RFC4287: The "href" attribute contains the link's IRI. atom:link elements MUST have an href attribute, whose * value MUST be a IRI reference [RFC3987]. * * @param href The href IRI * @throws IRISyntaxException if the href is malformed */ Link setHref(String href); /** * <p> * RFC4287: atom:link elements MAY have a "rel" attribute that indicates the link relation type. If the "rel" * attribute is not present, the link element MUST be interpreted as if the link relation type is "alternate"... The * value of "rel" MUST be a string that is non-empty and matches either the "isegment-nz-nc" or the "IRI" production * in [RFC3987]. Note that use of a relative reference other than a simple name is not allowed. If a name is given, * implementations MUST consider the link relation type equivalent to the same name registered within the IANA * Registry of Link Relations (Section 7), and thus to the IRI that would be obtained by appending the value of the * rel attribute to the string "http://www.iana.org/assignments/relation/". The value of "rel" describes the meaning * of the link, but does not impose any behavioral requirements on Atom Processors. * </p> * * @return The rel attribute value */ String getRel(); /** * <p> * RFC4287: atom:link elements MAY have a "rel" attribute that indicates the link relation type. If the "rel" * attribute is not present, the link element MUST be interpreted as if the link relation type is "alternate"... The * value of "rel" MUST be a string that is non-empty and matches either the "isegment-nz-nc" or the "IRI" production * in [RFC3987]. Note that use of a relative reference other than a simple name is not allowed. If a name is given, * implementations MUST consider the link relation type equivalent to the same name registered within the IANA * Registry of Link Relations (Section 7), and thus to the IRI that would be obtained by appending the value of the * rel attribute to the string "http://www.iana.org/assignments/relation/". The value of "rel" describes the meaning * of the link, but does not impose any behavioral requirements on Atom Processors. * </p> * * @param rel The rel attribute value */ Link setRel(String rel); /** * RFC4287: On the link element, the "type" attribute's value is an advisory media type: it is a hint about the type * of the representation that is expected to be returned when the value of the href attribute is dereferenced. Note * that the type attribute does not override the actual media type returned with the representation. Link elements * MAY have a type attribute, whose value MUST conform to the syntax of a MIME media type [MIMEREG]. * * @return The value of the type attribute * @throws MimeTypeParseException if the type is malformed */ MimeType getMimeType(); /** * RFC4287: On the link element, the "type" attribute's value is an advisory media type: it is a hint about the type * of the representation that is expected to be returned when the value of the href attribute is dereferenced. Note * that the type attribute does not override the actual media type returned with the representation. Link elements * MAY have a type attribute, whose value MUST conform to the syntax of a MIME media type [MIMEREG]. * * @param type The link type * @throws MimeTypeParseException if the type is malformed */ Link setMimeType(String type); /** * RFC4287: The "hreflang" attribute's content describes the language of the resource pointed to by the href * attribute. When used together with the rel="alternate", it implies a translated version of the entry. Link * elements MAY have an hreflang attribute, whose value MUST be a language tag [RFC3066]. * * @return The hreflang value */ String getHrefLang(); /** * RFC4287: The "hreflang" attribute's content describes the language of the resource pointed to by the href * attribute. When used together with the rel="alternate", it implies a translated version of the entry. Link * elements MAY have an hreflang attribute, whose value MUST be a language tag [RFC3066]. * * @param lang The hreflang value */ Link setHrefLang(String lang); /** * RFC4287: The "title" attribute conveys human-readable information about the link. The content of the "title" * attribute is Language-Sensitive. Entities such as "&amp;amp;" and "&amp;lt;" represent their corresponding * characters ("&amp;" and "&lt;", respectively), not markup. Link elements MAY have a title attribute. * * @return The title attribute */ String getTitle(); /** * RFC4287: The "title" attribute conveys human-readable information about the link. The content of the "title" * attribute is Language-Sensitive. Entities such as "&amp;amp;" and "&amp;lt;" represent their corresponding * characters ("&amp;" and "&lt;", respectively), not markup. Link elements MAY have a title attribute. * * @param title The title attribute */ Link setTitle(String title); /** * RFC4287: The "length" attribute indicates an advisory length of the linked content in octets; it is a hint about * the content length of the representation returned when the URI in the href attribute is mapped to a IRI and * dereferenced. Note that the length attribute does not override the actual content length of the representation as * reported by the underlying protocol. Link elements MAY have a length attribute. * * @return The length attribute value */ long getLength(); /** * RFC4287: The "length" attribute indicates an advisory length of the linked content in octets; it is a hint about * the content length of the representation returned when the IRI in the href attribute is mapped to a URI and * dereferenced. Note that the length attribute does not override the actual content length of the representation as * reported by the underlying protocol. Link elements MAY have a length attribute. * * @param length The length attribute value */ Link setLength(long length); }
7,204
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/Control.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; /** * <p> * Represents an Atom Publishing Protocol <code>control</code> element. * </p> * <p> * The purpose of the control extension is to provide a means for content publishers to embed various * publishing-operation specific control parameters within the body of the entry. For instance, the client may wish to * mark the entry as a draft, or may wish to ask the publishing server to enable or disable specific extended features * for a given entry. * </p> * <p> * Per APP Draft-08: * </p> * * <pre> * pubControl = * element pub:control { * atomCommonAttributes, * pubDraft? * &amp; extensionElement * } * * pubDraft = * element pub:draft { "yes" | "no" } * * The "pub:control" element MAY appear as a child of an "atom:entry" * which is being created or updated via the Atom Publishing Protocol. * The "pub:control" element, if it does appear in an entry, MUST only * appear at most one time. The "pub:control" element is considered * foreign markup as defined in Section 6 of [RFC4287]. * * The "pub:control" element and its child elements MAY be included in * Atom Feed or Entry Documents. * * The "pub:control" element MAY contain exactly one "pub:draft" element * as defined here, and MAY contain zero or more extension elements as * outlined in Section 6 of [RFC4287]. Both clients and servers MUST * ignore foreign markup present in the pub:control element. * </pre> */ public interface Control extends ExtensibleElement { /** * <p> * Returns true if the entry should <i>not</i> be made publicly visible. * </p> * <p> * APP Draft-08: The number of "pub:draft" elements in "pub:control" MUST be zero or one. Its value MUST be one of * "yes" or "no". A value of "no" means that the entry MAY be made publicly visible. If the "pub:draft" element is * missing then the value MUST be understood to be "no". The pub:draft element MAY be ignored. * </p> * * @return True if this is a draft */ boolean isDraft(); /** * <p> * Set to "true" if the entry should <i>not</i> be made publicly visible. * </p> * <p> * APP Draft-08: The number of "pub:draft" elements in "pub:control" MUST be zero or one. Its value MUST be one of * "yes" or "no". A value of "no" means that the entry MAY be made publicly visible. If the "pub:draft" element is * missing then the value MUST be understood to be "no". The pub:draft element MAY be ignored. * </p> * * @param draft true if app:draft should be set to "yes" */ Control setDraft(boolean draft); /** * <p> * Removes the draft setting completely from the control element. * </p> * <p> * APP Draft-08: The number of "pub:draft" elements in "pub:control" MUST be zero or one. Its value MUST be one of * "yes" or "no". A value of "no" means that the entry MAY be made publicly visible. If the "pub:draft" element is * missing then the value MUST be understood to be "no". The pub:draft element MAY be ignored. * </p> */ Control unsetDraft(); }
7,205
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/Base.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import org.apache.abdera.factory.Factory; import org.apache.abdera.writer.WriterOptions; /** * The Base interface provides the basis for the Feed Object Model API and defines the operations common to both the * Element and Document interfaces. Classes implementing Base MUST NOT be assumed to be thread safe. Developers wishing * to allow multiple threads to perform concurrent modifications to a Base MUST provide their own synchronization. */ public interface Base extends Cloneable { /** * Get the default WriterOptions for this object */ WriterOptions getDefaultWriterOptions(); /** * Serializes the model component out to the specified stream * * @param out The target output stream * @param options The WriterOptions to use */ void writeTo(OutputStream out, WriterOptions options) throws IOException; /** * Serializes the model component out to the specified java.io.Writer * * @param out The target output writer * @param options The WriterOptions to use */ void writeTo(Writer out, WriterOptions options) throws IOException; /** * Serializes the model component out to the specified stream using the given Abdera writer * * @param writer The Abdera writer to use * @param out The target output stream */ void writeTo(org.apache.abdera.writer.Writer writer, OutputStream out) throws IOException; /** * Serializes the model component out to the specified java.io.Writer using the given Abdera writer * * @param writer The Abdera writer to use * @param out The target output writer */ void writeTo(org.apache.abdera.writer.Writer writer, Writer out) throws IOException; /** * Serializes the model component out to the specified stream using the given Abdera writer * * @param writer The Abdera writer to use * @param out The target output stream */ void writeTo(String writer, OutputStream out) throws IOException; /** * Serializes the model component out to the specified java.io.Writer using the given Abdera writer * * @param writer The Abdera writer to use * @param out The target output writer */ void writeTo(String writer, Writer out) throws IOException; /** * Serializes the model component out to the specified stream using the given abdera writer * * @param writer The Abdera writer to use * @param out The target output stream * @param options The WriterOptions to use */ void writeTo(org.apache.abdera.writer.Writer writer, OutputStream out, WriterOptions options) throws IOException; /** * Serializes the model component out to the specified java.io.Writer using the given abdera writer * * @param writer The Abdera writer to use * @param out The target output writer * @param options The WriterOptions to use */ void writeTo(org.apache.abdera.writer.Writer writer, Writer out, WriterOptions options) throws IOException; /** * Serializes the model component out to the specified stream using the given abdera writer * * @param writer The name of the Abdera writer to use * @param out The target output stream * @param options The WriterOptions to use */ void writeTo(String writer, OutputStream out, WriterOptions options) throws IOException; /** * Serializes the model component out to the specified java.io.Writer using the given abdera writer * * @param writer The name of the Abdera writer to use * @param out The target output writer * @param options The WriterOptions to use */ void writeTo(String writer, Writer out, WriterOptions options) throws IOException; /** * Serializes the model component out to the specified stream * * @param out The java.io.OutputStream to use when serializing the Base. The charset encoding specified for the * document will be used */ void writeTo(OutputStream out) throws IOException; /** * Serializes the model component out to the specified writer * * @param writer The java.io.Writer to use when serializing the Base */ void writeTo(Writer writer) throws IOException; /** * Clone this Base */ Object clone(); /** * Get the Factory used to create this Base * * @return The Factory used to create this object */ Factory getFactory(); /** * Add an XML comment to this Base * * @param value The text value of the comment */ <T extends Base> T addComment(String value); /** * Ensure that the underlying streams are fully parsed. Calling complete on an Element does not necessarily mean * that the underlying stream is fully consumed, only that that particular element has been completely parsed. */ <T extends Base> T complete(); }
7,206
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/Collection.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import java.util.List; import javax.activation.MimeType; import org.apache.abdera.i18n.iri.IRI; /** * <p> * Represents an collection element in an Atom Publishing Protocol introspection document. * </p> * * <pre> * The "app:collection" describes an Atom Protocol collection. One * child element is defined here for app:collection: "app:member-type". * * appCollection = * element app:collection { * appCommonAttributes, * attribute href { text }, * ( atomTitle * &amp; appAccept * &amp; extensionElement* ) * } * </pre> */ public interface Collection extends ExtensibleElement { /** * The text value of the collections atom:title element * * @return The atom:title value */ String getTitle(); /** * Set the value of the collections atom:title element using type="text" * * @param title The value of the atom:title * @return The newly created title element */ Text setTitle(String title); /** * Set the value of the collections atom:title element using type="html". Special characters in the value will be * automatically escaped (e.g. & will become &amp; * * @param title The value of the atom:title * @return The newly created title element */ Text setTitleAsHtml(String title); /** * Set the value of the collections atom:title element using type="xhtml". The title text will be wrapped in a * xhtml:div and parsed to ensure that it is welformed XML. A ParseException (RuntimeException) could be thrown * * @param title The value of the atom:title * @return The newly created title element */ Text setTitleAsXHtml(String title); /** * Return the title element * * @return The title element */ Text getTitleElement(); /** * Return the value of the app:collection elements href attribute * * @return The href attribute IRI value * @throws IRISyntaxException if the value of the href attribute is malformed */ IRI getHref(); /** * Return the href attribute resolved against the in-scope Base URI * * @return The href attribute IRI value * @throws IRISyntaxException if the value of the href attribute is malformed */ IRI getResolvedHref(); /** * Set the value of the href attribute * * @param href The value of href attribute * @throws IRISyntaxException if the href attribute is malformed */ Collection setHref(String href); /** * Returns the listing of media-ranges allowed for this collection * * @return An array listing the media-ranges allowed for this collection */ String[] getAccept(); /** * Set the listing of media-ranges allowed for this collection. The special value "entry" is used to indicate Atom * Entry Documents. * * @param mediaRanges a listing of media-ranges * @throws MimeTypeParseException */ Collection setAccept(String... mediaRanges); /** * Returns true if the collection accepts the given media-type * * @param mediaType The media-type to check * @return True if the media-type is acceptable */ boolean accepts(String mediaType); /** * Returns true if the collection accepts Atom entry documents (equivalent to calling * accepts("application/atom+xml;type=entry");) */ boolean acceptsEntry(); /** * Returns true if the collection accepts nothing (i.e. there is an empty accept element) */ boolean acceptsNothing(); /** * Sets the appropriate accept element to indicate that entries are accepted (equivalent to calling * setAccept("application/atom+xml;type=entry");) */ Collection setAcceptsEntry(); /** * Sets the collection so that nothing is accepted (equivalent to calling setAccept(""); ) */ Collection setAcceptsNothing(); /** * Adds a new accept element to the collection */ Collection addAccepts(String mediaRange); /** * Adds new accept elements to the collection */ Collection addAccepts(String... mediaRanges); /** * Same as setAcceptsEntry except the existing accepts are not discarded */ Collection addAcceptsEntry(); /** * Returns true if the collection accepts the given media-type * * @param mediaType The media-type to check * @return True if the media-type is acceptable */ boolean accepts(MimeType mediaType); /** * Returns the app:categories element * * @return The app:categories element */ List<Categories> getCategories(); /** * Add an app:categories element * * @return The newly created app:categories element */ Categories addCategories(); /** * Add an app:categories element that links to an external Category Document * * @param href The IRI of the external Category Document * @return The newly created app:categories element */ Categories addCategories(String href); /** * Add the app:categories element to the collection * * @param categories The app:categories element */ Collection addCategories(Categories categories); /** * Add a listing of categories to the collection * * @param categories The listing of categories to add * @param fixed True if the listing of categories should be fixed * @param scheme The default IRI scheme for the categories listing * @return The newly created app:categories element */ Categories addCategories(List<Category> categories, boolean fixed, String scheme); }
7,207
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/Category.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import org.apache.abdera.i18n.iri.IRI; /** * <p> * Provides categorization informaton for a feed or entry * </p> * <p> * Per RFC4287: * </p> * * <pre> * The "atom:category" element conveys information about a category * associated with an entry or feed. This specification assigns no * meaning to the content (if any) of this element. * * atomCategory = * element atom:category { * atomCommonAttributes, * attribute term { text }, * attribute scheme { atomUri }?, * attribute label { text }?, * undefinedContent * } * </pre> */ public interface Category extends ExtensibleElement { /** * RFC4287: The "term" attribute is a string that identifies the category to which the entry or feed belongs. * Category elements MUST have a "term" attribute. * * @return The string value of the term attribute */ String getTerm(); /** * RFC4287: The "term" attribute is a string that identifies the category to which the entry or feed belongs. * Category elements MUST have a "term" attribute. * * @param term The string value of the term attribute */ Category setTerm(String term); /** * RFC4287: The "scheme" attribute is an IRI that identifies a categorization scheme. Category elements MAY have a * "scheme" attribute. * * @return The IRI value of the scheme attribute */ IRI getScheme(); /** * RFC4287: The "scheme" attribute is an IRI that identifies a categorization scheme. Category elements MAY have a * "scheme" attribute. * * @param scheme The IRI of the scheme */ Category setScheme(String scheme); /** * RFC4287: The "label" attribute provides a human-readable label for display in end-user applications. The content * of the "label" attribute is Language-Sensitive. Entities such as "&amp;amp;" and "&amp;lt;" represent their * corresponding characters ("&amp;" and "&lt;", respectively), not markup. Category elements MAY have a "label" * attribute. * * @return The value of the human-readable label */ String getLabel(); /** * RFC4287: The "label" attribute provides a human-readable label for display in end-user applications. The content * of the "label" attribute is Language-Sensitive. Entities such as "&amp;amp;" and "&amp;lt;" represent their * corresponding characters ("&amp;" and "&lt;", respectively), not markup. Category elements MAY have a "label" * attribute. * * @param label The value of the human-readable label */ Category setLabel(String label); }
7,208
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/ElementWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import javax.activation.DataHandler; import javax.xml.namespace.QName; import org.apache.abdera.factory.Factory; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.rfc4646.Lang; import org.apache.abdera.writer.WriterOptions; /** * Base implementation used for static extensions. */ @SuppressWarnings("unchecked") public abstract class ElementWrapper implements Element { private Element internal; protected ElementWrapper(Element internal) { this.internal = internal; } protected ElementWrapper(Factory factory, QName qname) { Element el = factory.newElement(qname); internal = (el instanceof ElementWrapper) ? ((ElementWrapper)el).getInternal() : el; } public <T extends Base> T addComment(String value) { internal.addComment(value); return (T)this; } public Object clone() { try { ElementWrapper wrapper = (ElementWrapper)super.clone(); wrapper.internal = (Element)internal.clone(); return wrapper; } catch (CloneNotSupportedException e) { // won't happen return null; } } public <T extends Element> T declareNS(String uri, String prefix) { internal.declareNS(uri, prefix); return (T)this; } public void discard() { internal.discard(); } public List<QName> getAttributes() { return internal.getAttributes(); } public String getAttributeValue(QName qname) { return internal.getAttributeValue(qname); } public String getAttributeValue(String name) { return internal.getAttributeValue(name); } public IRI getBaseUri() { return internal.getBaseUri(); } public <T extends Element> Document<T> getDocument() { return internal.getDocument(); } public List<QName> getExtensionAttributes() { return internal.getExtensionAttributes(); } public Factory getFactory() { return internal.getFactory(); } public <T extends Element> T getFirstChild() { return (T)internal.getFirstChild(); } public <T extends Element> T getFirstChild(QName qname) { return (T)internal.getFirstChild(qname); } public String getLanguage() { return internal.getLanguage(); } public Lang getLanguageTag() { return internal.getLanguageTag(); } public Locale getLocale() { return internal.getLocale(); } public <T extends Element> T getNextSibling() { return (T)internal.getNextSibling(); } public <T extends Element> T getNextSibling(QName qname) { return (T)internal.getNextSibling(qname); } public <T extends Base> T getParentElement() { return (T)internal.getParentElement(); } public <T extends Element> T getPreviousSibling() { return (T)internal.getPreviousSibling(); } public <T extends Element> T getPreviousSibling(QName qname) { return (T)internal.getPreviousSibling(qname); } public QName getQName() { return internal.getQName(); } public IRI getResolvedBaseUri() { return internal.getResolvedBaseUri(); } public String getText() { return internal.getText(); } public <T extends Element> T removeAttribute(QName qname) { internal.removeAttribute(qname); return (T)this; } public <T extends Element> T removeAttribute(String name) { internal.removeAttribute(name); return (T)this; } public <T extends Element> T setAttributeValue(QName qname, String value) { internal.setAttributeValue(qname, value); return (T)this; } public <T extends Element> T setAttributeValue(String name, String value) { internal.setAttributeValue(name, value); return (T)this; } public <T extends Element> T setBaseUri(IRI base) { internal.setBaseUri(base); return (T)this; } public <T extends Element> T setBaseUri(String base) { internal.setBaseUri(base); return (T)this; } public <T extends Element> T setLanguage(String language) { internal.setLanguage(language); return (T)this; } @SuppressWarnings("deprecation") public <T extends Element> T setParentElement(Element parent) { internal.setParentElement(parent); return (T)this; } public void setText(String text) { internal.setText(text); } public <T extends Element> T setText(DataHandler handler) { internal.setText(handler); return (T)this; } public void writeTo(OutputStream out) throws IOException { internal.writeTo(out); } public void writeTo(Writer writer) throws IOException { internal.writeTo(writer); } public boolean equals(Object other) { if (other instanceof ElementWrapper) other = ((ElementWrapper)other).getInternal(); return internal.equals(other); } public String toString() { return internal.toString(); } public int hashCode() { return internal.hashCode(); } public Element getInternal() { return internal; } public <T extends Element> List<T> getElements() { return internal.getElements(); } public Map<String, String> getNamespaces() { return internal.getNamespaces(); } public boolean getMustPreserveWhitespace() { return internal.getMustPreserveWhitespace(); } public <T extends Element> T setMustPreserveWhitespace(boolean preserve) { internal.setMustPreserveWhitespace(preserve); return (T)this; } public void writeTo(OutputStream out, WriterOptions options) throws IOException { internal.writeTo(out, options); } public void writeTo(org.apache.abdera.writer.Writer writer, OutputStream out, WriterOptions options) throws IOException { internal.writeTo(writer, out, options); } public void writeTo(org.apache.abdera.writer.Writer writer, OutputStream out) throws IOException { internal.writeTo(writer, out); } public void writeTo(org.apache.abdera.writer.Writer writer, Writer out, WriterOptions options) throws IOException { internal.writeTo(writer, out, options); } public void writeTo(org.apache.abdera.writer.Writer writer, Writer out) throws IOException { internal.writeTo(writer, out); } public void writeTo(String writer, OutputStream out, WriterOptions options) throws IOException { internal.writeTo(writer, out, options); } public void writeTo(String writer, OutputStream out) throws IOException { internal.writeTo(writer, out); } public void writeTo(String writer, Writer out, WriterOptions options) throws IOException { internal.writeTo(writer, out, options); } public void writeTo(String writer, Writer out) throws IOException { internal.writeTo(writer, out); } public void writeTo(Writer out, WriterOptions options) throws IOException { internal.writeTo(out, options); } public WriterOptions getDefaultWriterOptions() { return internal.getDefaultWriterOptions(); } public <T extends Base> T complete() { internal.complete(); return (T)this; } public Iterator<Element> iterator() { return internal.iterator(); } }
7,209
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/Document.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import java.io.Serializable; import java.util.Date; import javax.activation.MimeType; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.rfc4646.Lang; import org.apache.abdera.util.EntityTag; import org.apache.abdera.util.XmlUtil.XMLVersion; /** * <p> * The top level artifact of the Feed Object Model. The Parser component processes data from an InputStream and returns * a Document instance. The type of Document returned depends on the XML format being parsed. The Feed Object Model * supports four basic types of documents: FeedDocument, EntryDocument, ServiceDocument (Atom Publishing Protocol * Introspection Documents) and XmlDocument (any arbitrary XML). * </p> */ public interface Document<T extends Element> extends Base, Serializable { /** * Returns the root element of the document (equivalent to DOM's getDocumentElement) * * @return The root element of the document */ T getRoot(); /** * Sets the root element of the document * * @param root Set the root element of the document */ Document<T> setRoot(T root); /** * Returns the Base URI of the document. All relative URI's contained in the document will be resolved according to * this base. * * @return The Base IRI */ IRI getBaseUri(); /** * Sets the Base URI of the document. All relative URI's contained in the document will be resolved according to * this base. * * @param base The Base URI * @throws IRISyntaxException if the IRI is malformed */ Document<T> setBaseUri(String base); /** * Returns the content type of this document * * @return The content type of this document */ MimeType getContentType(); /** * Sets the content type for this document * * @param contentType The content type of document * @throws MimeTypeParseException if the content type is malformed */ Document<T> setContentType(String contentType); /** * Returns the last modified date for this document * * @return The last-modified date */ Date getLastModified(); /** * Sets the last modified date for this document * * @param lastModified the last-modified date */ Document<T> setLastModified(Date lastModified); /** * Gets the charset used for this document * * @return The character encoding used for this document */ String getCharset(); /** * Sets the charset used for this document * * @param charset The character encoding to use */ Document<T> setCharset(String charset); /** * Add a processing instruction to the document * * @param target The processing instruction target * @param value The processing instruction value */ Document<T> addProcessingInstruction(String target, String value); /** * Get the values for the given processing instruction */ String[] getProcessingInstruction(String target); /** * Add a xml-stylesheet processing instruction to the document * * @param href The href of the stylesheet * @param media The media target for this stylesheet or null if none */ Document<T> addStylesheet(String href, String media); /** * Return the entity tag for this document */ EntityTag getEntityTag(); /** * Set the entity tag for this document */ Document<T> setEntityTag(EntityTag tag); /** * Set the entity tag for this document */ Document<T> setEntityTag(String tag); /** * Get the language */ String getLanguage(); /** * Returns the value of the xml:lang attribute as a Lang object */ Lang getLanguageTag(); /** * set the base language */ Document<T> setLanguage(String lang); /** * Get the slug for this document */ String getSlug(); /** * Set the slug for this document */ Document<T> setSlug(String slug); /** * Return true if insignificant whitespace must be preserved */ boolean getMustPreserveWhitespace(); /** * Set to true to preserve insignificant whitespace */ Document<T> setMustPreserveWhitespace(boolean preserve); /** * Get the XMLVersion used by this document */ XMLVersion getXmlVersion(); }
7,210
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/Div.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; /** * <p> * Represents an XHTML div tag. * </p> */ public interface Div extends ExtensibleElement { /** * Returns the array of class attribute values on the div * * @return A listing of class attribute values */ String[] getXhtmlClass(); /** * Returns the value of the div element's id attribute * * @return The value of the id attribute */ String getId(); /** * Returns the value of the div element's title attribute * * @return The value of the title attribute */ String getTitle(); /** * Sets the value of the div element's id attribute * * @param id The value of the id attribute */ Div setId(String id); /** * Set the value of the div element's title attribute * * @param title The value of the title attribute */ Div setTitle(String title); /** * Sets the array of class attribute values on the div * * @param classes A listing of class attribute values */ Div setXhtmlClass(String[] classes); /** * Returns the value of the div element * * @return The value of the div element */ String getValue(); /** * Set the value of the div element * * @param value The text value */ void setValue(String value); }
7,211
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/TextValue.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import java.io.InputStream; import javax.activation.DataHandler; /** * A text value. Returned by the Abdera XPath implementation when querying for text nodes (e.g. * xpath.selectNodes("//text()"); ...). There should be very little reason why an application would use this. It is * provided to keep applications from having to deal directly with the underlying parser impl */ public interface TextValue { /** * A DataHandler for Base64 encoded binary data */ DataHandler getDataHandler(); /** * An InputStream used to read the text content */ InputStream getInputStream(); /** * Return the text value */ String getText(); /** * The parent element */ <T extends Base> T getParentElement(); /** * Delete this node */ void discard(); }
7,212
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/ExtensibleElement.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import java.util.List; import javax.xml.namespace.QName; /** * An abstract element that can be extended with namespaced child elements */ public interface ExtensibleElement extends Element { /** * Returns the complete set of extension elements * * @return a listing of extensions */ List<Element> getExtensions(); /** * Returns the complete set of extension elements using the specified XML Namespace URI * * @param uri A namespace URI * @return A listing of extensions using the specified XML namespace */ List<Element> getExtensions(String uri); /** * Returns the complete set of extension elements using the specified XML qualified name * * @param qname An XML QName * @return A listing of extensions with the specified QName */ <T extends Element> List<T> getExtensions(QName qname); /** * Returns the first extension element with the XML qualified name * * @param qname An XML QName * @return An extension with the specified qname */ <T extends Element> T getExtension(QName qname); /** * Adds an individual extension element * * @param extension An extension element to add */ <T extends ExtensibleElement> T addExtension(Element extension); /** * Adds an individual extension element before the specified element */ <T extends ExtensibleElement> T addExtension(Element extension, Element before); /** * Adds an individual extension element * * @param qname An extension element to create * @return The newly created extension element */ <T extends Element> T addExtension(QName qname); /** * Adds an individual extension element * * @param qname An extension element to create * @return The newly created extension element */ <T extends Element> T addExtension(QName qname, QName before); /** * Adds an individual extension element * * @param namespace An XML namespace * @param localPart A localname * @param prefix A XML namespace prefix * @return The newly creatd extension element */ <T extends Element> T addExtension(String namespace, String localPart, String prefix); /** * Adds a simple extension (text content only) * * @param qname An XML QName * @param value The simple text value of the element * @return The newly created extension element */ Element addSimpleExtension(QName qname, String value); /** * Adds a simple extension (text content only) * * @param namespace An XML namespace * @param localPart A local name * @param prefix A namespace prefix * @param value The simple text value * @return The newly created extension element */ Element addSimpleExtension(String namespace, String localPart, String prefix, String value); /** * Gets the value of a simple extension * * @param qname An XML QName * @return The string value of the extension */ String getSimpleExtension(QName qname); /** * Gets the value of a simple extension * * @param namespace An XML namespace * @param localPart A localname * @param prefix A namespace prefix * @return The string value of the extension */ String getSimpleExtension(String namespace, String localPart, String prefix); /** * Find an extension by Class rather than QName * * @param _class The implementation class of the extension * @return The extension element */ <T extends Element> T getExtension(Class<T> _class); }
7,213
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/IRIElement.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.iri.IRISyntaxException; /** * <p> * The IRI interface provides a common base for a set of feed and entry elements whose content value must be a valid * IRI/URI reference. These include the elements atom:icon, atom:logo, and atom:id. * </p> */ public interface IRIElement extends Element { /** * Returns the value of the element as a java.net.URI * * @return The IRI value of this element */ IRI getValue(); /** * Sets the value of the element * * @param iri The iri value * @throws IRISyntaxException if the value is malformed */ IRIElement setValue(String iri); /** * Set the value of this element using the normalization as specified in RFC4287 * * @param iri A non-normalized IRI * @throws IRISyntaxException if the iri is malformed */ IRIElement setNormalizedValue(String iri); /** * Returns the value of the element resolved against the current in-scope Base URI * * @return The resolved IRI value */ IRI getResolvedValue(); }
7,214
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/Person.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.iri.IRISyntaxException; /** * <p> * An Atom Person Construct * </p> * <p> * Per RFC4287: * </p> * * <pre> * A Person construct is an element that describes a person, * corporation, or similar entity (hereafter, 'person'). * * atomPersonConstruct = * atomCommonAttributes, * (element atom:name { text } * &amp; element atom:uri { atomUri }? * &amp; element atom:email { atomEmailAddress }? * &amp; extensionElement*) * * </pre> */ public interface Person extends ExtensibleElement, Element { /** * The "atom:name" element's content conveys a human-readable name for the person. The content of atom:name is * Language-Sensitive. Person constructs MUST contain exactly one "atom:name" element. * * @return The atom:name element */ Element getNameElement(); /** * The "atom:name" element's content conveys a human-readable name for the person. The content of atom:name is * Language-Sensitive. Person constructs MUST contain exactly one "atom:name" element. * * @param element The atom:name element */ Person setNameElement(Element element); /** * The "atom:name" element's content conveys a human-readable name for the person. The content of atom:name is * Language-Sensitive. Person constructs MUST contain exactly one "atom:name" element. * * @param name The person name * @return The newly created atom:name element */ Element setName(String name); /** * The "atom:name" element's content conveys a human-readable name for the person. The content of atom:name is * Language-Sensitive. Person constructs MUST contain exactly one "atom:name" element. * * @return The name value */ String getName(); /** * The "atom:email" element's content conveys an e-mail address associated with the person. Person constructs MAY * contain an atom:email element, but MUST NOT contain more than one. Its content MUST conform to the "addr-spec" * production in [RFC2822]. * * @return the atom:email element */ Element getEmailElement(); /** * The "atom:email" element's content conveys an e-mail address associated with the person. Person constructs MAY * contain an atom:email element, but MUST NOT contain more than one. Its content MUST conform to the "addr-spec" * production in [RFC2822]. * * @param element The atom:email element */ Person setEmailElement(Element element); /** * The "atom:email" element's content conveys an e-mail address associated with the person. Person constructs MAY * contain an atom:email element, but MUST NOT contain more than one. Its content MUST conform to the "addr-spec" * production in [RFC2822]. * * @param email The person email * @return the newly created atom:email element */ Element setEmail(String email); /** * The "atom:email" element's content conveys an e-mail address associated with the person. Person constructs MAY * contain an atom:email element, but MUST NOT contain more than one. Its content MUST conform to the "addr-spec" * production in [RFC2822]. * * @return the person's emali */ String getEmail(); /** * The "atom:uri" element's content conveys an IRI associated with the person. Person constructs MAY contain an * atom:uri element, but MUST NOT contain more than one. The content of atom:uri in a Person construct MUST be an * IRI reference [RFC3987]. * * @return the atom:uri element */ IRIElement getUriElement(); /** * The "atom:uri" element's content conveys an IRI associated with the person. Person constructs MAY contain an * atom:uri element, but MUST NOT contain more than one. The content of atom:uri in a Person construct MUST be an * IRI reference [RFC3987]. * * @param uri The atom:uri element */ Person setUriElement(IRIElement uri); /** * The "atom:uri" element's content conveys an IRI associated with the person. Person constructs MAY contain an * atom:uri element, but MUST NOT contain more than one. The content of atom:uri in a Person construct MUST be an * IRI reference [RFC3987]. * * @param uri The atom:uri value * @throws IRISyntaxException if the uri is malformed */ IRIElement setUri(String uri); /** * The "atom:uri" element's content conveys an IRI associated with the person. Person constructs MAY contain an * atom:uri element, but MUST NOT contain more than one. The content of atom:uri in a Person construct MUST be an * IRI reference [RFC3987]. * * @return The atom:uri value * @throws IRISyntaxException if the uri is invalid */ IRI getUri(); }
7,215
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/DateTimeWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import java.util.Calendar; import java.util.Date; import javax.xml.namespace.QName; import org.apache.abdera.factory.Factory; /** * An ElementWrapper implementation that can serve as the basis for Atom Date Construct based extensions. */ public abstract class DateTimeWrapper extends ElementWrapper implements DateTime { protected DateTimeWrapper(Element internal) { super(internal); } protected DateTimeWrapper(Factory factory, QName qname) { super(factory, qname); } public AtomDate getValue() { AtomDate value = null; String v = getText(); if (v != null) { value = AtomDate.valueOf(v); } return value; } public DateTime setValue(AtomDate dateTime) { if (dateTime != null) setText(dateTime.getValue()); else setText(""); return this; } public DateTime setDate(Date date) { if (date != null) setText(AtomDate.valueOf(date).getValue()); else setText(""); return this; } public DateTime setCalendar(Calendar date) { if (date != null) setText(AtomDate.valueOf(date).getValue()); else setText(""); return this; } public DateTime setTime(long date) { setText(AtomDate.valueOf(date).getValue()); return this; } public DateTime setString(String date) { if (date != null) setText(AtomDate.valueOf(date).getValue()); else setText(""); return this; } public Date getDate() { AtomDate ad = getValue(); return (ad != null) ? ad.getDate() : null; } public Calendar getCalendar() { AtomDate ad = getValue(); return (ad != null) ? ad.getCalendar() : null; } public long getTime() { AtomDate ad = getValue(); return (ad != null) ? ad.getTime() : null; } public String getString() { AtomDate ad = getValue(); return (ad != null) ? ad.getValue() : null; } }
7,216
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/Comment.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import org.apache.abdera.factory.Factory; /** * A comment. Returned by the Abdera XPath implementation when querying for comment nodes (e.g. * xpath.selectNodes("//comment()"); ...). Most applications should never have much of a reason to use this interface. * It is provided primarily to avoid application from having to deal directly with the underlying parser implementation */ public interface Comment { /** * Delete the comment node */ void discard(); /** * The text of this comment node */ String getText(); /** * The text of this comment node */ Comment setText(String text); /** * The Abdera Factory */ Factory getFactory(); /** * The parent node */ <T extends Base> T getParentElement(); }
7,217
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/Service.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import java.util.List; import javax.activation.MimeType; /** * <p> * Represents the root of an Atom Publishing Protocol Introspection Document. * </p> * <p> * Per APP Draft-08: * </p> * * <pre> * The root of an introspection document is the "app:service" element. * * The "app:service" element is the container for introspection * information associated with one or more workspaces. An app:service * element MUST contain one or more app:workspace elements. * * appService = * element app:service { * appCommonAttributes, * ( appWorkspace+ * &amp; extensionElement* ) * } * </pre> */ public interface Service extends ExtensibleElement { /** * Return the complete set of workspaces * * @return A listing of app:workspaces elements */ List<Workspace> getWorkspaces(); /** * Return the named workspace * * @param title The workspace title * @return A matching app:workspace */ Workspace getWorkspace(String title); /** * Add an individual workspace * * @param workspace a app:workspace element */ Service addWorkspace(Workspace workspace); /** * Add an individual workspace * * @param title The workspace title * @return The newly created app:workspace */ Workspace addWorkspace(String title); /** * Returns the named collection * * @param workspace The workspace title * @param collection The collection title * @return A matching app:collection element */ Collection getCollection(String workspace, String collection); /** * Returns a collection that accepts the specified media types * * @param a listing of media types the collection must accept * @return A matching app:collection element */ Collection getCollectionThatAccepts(MimeType... type); /** * Returns a collection that accepts the specified media types * * @param a listing of media types the collection must accept * @return A matching app:collection element */ Collection getCollectionThatAccepts(String... type); /** * Returns collections that accept the specified media types * * @param a listing of media types the collection must accept * @return A listing matching app:collection elements */ List<Collection> getCollectionsThatAccept(MimeType... type); /** * Returns collections that accept the specified media types * * @param a listing of media types the collection must accept * @return A listing of matching app:collection elements */ List<Collection> getCollectionsThatAccept(String... type); }
7,218
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/Attribute.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import javax.xml.namespace.QName; import org.apache.abdera.factory.Factory; /** * An attribute. Returned by the Abdera XPath implementation when querying for Attribute nodes. */ public interface Attribute { /** * Get the QName of the attribute * * @return The attribute QName */ QName getQName(); /** * Return the text value of the attribute * * @return The attribute value */ String getText(); /** * Set the text value of the attribute. The value will be automatically escaped for proper serialization to XML * * @param text The attribute value */ Attribute setText(String text); /** * The Abdera Factory */ Factory getFactory(); }
7,219
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/Source.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import java.util.Date; import java.util.List; import org.apache.abdera.i18n.iri.IRI; /** * <p> * Per RFC4287: * </p> * * <pre> * If an atom:entry is copied from one feed into another feed, then the * source atom:feed's metadata (all child elements of atom:feed other * than the atom:entry elements) MAY be preserved within the copied * entry by adding an atom:source child element, if it is not already * present in the entry, and including some or all of the source feed's * Metadata elements as the atom:source element's children. Such * metadata SHOULD be preserved if the source atom:feed contains any of * the child elements atom:author, atom:contributor, atom:rights, or * atom:category and those child elements are not present in the source * atom:entry. * * atomSource = * element atom:source { * atomCommonAttributes, * (atomAuthor* * &amp; atomCategory* * &amp; atomContributor* * &amp; atomGenerator? * &amp; atomIcon? * &amp; atomId? * &amp; atomLink* * &amp; atomLogo? * &amp; atomRights? * &amp; atomSubtitle? * &amp; atomTitle? * &amp; atomUpdated? * &amp; extensionElement*) * } * * The atom:source element is designed to allow the aggregation of * entries from different feeds while retaining information about an * entry's source feed. For this reason, Atom Processors that are * performing such aggregation SHOULD include at least the required * feed-level Metadata elements (atom:id, atom:title, and atom:updated) * in the atom:source element. * </pre> */ public interface Source extends ExtensibleElement { /** * Returns the first author listed for the entry * * @return This feed's author */ Person getAuthor(); /** * Returns the complete set of authors listed for the entry * * @return This feeds list of authors */ List<Person> getAuthors(); /** * Adds an individual author to the entry * * @param person an atom:author element */ <T extends Source> T addAuthor(Person person); /** * Adds an author * * @param name The author name * @return The newly created atom:author element */ Person addAuthor(String name); /** * Adds an author * * @param name The author name * @param email The author email * @param iri The author iri * @return The newly created atom:author element * @throws IRISyntaxException if the iri is malformed */ Person addAuthor(String name, String email, String iri); /** * Lists the complete set of categories listed for the entry * * @return A listing of app:category elements */ List<Category> getCategories(); /** * Lists the complete set of categories using the specified scheme * * @param scheme A Scheme IRI * @return The listing of app:category elements * @throws IRISyntaxException if the scheme is malformed */ List<Category> getCategories(String scheme); /** * Adds an individual category to the entry * * @param category A atom:category element */ <T extends Source> T addCategory(Category category); /** * Adds a category to the feed * * @param term A category term * @return The newly created atom:category element */ Category addCategory(String term); /** * Adds a category to the feed * * @param scheme A category scheme * @param term A category term * @param label The human readable label * @return the newly created atom:category element * @throws IRISyntaxException if the scheme is malformed */ Category addCategory(String scheme, String term, String label); /** * Lists the complete set of contributors for this entry * * @return A listing of atom:contributor elements */ List<Person> getContributors(); /** * Adds an individual contributor to this entry * * @param person a atom:contributor element */ <T extends Source> T addContributor(Person person); /** * Adds a contributor * * @param name The name of a contributor * @return The newly created atom:contributor element */ Person addContributor(String name); /** * Adds a contributor * * @param name The contributor name * @param email The contributor email * @param iri The contributor uri * @return The atom:contributor element * @throws IRISyntaxException if the iri is malformed */ Person addContributor(String name, String email, String iri); /** * RFC4287: The "atom:generator" element's content identifies the agent used to generate a feed, for debugging and * other purposes. * * @return The atom:generator */ Generator getGenerator(); /** * RFC4287: The "atom:generator" element's content identifies the agent used to generate a feed, for debugging and * other purposes. * * @param generator A atom:generator element */ <T extends Source> T setGenerator(Generator generator); /** * RFC4287: The "atom:generator" element's content identifies the agent used to generate a feed, for debugging and * other purposes. * * @param iri The iri attribute * @param version The version attribute * @param value The value attribute * @return A newly created atom:generator element * @throws IRISyntaxException if the iri is malformed */ Generator setGenerator(String iri, String version, String value); /** * RFC4287: The "atom:icon" element's content is an IRI reference [RFC3987] that identifies an image that provides * iconic visual identification for a feed... The image SHOULD have an aspect ratio of one (horizontal) to one * (vertical) and SHOULD be suitable for presentation at a small size. * * @return the atom:icon element */ IRIElement getIconElement(); /** * RFC4287: The "atom:icon" element's content is an IRI reference [RFC3987] that identifies an image that provides * iconic visual identification for a feed... The image SHOULD have an aspect ratio of one (horizontal) to one * (vertical) and SHOULD be suitable for presentation at a small size. * * @param iri The atom:icon element */ <T extends Source> T setIconElement(IRIElement iri); /** * RFC4287: The "atom:icon" element's content is an IRI reference [RFC3987] that identifies an image that provides * iconic visual identification for a feed... The image SHOULD have an aspect ratio of one (horizontal) to one * (vertical) and SHOULD be suitable for presentation at a small size. * * @param iri The atom:icon IRI value * @throws IRISyntaxException if the iri is malformed */ IRIElement setIcon(String iri); /** * RFC4287: The "atom:icon" element's content is an IRI reference [RFC3987] that identifies an image that provides * iconic visual identification for a feed... The image SHOULD have an aspect ratio of one (horizontal) to one * (vertical) and SHOULD be suitable for presentation at a small size. * * @return The atom:icon value * @throws IRISyntaxException if the atom:icon value is malformed */ IRI getIcon(); /** * RFC4287: The "atom:id" element conveys a permanent, universally unique identifier for an entry or feed. * * @return The atom:id element */ IRIElement getIdElement(); /** * RFC4287: The "atom:id" element conveys a permanent, universally unique identifier for an entry or feed. * * @param id A atom:id element */ <T extends Source> T setIdElement(IRIElement id); /** * Returns the universally unique identifier for this feed * * @return The atom:id value * @throws IRISyntaxException if the atom:id is malformed */ IRI getId(); /** * Sets the universally unique identifier for this feed * * @param id The atom:id value * @return The newly created atom:id element * @throws IRISyntaxException if the id is malformed */ IRIElement setId(String id); /** * Creates a new randomized atom:id for the entry */ IRIElement newId(); /** * Sets the universally unique identifier for this feed * * @param id The atom:id value * @param normalize True if the atom:id value should be normalized * @return The newly created atom:id element * @throws IRISyntaxException if the id is malformed */ IRIElement setId(String id, boolean normalize); /** * Lists the complete set of links for this entry * * @return returns a listing of atom:link elements */ List<Link> getLinks(); /** * Lists the complete set of links using the specified rel attribute value * * @param rel A link relation * @return A listing of atom:link elements */ List<Link> getLinks(String rel); /** * Lists the complete set of links using the specified rel attributes values * * @param rels A listing of link relations * @return A listof atom:link elements */ List<Link> getLinks(String... rel); /** * Adds an individual link to the entry * * @param link A atom:link element */ <T extends Source> T addLink(Link link); /** * Adds an individual link element * * @param href The href IRI of the link * @return The newly created atom:link * @throws IRISyntaxException if the href is malformed */ Link addLink(String href); /** * Adds an individual link element * * @param href The href IRI of the link * @param rel The link rel attribute * @return The newly created atom:link * @throws IRISyntaxException if the href is malformed */ Link addLink(String href, String rel); /** * Adds an individual link element * * @param href The href IRI of the link * @param rel The link rel attribute * @param type The link type attribute * @param hreflang The link hreflang attribute * @param length The length attribute * @return The newly created atom:link * @throws IRISyntaxException if the href is malformed */ Link addLink(String href, String rel, String type, String title, String hreflang, long length); /** * RFC4287: The "atom:logo" element's content is an IRI reference [RFC3987] that identifies an image that provides * visual identification for a feed. The image SHOULD have an aspect ratio of 2 (horizontal) to 1 (vertical). * * @return the atom:logo element */ IRIElement getLogoElement(); /** * RFC4287: The "atom:logo" element's content is an IRI reference [RFC3987] that identifies an image that provides * visual identification for a feed. The image SHOULD have an aspect ratio of 2 (horizontal) to 1 (vertical). * * @param iri The atom:logo element */ <T extends Source> T setLogoElement(IRIElement iri); /** * RFC4287: The "atom:logo" element's content is an IRI reference [RFC3987] that identifies an image that provides * visual identification for a feed. The image SHOULD have an aspect ratio of 2 (horizontal) to 1 (vertical). * * @param iri The atom:logo value * @return The newly created atom:logo element * @throws IRISyntaxException if the iri is malformed */ IRIElement setLogo(String iri); /** * RFC4287: The "atom:logo" element's content is an IRI reference [RFC3987] that identifies an image that provides * visual identification for a feed. The image SHOULD have an aspect ratio of 2 (horizontal) to 1 (vertical). * * @return The atom:logo element value * @throws IRISyntaxException if the atom:logo value is malformed */ IRI getLogo(); /** * <p> * The rights element is typically used to convey a human readable copyright (e.g. "&lt;atom:rights>Copyright (c), * 2006&lt;/atom:rights>). * </p> * <p> * RFC4287: The "atom:rights" element is a Text construct that conveys information about rights held in and over an * entry or feed. * </p> * * @return The atom:rights element */ Text getRightsElement(); /** * <p> * The rights element is typically used to convey a human readable copyright (e.g. "&lt;atom:rights>Copyright (c), * 2006&lt;/atom:rights>). * </p> * <p> * RFC4287: The "atom:rights" element is a Text construct that conveys information about rights held in and over an * entry or feed. * </p> * * @param text The atom:rights element */ <T extends Source> T setRightsElement(Text text); /** * Sets the value of the rights as @type="text" * * @param value The atom:rights text value * @return The newly created atom:rights element */ Text setRights(String value); /** * Sets the value of the rights as @type="html" * * @param value The atom:rights text value * @return The newly created atom:rights element */ Text setRightsAsHtml(String value); /** * Sets the value of the rights as @type="xhtml" * * @param value The atom:rights text value * @return The newly created atom:rights element */ Text setRightsAsXhtml(String value); /** * Sets the value of the rights * * @param value The atom:rights text value * @param type The atom:rights text type * @return The newly created atom:rights element */ Text setRights(String value, Text.Type type); /** * Sets the value of the rights as @type="xhtml" * * @param value The XHTML div element * @return The newly created atom:rights element */ Text setRights(Div value); /** * Returns the text of atom:rights * * @return The value of the atom:rights element */ String getRights(); /** * Returns the type of atom:rights * * @return The Text.Type of the atom:rights element */ Text.Type getRightsType(); /** * RFC4287: The "atom:subtitle" element is a Text construct that conveys a human-readable description or subtitle * for a feed. * * @return The atom:subtitle element */ Text getSubtitleElement(); /** * RFC4287: The "atom:subtitle" element is a Text construct that conveys a human-readable description or subtitle * for a feed. * * @param text A atom:subtitle element */ <T extends Source> T setSubtitleElement(Text text); /** * Sets the value of the subtitle as @type="text" * * @param value the value of the atom:subtitle element * @return The atom:subtitle element */ Text setSubtitle(String value); /** * Sets the value of the subtitle as @type="html" * * @param value The value of the atom:subtitle element * @return The newly created atom:subtitle element */ Text setSubtitleAsHtml(String value); /** * Sets the value of the subtitle as @type="xhtml" * * @param value The value of the atom:subtitle element * @return The newly created atom:subtitle element */ Text setSubtitleAsXhtml(String value); /** * Sets the value of the subtitle * * @param value The value of the atom:subtitle element * @param type The atom:subtitle Text.Type * @return The newly created atom:subtitle element */ Text setSubtitle(String value, Text.Type type); /** * Sets the value of the subtitle as @type="xhtml" * * @param value The atom:subtitle element * @return The newly created atom:subtitle element */ Text setSubtitle(Div value); /** * Returns the text value of atom:subtitle * * @return The atom:subtitle text value */ String getSubtitle(); /** * Returns the atom:subtitle type * * @return The atom:subtitle Text.Type */ Text.Type getSubtitleType(); /** * RFC4287: The "atom:title" element is a Text construct that conveys a human-readable title for an entry or feed. * * @return The atom:title element */ Text getTitleElement(); /** * RFC4287: The "atom:title" element is a Text construct that conveys a human-readable title for an entry or feed. * * @param text The atom:title element */ <T extends Source> T setTitleElement(Text text); /** * Sets the value of the title as @type="text" * * @param value The atom:title value * @return The newly created atom:title element */ Text setTitle(String value); /** * Sets the value of the title as @type="html" * * @param value The atom:title value * @return The newly created atom:title element */ Text setTitleAsHtml(String value); /** * Sets the value of the title as @type="xhtml" * * @param value The atom:title value * @return The newly created atom:title element */ Text setTitleAsXhtml(String value); /** * Sets the value of the title * * @param value The atom:title value * @param type The atom:title Text.Type * @return The newly created atom:title element */ Text setTitle(String value, Text.Type type); /** * Sets the value of the title as @type="xhtml" * * @param value The XHTML div * @return The newly created atom:title element */ Text setTitle(Div value); /** * Returns the text of atom:title * * @return The text value of the atom:title element */ String getTitle(); /** * Returns the type of atom:title * * @return The atom:title Text.Type value */ Text.Type getTitleType(); /** * RFC4287: The "atom:updated" element is a Date construct indicating the most recent instant in time when an entry * or feed was modified in a way the publisher considers significant. Therefore, not all modifications necessarily * result in a changed atom:updated value. * * @return the atom:updated element */ DateTime getUpdatedElement(); /** * RFC4287: The "atom:updated" element is a Date construct indicating the most recent instant in time when an entry * or feed was modified in a way the publisher considers significant. Therefore, not all modifications necessarily * result in a changed atom:updated value. * * @param dateTime A atom:updated element */ <T extends Source> T setUpdatedElement(DateTime dateTime); /** * Return the atom:updated value * * @return The serialized string form value of atom:updated */ String getUpdatedString(); /** * Return the atom:updated value * * @return The atom:updated as a java.util.Date */ Date getUpdated(); /** * Set the atom:updated value * * @param value The java.util.Date * @return The newly created atom:updated element */ DateTime setUpdated(Date value); /** * Set the atom:updated value * * @param value The serialized string date * @return The newly created atom:updated element */ DateTime setUpdated(String value); /** * Returns the first link with the specified rel attribute value * * @param rel A link relation * @return The newly created atom:link element */ Link getLink(String rel); /** * Returns the first link using the rel attribute value "self" * * @return An atom:link */ Link getSelfLink(); /** * Returns this entries first alternate link * * @return An atom:link */ Link getAlternateLink(); /** * @param type A media type * @param hreflang A target language * @return A matching atom:link * @throws MimeTypeParseException if the type if malformed */ Link getAlternateLink(String type, String hreflang); /** * @param rel A link relation * @return An atom:link */ IRI getLinkResolvedHref(String rel); /** * @return An atom:link */ IRI getSelfLinkResolvedHref(); /** * @return An atom:link */ IRI getAlternateLinkResolvedHref(); /** * @param type A media type * @param hreflang A target language * @return A matching atom:link * @throws MimeTypeParseException if the type if malformed */ IRI getAlternateLinkResolvedHref(String type, String hreflang); /** * Return an app:collection element associatd with this atom:source. The Atom Publishing Protocol allows an * app:collection to be contained by atom:feed to specify the collection to which the feed is associated. * * @return An app:collection element */ Collection getCollection(); /** * Set the app:collection element * * @param collection An app:collection element */ <T extends Source> T setCollection(Collection collection); /** * Convert the Source element into an empty Feed element */ Feed getAsFeed(); }
7,220
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/AtomDate.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import java.io.Serializable; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * <p> * Provides an implementation of the Atom Date Construct, which is itself a specialization of the RFC3339 date-time. * </p> * <p> * Accessors on this class are not synchronized. * </p> * <p> * Per RFC4287: * </p> * * <pre> * 3.3. Date Constructs * * A Date construct is an element whose content MUST conform to the * "date-time" production in [RFC3339]. In addition, an uppercase "T" * character MUST be used to separate date and time, and an uppercase * "Z" character MUST be present in the absence of a numeric time zone * offset. * * atomDateConstruct = * atomCommonAttributes, * xsd:dateTime * * Such date values happen to be compatible with the following * specifications: [ISO.8601.1988], [W3C.NOTE-datetime-19980827], and * [W3C.REC-xmlschema-2-20041028]. * * Example Date constructs: * * &lt;updated>2003-12-13T18:30:02Z&lt;/updated> * &lt;updated>2003-12-13T18:30:02.25Z&lt;/updated> * &lt;updated>2003-12-13T18:30:02+01:00&lt;/updated> * &lt;updated>2003-12-13T18:30:02.25+01:00&lt;/updated> * * Date values SHOULD be as accurate as possible. For example, it would * be generally inappropriate for a publishing system to apply the same * timestamp to several entries that were published during the course of * a single day. * </pre> */ public final class AtomDate implements Cloneable, Serializable { private static final long serialVersionUID = -7062139688635877771L; private Date value; /** * Create an AtomDate using the current date and time */ public AtomDate() { this(new Date()); } /** * Create an AtomDate using the serialized string format (e.g. 2003-12-13T18:30:02Z). * * @param value The serialized RFC3339 date/time value */ public AtomDate(String value) { this(parse(value)); } /** * Create an AtomDate using a java.util.Date * * @param value The java.util.Date value * @throws NullPointerException if {@code date} is {@code null} */ public AtomDate(Date value) { this.value = (Date)value.clone(); } /** * Create an AtomDate using a java.util.Calendar. * * @param value The java.util.Calendar value * @throws NullPointerException if {@code value} is {@code null} */ public AtomDate(Calendar value) { this(value.getTime()); } /** * Create an AtomDate using the number of milliseconds since January 1, 1970, 00:00:00 GMT * * @param value The number of milliseconds since January 1, 1970, 00:00:00 GMT */ public AtomDate(long value) { this(new Date(value)); } /** * Return the serialized string form of the Atom date * * @return the serialized string form of the date as specified by RFC4287 */ public String getValue() { return format(value); } /** * Sets the value of the Atom date using the serialized string form * * @param value The serialized string form of the date */ public AtomDate setValue(String value) { this.value = parse(value); return this; } /** * Sets the value of the Atom date using java.util.Date * * @param date A java.util.Date * @throws NullPointerException if {@code date} is {@code null} */ public AtomDate setValue(Date date) { this.value = (Date)date.clone(); return this; } /** * Sets the value of the Atom date using java.util.Calendar * * @param calendar a java.util.Calendar */ public AtomDate setValue(Calendar calendar) { this.value = calendar.getTime(); return this; } /** * Sets the value of the Atom date using the number of milliseconds since January 1, 1970, 00:00:00 GMT * * @param timestamp The number of milliseconds since January 1, 1970, 00:00:00 GMT */ public AtomDate setValue(long timestamp) { this.value = new Date(timestamp); return this; } /** * Returns the value of this Atom Date * * @return A java.util.Date representing this Atom Date */ public Date getDate() { return (Date)value.clone(); } /** * Returns the value of this Atom Date as a java.util.Calendar * * @return A java.util.Calendar representing this Atom Date */ public Calendar getCalendar() { Calendar cal = Calendar.getInstance(); cal.setTime(value); return cal; } /** * Returns the value of this Atom Date as the number of milliseconds since January 1, 1970, 00:00:00 GMT * * @return The number of milliseconds since January 1, 1970, 00:00:00 GMT */ public long getTime() { return value.getTime(); } @Override public String toString() { return getValue(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + value.hashCode(); return result; } @Override public boolean equals(Object obj) { boolean answer = false; if (obj instanceof Date) { Date d = (Date)obj; answer = (this.value.equals(d)); } else if (obj instanceof String) { Date d = parse((String)obj); answer = (this.value.equals(d)); } else if (obj instanceof Calendar) { Calendar c = (Calendar)obj; answer = (this.value.equals(c.getTime())); } else if (obj instanceof AtomDate) { Date d = ((AtomDate)obj).value; answer = (this.value.equals(d)); } return answer; } @Override public Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(e); } } private static final Pattern PATTERN = Pattern .compile("(\\d{4})(?:-(\\d{2}))?(?:-(\\d{2}))?(?:([Tt])?(?:(\\d{2}))?(?::(\\d{2}))?(?::(\\d{2}))?(?:\\.(\\d{3}))?)?([Zz])?(?:([+-])(\\d{2}):(\\d{2}))?"); /** * Parse the serialized string form into a java.util.Date * * @param date The serialized string form of the date * @return The created java.util.Date */ public static Date parse(String date) { Matcher m = PATTERN.matcher(date); if (m.find()) { if (m.group(4) == null) throw new IllegalArgumentException("Invalid Date Format"); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); int hoff = 0, moff = 0, doff = -1; if (m.group(10) != null) { doff = m.group(10).equals("-") ? 1 : -1; hoff = doff * (m.group(11) != null ? Integer.parseInt(m.group(11)) : 0); moff = doff * (m.group(12) != null ? Integer.parseInt(m.group(12)) : 0); } c.set(Calendar.YEAR, Integer.parseInt(m.group(1))); c.set(Calendar.MONTH, m.group(2) != null ? Integer.parseInt(m.group(2)) - 1 : 0); c.set(Calendar.DATE, m.group(3) != null ? Integer.parseInt(m.group(3)) : 1); c.set(Calendar.HOUR_OF_DAY, m.group(5) != null ? Integer.parseInt(m.group(5)) + hoff : 0); c.set(Calendar.MINUTE, m.group(6) != null ? Integer.parseInt(m.group(6)) + moff : 0); c.set(Calendar.SECOND, m.group(7) != null ? Integer.parseInt(m.group(7)) : 0); c.set(Calendar.MILLISECOND, m.group(8) != null ? Integer.parseInt(m.group(8)) : 0); return c.getTime(); } else { throw new IllegalArgumentException("Invalid Date Format"); } } /** * Create the serialized string form from a java.util.Date * * @param d A java.util.Date * @return The serialized string form of the date */ public static String format(Date date) { StringBuilder sb = new StringBuilder(); Calendar c = Calendar.getInstance(TimeZone.getTimeZone("UTC")); c.setTime(date); sb.append(c.get(Calendar.YEAR)); sb.append('-'); int f = c.get(Calendar.MONTH); if (f < 9) sb.append('0'); sb.append(f + 1); sb.append('-'); f = c.get(Calendar.DATE); if (f < 10) sb.append('0'); sb.append(f); sb.append('T'); f = c.get(Calendar.HOUR_OF_DAY); if (f < 10) sb.append('0'); sb.append(f); sb.append(':'); f = c.get(Calendar.MINUTE); if (f < 10) sb.append('0'); sb.append(f); sb.append(':'); f = c.get(Calendar.SECOND); if (f < 10) sb.append('0'); sb.append(f); sb.append('.'); f = c.get(Calendar.MILLISECOND); if (f < 100) sb.append('0'); if (f < 10) sb.append('0'); sb.append(f); sb.append('Z'); return sb.toString(); } /** * Create a new Atom Date instance from the serialized string form * * @param value The serialized string form of the date * @return The created AtomDate */ public static AtomDate valueOf(String value) { return new AtomDate(value); } /** * Create a new Atom Date instance from a java.util.Date * * @param value a java.util.Date * @return The created AtomDate */ public static AtomDate valueOf(Date value) { return new AtomDate(value); } /** * Create a new Atom Date instance from a java.util.Calendar * * @param value A java.util.Calendar * @return The created AtomDate */ public static AtomDate valueOf(Calendar value) { return new AtomDate(value); } /** * Create a new Atom Date instance using the number of milliseconds since January 1, 1970, 00:00:00 GMT * * @param value The number of milliseconds since January 1, 1970, 00:00:00 GMT * @return The created AtomDate */ public static AtomDate valueOf(long value) { return new AtomDate(value); } }
7,221
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/DateTime.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import java.util.Calendar; import java.util.Date; /** * <p> * An element conforming to the Atom Date Construct. The data type implementation for this element is provided by the * AtomDate class. * </p> */ public interface DateTime extends Element { /** * Returns the content value of the element as an AtomDate object * * @return The Atom Date value of this element */ AtomDate getValue(); /** * Returns the content value of the element as a java.util.Date object * * @return The java.util.Date value of this element */ Date getDate(); /** * Returns the content value of the element as a java.util.Calendar object * * @return The java.util.Calendar value of this element */ Calendar getCalendar(); /** * Returns the content value of the element as a long (equivalent to calling DateTimeElement().getDate().getTime() * * @return The number of milliseconds since January 1, 1970, 00:00:00 GMT */ long getTime(); /** * Returns the content value of the element as a string conforming to RFC-3339 * * @return The serialized string form of this element */ String getString(); /** * Sets the content value of the element * * @param dateTime the Atom Date value */ DateTime setValue(AtomDate dateTime); /** * Sets the content value of the element * * @param date The java.util.Date value */ DateTime setDate(Date date); /** * Sets the content value of the element * * @param date The java.util.Calendar value */ DateTime setCalendar(Calendar date); /** * Sets the content value of the element * * @param date the number of milliseconds since January 1, 1970, 00:00:00 GMT */ DateTime setTime(long date); /** * Sets the content value of the element * * @param date The serialized string value */ DateTime setString(String date); }
7,222
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/ProcessingInstruction.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import org.apache.abdera.factory.Factory; /** * A processing instruction. Returned by the Abdera XPath implementation when querying for PI nodes (e.g. * xpath.selectNodes("//processing-instruction()"); ...). There should be very little reason for applications to use * this. It is provided to keep applications from having to deal with the underlying parser implementation */ public interface ProcessingInstruction { /** * Delete this PI */ void discard(); /** * The Abdera Factory */ Factory getFactory(); /** * The parent node */ <T extends Base> T getParentElement(); /** * The PI target */ String getTarget(); /** * The PI target */ void setTarget(String target); /** * The PI text */ String getText(); /** * The PI text */ <T extends ProcessingInstruction> T setText(String text); }
7,223
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/Workspace.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import java.util.List; import javax.activation.MimeType; import org.apache.abdera.i18n.iri.IRISyntaxException; /** * <p> * An Atom Publishing Protocol Introspection Document workspace element. * </p> * <p> * Per APP Draft-08 * </p> * * <pre> * The "app:workspace" element contains information elements about the * collections of resources available for editing. The app:workspace * element MUST contain one or more app:collection elements. * * appWorkspace = * element app:workspace { * appCommonAttributes, * ( atomTitle * &amp; appCollection* * &amp; extensionElement* ) * } * * </pre> */ public interface Workspace extends ExtensibleElement { /** * Return the workspace title * * @return The atom:title value */ String getTitle(); /** * Set the workspace title * * @param title The atom:title value * @return The newly created atom:title */ Text setTitle(String title); /** * Set the workspace title as escaped HTML * * @param title The atom:title value * @return The newly created atom:title */ Text setTitleAsHtml(String title); /** * Set the workspace title as XHTML * * @param title The atom:title value * @return the newly created atom:title */ Text setTitleAsXHtml(String title); /** * Return the atom:title * * @return The atom:title element */ Text getTitleElement(); /** * Returns the full set of collections in this workspace * * @return A listing of app:collection elements */ List<Collection> getCollections(); /** * Returns the named collection * * @param title A collection title * @return A matching app:collection */ Collection getCollection(String title); /** * Adds an individual collection to this workspace * * @param collection The collection to add */ Workspace addCollection(Collection collection); /** * Adds an individual collection to this workspace * * @param title The collection title * @param href The collection HREF * @return The newly created app:collection * @throws IRISyntaxException if the href is malformed */ Collection addCollection(String title, String href); /** * Adds a multipart collection to this workspace * * @param title The collection title * @param href The collection HREF * @return The newly created app:collection * @throws IRISyntaxException if the href is malformed */ public Collection addMultipartCollection(String title, String href); /** * Returns a collection that accepts the specified media types * * @param a listing of media types the collection must accept * @return A matching app:collection element */ Collection getCollectionThatAccepts(MimeType... type); /** * Returns a collection that accepts the specified media types * * @param a listing of media types the collection must accept * @return A matching app:collection element */ Collection getCollectionThatAccepts(String... type); /** * Returns collections that accept the specified media types * * @param a listing of media types the collection must accept * @return A listing matching app:collection elements */ List<Collection> getCollectionsThatAccept(MimeType... type); /** * Returns collections that accept the specified media types * * @param a listing of media types the collection must accept * @return A listing of matching app:collection elements */ List<Collection> getCollectionsThatAccept(String... type); }
7,224
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/ExtensibleElementWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import java.util.List; import javax.xml.namespace.QName; import org.apache.abdera.factory.Factory; /** * ElementWrapper implementation that implements the ExtensibleElement interface. This should be used to create static * extension elements that support extensions */ @SuppressWarnings("unchecked") public abstract class ExtensibleElementWrapper extends ElementWrapper implements ExtensibleElement { protected ExtensibleElementWrapper(Element internal) { super(internal); } public ExtensibleElementWrapper(Factory factory, QName qname) { super(factory, qname); } protected ExtensibleElement getExtInternal() { return (ExtensibleElement)getInternal(); } public <T extends ExtensibleElement> T addExtension(Element extension) { getExtInternal().addExtension(extension); return (T)this; } public <T extends Element> T addExtension(QName qname) { return (T)getExtInternal().addExtension(qname); } public <T extends Element> T addExtension(String namespace, String localPart, String prefix) { return (T)getExtInternal().addExtension(namespace, localPart, prefix); } public Element addSimpleExtension(QName qname, String value) { return getExtInternal().addSimpleExtension(qname, value); } public Element addSimpleExtension(String namespace, String localPart, String prefix, String value) { return getExtInternal().addSimpleExtension(namespace, localPart, prefix, value); } public <T extends Element> T getExtension(QName qname) { return (T)getExtInternal().getExtension(qname); } public <T extends Element> T getExtension(Class<T> _class) { return (T)getExtInternal().getExtension(_class); } public List<Element> getExtensions() { return getExtInternal().getExtensions(); } public List<Element> getExtensions(String uri) { return getExtInternal().getExtensions(uri); } public <T extends Element> List<T> getExtensions(QName qname) { return getExtInternal().getExtensions(qname); } public String getSimpleExtension(QName qname) { return getExtInternal().getSimpleExtension(qname); } public String getSimpleExtension(String namespace, String localPart, String prefix) { return getExtInternal().getSimpleExtension(namespace, localPart, prefix); } public boolean getMustPreserveWhitespace() { return getExtInternal().getMustPreserveWhitespace(); } public <T extends Element> T setMustPreserveWhitespace(boolean preserve) { getExtInternal().setMustPreserveWhitespace(preserve); return (T)this; } public <T extends ExtensibleElement> T addExtension(Element extension, Element before) { getExtInternal().addExtension(extension, before); return (T)this; } public <T extends Element> T addExtension(QName qname, QName before) { return (T)getExtInternal().addExtension(qname, before); } }
7,225
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/Entry.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import java.io.IOException; import java.io.InputStream; import java.util.Date; import java.util.List; import javax.activation.DataHandler; import javax.activation.MimeType; import org.apache.abdera.i18n.iri.IRI; /** * <p> * Represents an Atom Entry element. * </p> * <p> * Per RFC4287: * </p> * * <pre> * The "atom:entry" element represents an individual entry, acting as a * container for metadata and data associated with the entry. This * element can appear as a child of the atom:feed element, or it can * appear as the document (i.e., top-level) element of a stand-alone * Atom Entry Document. * * atomEntry = * element atom:entry { * atomCommonAttributes, * (atomAuthor* * &amp; atomCategory* * &amp; atomContent? * &amp; atomContributor* * &amp; atomId * &amp; atomLink* * &amp; atomPublished? * &amp; atomRights? * &amp; atomSource? * &amp; atomSummary? * &amp; atomTitle * &amp; atomUpdated * &amp; extensionElement*) * } * * This specification assigns no significance to the order of appearance * of the child elements of atom:entry. * * The following child elements are defined by this specification (note * that it requires the presence of some of these elements): * * o atom:entry elements MUST contain one or more atom:author elements, * unless the atom:entry contains an atom:source element that * contains an atom:author element or, in an Atom Feed Document, the * atom:feed element contains an atom:author element itself. * o atom:entry elements MAY contain any number of atom:category * elements. * o atom:entry elements MUST NOT contain more than one atom:content * element. * o atom:entry elements MAY contain any number of atom:contributor * elements. * o atom:entry elements MUST contain exactly one atom:id element. * o atom:entry elements that contain no child atom:content element * MUST contain at least one atom:link element with a rel attribute * value of "alternate". * o atom:entry elements MUST NOT contain more than one atom:link * element with a rel attribute value of "alternate" that has the * same combination of type and hreflang attribute values. * o atom:entry elements MAY contain additional atom:link elements * beyond those described above. * o atom:entry elements MUST NOT contain more than one atom:published * element. * o atom:entry elements MUST NOT contain more than one atom:rights * element. * o atom:entry elements MUST NOT contain more than one atom:source * element. * o atom:entry elements MUST contain an atom:summary element in either * of the following cases: * * the atom:entry contains an atom:content that has a "src" * attribute (and is thus empty). * * the atom:entry contains content that is encoded in Base64; * i.e., the "type" attribute of atom:content is a MIME media type * [MIMEREG], but is not an XML media type [RFC3023], does not * begin with "text/", and does not end with "/xml" or "+xml". * o atom:entry elements MUST NOT contain more than one atom:summary * element. * o atom:entry elements MUST contain exactly one atom:title element. * o atom:entry elements MUST contain exactly one atom:updated element. * </pre> */ public interface Entry extends ExtensibleElement { /** * Returns the first author listed for the entry * * @return The atom:author */ Person getAuthor(); /** * Returns the complete set of authors listed for the entry * * @return The listing of atom:author elements */ List<Person> getAuthors(); /** * Adds an individual author to the entry * * @param person The person to add */ Entry addAuthor(Person person); /** * Adds an author * * @param name The name of the author * @return The newly created atom:author element */ Person addAuthor(String name); /** * Adds an author * * @param name The name of the author * @param email The author's email address * @param uri A URI belonging to the author * @return The newly created atom:author element * @throws IRISyntaxException if the URI is malformed */ Person addAuthor(String name, String email, String uri); /** * Lists the complete set of categories listed for the entry * * @return The listing of atom:category elements */ List<Category> getCategories(); /** * Lists the complete set of categories using the specified scheme A listing of atom:category elements using the * specified scheme * * @throws IRISyntaxException if the scheme is malformed */ List<Category> getCategories(String scheme); /** * Adds an individual category to the entry * * @param category The atom:category element to add */ Entry addCategory(Category category); /** * Adds a category to the entry * * @param term The category term to add * @return The newly created atom:category */ Category addCategory(String term); /** * Adds a category to the entry * * @param scheme The category scheme * @param term The category term * @param label The human readable label * @return The newly create atom:category * @throws IRISyntaxException if the scheme is malformed */ Category addCategory(String scheme, String term, String label); /** * Returns the content for this entry * * @return The atom:content element */ Content getContentElement(); /** * Sets the content for this entry * * @param content The atom:content element */ Entry setContentElement(Content content); /** * Sets the content for this entry as @type="text" * * @param value The text value of the content * @return The newly created atom:content */ Content setContent(String value); /** * Sets the content for this entry as @type="html" * * @param value The text value of the content. Special characters will be escaped (e.g. &amp; will become &amp;amp;) * @return The newly created atom:content */ Content setContentAsHtml(String value); /** * Sets the content for this entry as @type="xhtml" * * @param value The text value of the content. The text will be parsed as XHTML * @return The newly created atom:content */ Content setContentAsXhtml(String value); /** * Sets the content for this entry * * @param value The text value of the content * @param type The Content Type of the text * @return The newly created atom:content */ Content setContent(String value, Content.Type type); /** * Sets the content for this entry * * @param value The content element value. If the value is a Div, the the type attribute will be set to * type="xhtml", otherwise type="application/xml" * @return The newly create atom:content */ Content setContent(Element value); /** * Sets the content for this entry * * @param element The element value * @param mediaType The media type of the element * @throws MimeTypeParseException if the mediaType is malformed */ Content setContent(Element element, String mediaType); /** * Sets the content for this entry * * @param dataHandler The Data Handler containing the binary content needing Base64 encoding. * @throws MimeTypeParseException if the media Type specified by the dataHandler is malformed */ Content setContent(DataHandler dataHandler); /** * Sets the content for this entry * * @param dataHandler The Data Handler containing the binary content needing Base64 encoding. * @param mediaType The mediatype of the binary content * @return The created content element * @throws MimeTypeParseException if the media type specified is malformed */ Content setContent(DataHandler dataHandler, String mediatype); /** * Sets the content for this entry * * @param inputStream An inputstream providing binary content * @return The created content element */ Content setContent(InputStream inputStream); /** * Sets the content for this entry * * @param inputStream An inputstream providing binary content * @param mediaType The mediatype of the binary content * @return The created content element * @throws MimeTypeParseException if the media type specified is malformed */ Content setContent(InputStream inputStream, String mediatype); /** * Sets the content for this entry * * @param value the string value of the content * @param mediatype the media type for the content * @return The newly created atom:content * @throws MimeTypeParseException if the media type is malformed */ Content setContent(String value, String mediatype); /** * Sets the content for this entry as out of line. * * @param uri URI of the content (value of the "src" attribute). * @param mediatype Type of the content. * @return The new content element. * @throws MimeTypeParseException if the mime type is invalid. * @throws IRISyntaxException if the URI is invalid. */ Content setContent(IRI uri, String mediatype); /** * Returns the text of the content element * * @return text content */ String getContent(); /** * Returns an input stream from the content element value. This is particularly useful when dealing with Base64 * binary content. * * @throws IOException */ InputStream getContentStream() throws IOException; /** * Returns the content/@src attribute, if any * * @return The src IRI * @throws IRISyntaxException if the src attribute is invalid */ IRI getContentSrc(); /** * Returns the content type * * @return The content type */ Content.Type getContentType(); /** * Returns the media type of the content type or null if type equals 'text', 'html' or 'xhtml' * * @return The content media type */ MimeType getContentMimeType(); /** * Lists the complete set of contributors for this entry * * @return The listing of atom:contributor elements */ List<Person> getContributors(); /** * Adds an individual contributor to this entry * * @param person The atom:contributor element */ Entry addContributor(Person person); /** * Adds a contributor * * @param name The contributor name * @return The newly created atom:contributor */ Person addContributor(String name); /** * Adds an author * * @param name The contributor name * @param email The contributor's email address * @param uri The contributor's URI * @return The newly created atom:contributor * @throws IRISyntaxException if the uri is malformed */ Person addContributor(String name, String email, String uri); /** * Returns the universally unique identifier for this entry * * @return The atom:id element */ IRIElement getIdElement(); /** * Sets the universally unique identifier for this entry * * @param id The atom:id element */ Entry setIdElement(IRIElement id); /** * Returns the universally unique identifier for this entry * * @throws IRISyntaxException if the atom:id value is malformed */ IRI getId(); /** * Sets the universally unique identifier for this entry * * @param id The atom:id value * @return The newly created atom:id element * @throws IRISyntaxException if the atom:id value is malformed */ IRIElement setId(String id); /** * Creates a new randomized atom:id for the entry */ IRIElement newId(); /** * Sets the universally unique identifier for this entry * * @param id The atom:id value * @param normalize true if the atom:id value should be normalized as called for by RFC4287 * @return The newly created atom:id element * @throws IRISyntaxException if the atom:id value is malformed */ IRIElement setId(String id, boolean normalize); /** * Lists the complete set of links for this entry * * @return The listing of atom:link elements */ List<Link> getLinks(); /** * Lists the complete set of links using the specified rel attribute value * * @param rel The rel attribute value to look for * @return The listing of atom:link element's with the rel attribute */ List<Link> getLinks(String rel); /** * Lists the complete set of links using the specified rel attributes values * * @param rels A listing of link relations * @return A listof atom:link elements */ List<Link> getLinks(String... rel); /** * Adds an individual link to the entry * * @param link the atom:link to add */ Entry addLink(Link link); /** * Add a link to the entry * * @param href The IRI of the link * @return The newly created atom:link * @throws IRISyntaxException if the href is malformed */ Link addLink(String href); /** * Add a link to the entry * * @param href The IRI of the link * @param rel The link rel attribute * @return The newly created atom:link * @throws IRISyntaxException if the href is malformed */ Link addLink(String href, String rel); /** * Add a link to the entry * * @param href The IRI of the link * @param rel The link rel attribute * @param type The media type of the link * @param hreflang The language of the target * @param length The length of the resource * @return The newly created atom:link * @throws IRISyntaxException if the href is malformed */ Link addLink(String href, String rel, String type, String title, String hreflang, long length); /** * RFC4287: The "atom:published" element is a Date construct indicating an instant in time associated with an event * early in the life cycle of the entry... Typically, atom:published will be associated with the initial creation or * first availability of the resource. * * @return The atom:published element */ DateTime getPublishedElement(); /** * RFC4287: The "atom:published" element is a Date construct indicating an instant in time associated with an event * early in the life cycle of the entry... Typically, atom:published will be associated with the initial creation or * first availability of the resource. * * @param dateTime the atom:published element */ Entry setPublishedElement(DateTime dateTime); /** * Return the value of the atom:published element * * @return a java.util.Date for the atom:published value */ Date getPublished(); /** * Set the value of the atom:published element * * @param value The java.util.Date * @return The newly created atom:published element */ DateTime setPublished(Date value); /** * Set the value of the atom:published element using the serialized string value * * @param value The serialized date * @return The newly created atom:published element */ DateTime setPublished(String value); /** * <p> * The rights element is typically used to convey a human readable copyright (e.g. "&lt;atom:rights>Copyright (c), * 2006&lt;/atom:rights>). * </p> * <p> * RFC4287: The "atom:rights" element is a Text construct that conveys information about rights held in and over an * entry or feed. * </p> * * @return The atom:rights element */ Text getRightsElement(); /** * <p> * The rights element is typically used to convey a human readable copyright (e.g. "&lt;atom:rights>Copyright (c), * 2006&lt;/atom:rights>). * </p> * <p> * RFC4287: The "atom:rights" element is a Text construct that conveys information about rights held in and over an * entry or feed. * </p> * * @param text The atom:rights element */ Entry setRightsElement(Text text); /** * Sets the value of the rights as @type="text" * * @param value The text value of the atom:rights element * @return The newly created atom:rights element */ Text setRights(String value); /** * Sets the value of the rights as @type="html". Special characters like & will be automatically escaped * * @param value The text value of the atom:rights element. * @return The newly created atom:rights element */ Text setRightsAsHtml(String value); /** * Sets the value of the rights as @type="xhtml" * * @param value The text value of the atom:rights element * @return The newly created atom:rights element */ Text setRightsAsXhtml(String value); /** * Sets the value of the rights * * @param value The text value of the atom:rights element * @param type The text type * @return The newly create atom:rights element */ Text setRights(String value, Text.Type type); /** * Sets the value of the right as @type="xhtml" * * @param value The XHTML div for the atom:rights element * @return The newly created atom:rights element */ Text setRights(Div value); /** * Return the String value of the atom:rights element * * @return The text value of the atom:rights element */ String getRights(); /** * Return the @type of the atom:rights element * * @return The Text.Type of the atom:rights element */ Text.Type getRightsType(); /** * <p> * Returns the source element for this entry. * </p> * <p> * RFC4287: If an atom:entry is copied from one feed into another feed, then the source atom:feed's metadata (all * child elements of atom:feed other than the atom:entry elements) MAY be preserved within the copied entry by * adding an atom:source child element, if it is not already present in the entry, and including some or all of the * source feed's Metadata elements as the atom:source element's children. Such metadata SHOULD be preserved if the * source atom:feed contains any of the child elements atom:author, atom:contributor, atom:rights, or atom:category * and those child elements are not present in the source atom:entry. * </p> * * @return The atom:source element */ Source getSource(); /** * <p> * Returns the source element for this entry. * </p> * <p> * RFC4287: If an atom:entry is copied from one feed into another feed, then the source atom:feed's metadata (all * child elements of atom:feed other than the atom:entry elements) MAY be preserved within the copied entry by * adding an atom:source child element, if it is not already present in the entry, and including some or all of the * source feed's Metadata elements as the atom:source element's children. Such metadata SHOULD be preserved if the * source atom:feed contains any of the child elements atom:author, atom:contributor, atom:rights, or atom:category * and those child elements are not present in the source atom:entry. * </p> * * @param source The atom:source element */ Entry setSource(Source source); /** * RFC4287: The "atom:summary" element is a Text construct that conveys a short summary, abstract, or excerpt of an * entry... It is not advisable for the atom:summary element to duplicate atom:title or atom:content because Atom * Processors might assume there is a useful summary when there is none. * * @return The atom:summary element */ Text getSummaryElement(); /** * RFC4287: The "atom:summary" element is a Text construct that conveys a short summary, abstract, or excerpt of an * entry... It is not advisable for the atom:summary element to duplicate atom:title or atom:content because Atom * Processors might assume there is a useful summary when there is none. * * @param text The atom:summary element */ Entry setSummaryElement(Text text); /** * Sets the value of the summary as @type="text" * * @param value The text value of the atom:summary element * @return the newly created atom:summary element */ Text setSummary(String value); /** * Sets the value of the summary as @type="html" * * @param value The text value of the atom:summary element * @return the newly created atom:summary element */ Text setSummaryAsHtml(String value); /** * Sets the value of the summary as @type="xhtml" * * @param value The text value of the atom:summary element * @return the newly created atom:summary element */ Text setSummaryAsXhtml(String value); /** * Sets the value of the summary * * @param value The text value of the atom:summary element * @param type The Text.Type of the atom:summary element * @return The newly created atom:summary element */ Text setSummary(String value, Text.Type type); /** * Sets the value of the summary as @type="xhtml" * * @param value The XHTML div * @return the newly created atom:summary element */ Text setSummary(Div value); /** * Returns the text string value of this summary * * @return the text value of the atom:summary */ String getSummary(); /** * Returns the summary type * * @return the Text.Type of the atom:summary */ Text.Type getSummaryType(); /** * RFC4287: The "atom:title" element is a Text construct that conveys a human-readable title for an entry or feed. * * @return the atom:title element */ Text getTitleElement(); /** * RFC4287: The "atom:title" element is a Text construct that conveys a human-readable title for an entry or feed. * * @param title the atom:title element */ Entry setTitleElement(Text title); /** * Sets the value of the title as @type="text" * * @param value The title value * @return The newly created atom:title element */ Text setTitle(String value); /** * Sets the value of the title as @type="html" * * @param value The title value * @return The newly created atom:title element */ Text setTitleAsHtml(String value); /** * Sets the value of the title as @type="xhtml" * * @param value The title value * @return The newly created atom:title element */ Text setTitleAsXhtml(String value); /** * Sets the value of the title * * @param value The title value * @param type The Text.Type of the title * @return the newly created atom:title element */ Text setTitle(String value, Text.Type type); /** * Sets the value of the title as @type="xhtml" * * @param value The XHTML div * @return the newly created atom:title element */ Text setTitle(Div value); /** * Returns the text string value of the title element * * @return text value of the atom:title */ String getTitle(); /** * Returns the @type of this entries title * * @return the Text.Type of the atom:title */ Text.Type getTitleType(); /** * RFC4287: The "atom:updated" element is a Date construct indicating the most recent instant in time when an entry * or feed was modified in a way the publisher considers significant. Therefore, not all modifications necessarily * result in a changed atom:updated value. * * @return the atom:updated element */ DateTime getUpdatedElement(); /** * RFC4287: The "atom:updated" element is a Date construct indicating the most recent instant in time when an entry * or feed was modified in a way the publisher considers significant. Therefore, not all modifications necessarily * result in a changed atom:updated value. * * @param updated the atom:updated element. */ Entry setUpdatedElement(DateTime updated); /** * Return atom:updated * * @return A java.util.Date value */ Date getUpdated(); /** * Set the atom:updated value * * @param value The new value * @return The newly created atom:updated element */ DateTime setUpdated(Date value); /** * Set the atom:updated value * * @param value The new value * @return The newly created atom:updated element */ DateTime setUpdated(String value); /** * APP Introduces a new app:edited element whose value changes every time the entry is updated * * @return the app:edited element */ DateTime getEditedElement(); /** * Set the app:edited element * * @param modified The app:edited element */ void setEditedElement(DateTime modified); /** * Return the value of app:edited * * @return app:edited */ Date getEdited(); /** * Set the value of app:edited * * @param value The java.util.Date value * @return The newly created app:edited element */ DateTime setEdited(Date value); /** * Set the value of app:edited * * @param value the serialized string value for app:edited * @return The newly created app:edited element */ DateTime setEdited(String value); /** * Returns this entries Atom Publishing Protocol control element. A new control element will be created if one * currently does not exist * * @return The app:control element */ Control getControl(boolean create); /** * Returns this entries Atom Publishing Protocol control element * * @return The app:control element */ Control getControl(); /** * Sets this entries Atom Publishing Protocol control element * * @param control The app:contorl element */ Entry setControl(Control control); /** * Sets whether or not this entry is a draft * * @param draft true if this entry should be marked as a draft */ Entry setDraft(boolean draft); /** * Returns true if this entry is a draft * * @return True if this entry is a date */ boolean isDraft(); /** * Returns the first link with the specified rel attribute value * * @param rel The link rel * @return a Link with the specified rel attribute */ Link getLink(String rel); /** * Returns this entries first alternate link * * @return the Alternate link */ Link getAlternateLink(); /** * Returns the first alternate link matching the specified type and hreflang * * @throws MimeTypeParseException * @param type The link media type * @param hreflang The link target language * @return The matching atom:link * @throws MimeTypeParseException if the type is malformed */ Link getAlternateLink(String type, String hreflang); /** * Returns this entries first enclosure link * * @return the Enclosure link */ Link getEnclosureLink(); /** * Returns this entries first edit link * * @return the Edit Link */ Link getEditLink(); /** * Returns this entries first edit-media link (if any) * * @return the Edit Media Link */ Link getEditMediaLink(); /** * Returns the first edit-media link matching the specified type and hreflang * * @param type a media type * @param hreflang a target language * @return A matching atom:link element * @throws MimeTypeParseException */ Link getEditMediaLink(String type, String hreflang); /** * Returns this entries first self link * * @return the Self Link */ Link getSelfLink(); /** * Return a link href resolved against the in-scope Base URI * * @param rel The rel attribute value * @return The resolved IRI * @throws IRISyntaxException if the href attribute is malformed */ IRI getLinkResolvedHref(String rel); /** * Return a link href resolved against the in-scope Base URI * * @return The resolved IRI * @throws IRISyntaxException if the href attribute is malformed */ IRI getAlternateLinkResolvedHref(); /** * Return a link href resolved against the in-scope Base URI * * @param type A target type * @param hreflang A target language * @return The resolved IRI * @throws IRISyntaxException if the href attribute is malformed */ IRI getAlternateLinkResolvedHref(String type, String hreflang); /** * Return a link href resolved against the in-scope Base URI * * @return The resolved IRI * @throws IRISyntaxException if the href attribute is malformed */ IRI getEnclosureLinkResolvedHref(); /** * Return a link href resolved against the in-scope Base URI * * @return The resolved IRI * @throws IRISyntaxException if the href attribute is malformed */ IRI getEditLinkResolvedHref(); /** * Return a link href resolved against the in-scope Base URI * * @return The resolved IRI * @throws IRISyntaxException if the href attribute is malformed */ IRI getEditMediaLinkResolvedHref(); /** * Return a link href resolved against the in-scope Base URI * * @param type A target type * @param hreflang A target language * @return The resolved IRI * @throws IRISyntaxException if the href attribute is malformed * @throws MimeTypeParseException if the type is malformed */ IRI getEditMediaLinkResolvedHref(String type, String hreflang); /** * Return a link href resolved against the in-scope Base URI * * @return The resolved IRI * @throws IRISyntaxException if the href attribute is malformed */ IRI getSelfLinkResolvedHref(); Control addControl(); }
7,226
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/PersonWrapper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import javax.xml.namespace.QName; import org.apache.abdera.factory.Factory; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.util.Constants; /** * ElementWrapper implementation that implements the Person interface. Used to create static extensions based on the * Atom Person Construct */ public abstract class PersonWrapper extends ExtensibleElementWrapper implements Person, Constants { protected PersonWrapper(Element internal) { super(internal); } public PersonWrapper(Factory factory, QName qname) { super(factory, qname); } public String getEmail() { Element email = getEmailElement(); return (email != null) ? email.getText() : null; } public Element getEmailElement() { return getInternal().getFirstChild(EMAIL); } public String getName() { Element name = getNameElement(); return (name != null) ? name.getText() : null; } public Element getNameElement() { return getInternal().getFirstChild(NAME); } public IRI getUri() { IRIElement iri = getUriElement(); return (iri != null) ? iri.getResolvedValue() : null; } public IRIElement getUriElement() { return getInternal().getFirstChild(URI); } public Element setEmail(String email) { ExtensibleElement internal = getExtInternal(); Element el = getEmailElement(); if (email != null) { if (el == null) el = internal.getFactory().newEmail(internal); el.setText(email); return el; } else { if (el != null) el.discard(); return null; } } public Person setEmailElement(Element element) { ExtensibleElement internal = getExtInternal(); Element el = getEmailElement(); if (el != null) el.discard(); if (element != null) internal.addExtension(element); return this; } public Element setName(String name) { ExtensibleElement internal = getExtInternal(); Element el = getNameElement(); if (name != null) { if (el == null) el = internal.getFactory().newName(internal); el.setText(name); return el; } else { if (el != null) el.discard(); return null; } } public Person setNameElement(Element element) { ExtensibleElement internal = getExtInternal(); Element el = getNameElement(); if (el != null) el.discard(); if (element != null) internal.addExtension(element); return this; } public IRIElement setUri(String uri) { ExtensibleElement internal = getExtInternal(); IRIElement el = getUriElement(); if (uri != null) { if (el == null) el = internal.getFactory().newUri(internal); el.setText(uri.toString()); return el; } else { if (el != null) el.discard(); return null; } } public Person setUriElement(IRIElement element) { ExtensibleElement internal = getExtInternal(); Element el = getUriElement(); if (el != null) el.discard(); if (element != null) internal.addExtension(element); return this; } }
7,227
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/Content.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import javax.activation.DataHandler; import javax.activation.MimeType; import org.apache.abdera.util.MimeTypeHelper; import org.apache.abdera.i18n.iri.IRI; /** * <p> * Represents an atom:content element. * </p> * <p> * Atom has a very clearly defined and extremely flexible content model. The model allows for five basic types of * content: * </p> * <ul> * <li>Text, consisting of content that is to be interpreted as plain text with no markup. For instance, * <code>&lt;content type="text">&amp;lt;content&amp;gt;&lt;/content></code> is interpreted as literal characer "&lt;" * followed by the word "content", followed by the literal character "&gt;".</li> * <li>HTML, consisting of content that is to be interpreted as escaped HTML markup. For instance, * <code>&lt;content type="html">&amp;lt;b&amp;gt;content&amp;lt;/b&amp;gt;&lt;/content></code> is interpreted as the * word "content" surrounded by the HTML <code>&lt;b&gt;</code> and <code>&lt;/b&gt;</code> tags.</li> * <li>XHTML, consisting of well-formed XHTML content wrapped in an XHTML div element. For instance, * <code>&lt;content type="xhtml">&lt;div xmlns="http://www.w3.org/1999/xhtml">&lt;b>Content&lt;/b>&lt;/div>&lt;/content></code> * .</li> * <li>XML, consisting of well-formed XML content. For instance, * <code>&lt;content type="application/xml">&lt;a xmlns="...">&lt;b>&lt;c/>&lt;/b>&lt;/a>&lt;/content></code>. The * content could, alternatively, be linked to via the src attribute, * <code>&lt;content type="application/xml" src="http://example.org/foo.xml"/></code>.</li> * <li>Media, consisting of content conforming to any MIME media type. * <ul> * <li>Text media types are encoded literally, e.g. * <code>&lt;content type="text/calendar">BEGIN:VCALENDAR...&lt;/content></code>.</li> * <li>Other media types are encoded as Base64 strings, e.g. * <code>&lt;content type="image/jpeg">{Base64}&lt;/content></code>.</li> * <li>Alternatively, media content may use the src attribute, * <code>&lt;content type="text/calendar" src="http://example.org/foo.cal"/></code>, * <code>&lt;content type="image/jpeg" src="http://example.org/foo.jpg" /></code></li> * </ul> * </li> * </ul> * <p> * Per RFC4287: * </p> * * <pre> * The "atom:content" element either contains or links to the content of * the entry. The content of atom:content is Language-Sensitive. * * atomInlineTextContent = * element atom:content { * atomCommonAttributes, * attribute type { "text" | "html" }?, * (text)* * } * * atomInlineXHTMLContent = * element atom:content { * atomCommonAttributes, * attribute type { "xhtml" }, * xhtmlDiv * } * atomInlineOtherContent = * element atom:content { * atomCommonAttributes, * attribute type { atomMediaType }?, * (text|anyElement)* * } * * atomOutOfLineContent = * element atom:content { * atomCommonAttributes, * attribute type { atomMediaType }?, * attribute src { atomUri }, * empty * } * * atomContent = atomInlineTextContent * | atomInlineXHTMLContent * | atomInlineOtherContent * | atomOutOfLineContent * * </pre> */ public interface Content extends Element { /** * Used to identify the type of content */ public enum Type { /** Plain text **/ TEXT, /** Escaped HTML **/ HTML, /** Welformed XHTML **/ XHTML, /** Welformed XML **/ XML, /** Base64-encoded Binary **/ MEDIA; /** * Return an appropriate Type given the specified @type attribute value */ public static Type typeFromString(String val) { Type type = TEXT; if (val != null) { if (val.equalsIgnoreCase("text")) type = TEXT; else if (val.equalsIgnoreCase("html")) type = HTML; else if (val.equalsIgnoreCase("xhtml")) type = XHTML; else if (MimeTypeHelper.isXml(val)) type = XML; else { type = MimeTypeHelper.isMimeType(val) ? MEDIA : null; } } return type; } } /** * Returns the Content Type * * @return The Content Type */ Type getContentType(); /** * Set the Content Type * * @param type The Content Type */ Content setContentType(Type type); /** * Return the value element or null if type="text", type="html" or type is some non-XML media type * * @return The first child element of the atom:content element or null */ <T extends Element> T getValueElement(); /** * Set the value element of the content. If the value is a Div, the type attribute will be set to type="xhtml", * otherwise, the attribute will be set to type="application/xml" * * @param value The element to set */ <T extends Element> Content setValueElement(T value); /** * RFC4287: On the atom:content element, the value of the "type" attribute MAY be one of "text", "html", or "xhtml". * Failing that, it MUST conform to the syntax of a MIME media type, but MUST NOT be a composite type. If neither * the type attribute nor the src attribute is provided, Atom Processors MUST behave as though the type attribute * were present with a value of "text". * * @return null if type = text, html or xhtml, otherwise a media type */ MimeType getMimeType(); /** * RFC4287: On the atom:content element, the value of the "type" attribute MAY be one of "text", "html", or "xhtml". * Failing that, it MUST conform to the syntax of a MIME media type, but MUST NOT be a composite type. If neither * the type attribute nor the src attribute is provided, Atom Processors MUST behave as though the type attribute * were present with a value of "text". * * @param type The media type * @throws MimeTypeParseException if the media type is malformed */ Content setMimeType(String type); /** * <p> * RFC4287: atom:content MAY have a "src" attribute, whose value MUST be an IRI reference. If the "src" attribute is * present, atom:content MUST be empty. Atom Processors MAY use the IRI to retrieve the content and MAY choose to * ignore remote content or to present it in a different manner than local content. * </p> * <p> * If the "src" attribute is present, the "type" attribute SHOULD be provided and MUST be a MIME media type, rather * than "text", "html", or "xhtml". * </p> * * @return The IRI value of the src attribute or null if none * @throws IRISyntaxException if the src attribute value is malformed */ IRI getSrc(); /** * Returns the fully qualified URI form of the content src attribute. * * @return The IRI value of the src attribute resolved against the in-scope Base URI * @throws IRISyntaxException if the src attribute value is malformed */ IRI getResolvedSrc(); /** * <p> * RFC4287: atom:content MAY have a "src" attribute, whose value MUST be an IRI reference. If the "src" attribute is * present, atom:content MUST be empty. Atom Processors MAY use the IRI to retrieve the content and MAY choose to * ignore remote content or to present it in a different manner than local content. * </p> * <p> * If the "src" attribute is present, the "type" attribute SHOULD be provided and MUST be a MIME media type, rather * than "text", "html", or "xhtml". * </p> * * @param src The IRI to use as the src attribute value for the content * @throws IRISyntaxException if the src value is malformed */ Content setSrc(String src); /** * Attempts to Base64 decode the string value of the content element. * * @return A DataHandler or null * @throws UnsupportedOperationException if type = text, html, xhtml, or any application/*+xml, or text/* type */ DataHandler getDataHandler(); /** * Sets the string value of the content element by Base64 encoding the specifed byte array. * * @param dataHandler The DataHandler for the binary content requiring Base64 encoding * @throws UnsupportedOperationException if type = text, html, xhtml, or any application/*+xml, or text/* type */ Content setDataHandler(DataHandler dataHandler); /** * Returns the string value of this atom:content element * * @return The string value */ String getValue(); /** * Set the string value of the atom:content element * * @param value The string value */ Content setValue(String value); /** * Return the string value of the atom:content element with the enclosing div tag if type="xhtml" * * @return The div wrapped value */ String getWrappedValue(); /** * Set the string value of the atom:content with the enclosing div tag * * @param wrappedValue The string value with the wrapping div tag */ Content setWrappedValue(String wrappedValue); }
7,228
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/Categories.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import java.util.List; import org.apache.abdera.i18n.iri.IRI; /** * The Atom Publishing Protocol introduces the notion of a "Category Document" and the app:categories element. These are * used to provide a listing of atom:category elements that may be used with the members of an Atom Publishing Protocol * collection. */ public interface Categories extends ExtensibleElement { /** * When contained within an app:collection element, the app:categories element can have an href attribute whose * value MUST point to an Atompub Categories Document. * * @return The href attribute value */ IRI getHref(); /** * Returns the value of the href attribute resolved against the in-scope Base URI * * @return The fully resolved href attribute value */ IRI getResolvedHref(); /** * Sets the value of the href attribute. * * @param href The location of an Atompub Categories Document */ Categories setHref(String href); /** * If an app:categories element is marked as fixed, then the set of atom:category elements is considered to be a * closed set. That is, Atom Publishing Protocol clients SHOULD only use the atom:category elements listed. The * default is false (fixed="no") * * @return True if the categories listing is fixed */ boolean isFixed(); /** * Sets whether or not this is a fixed listing of categories. If set to false, the fixed attribute will be removed * from the app:categories element. * * @param fixed True if the app:categories listing is fixed */ Categories setFixed(boolean fixed); /** * The app:categories element may specify a default scheme attribute for listed atom:category elements that do not * have their own scheme attribute. * * @return The scheme IRI */ IRI getScheme(); /** * Sets the default scheme for this listing of categories * * @param scheme The default scheme used for this listing of categories */ Categories setScheme(String scheme); /** * Lists the complete set of categories * * @return This app:categories listing of atom:category elements */ List<Category> getCategories(); /** * Lists the complete set of categories that use the specified scheme * * @param scheme The IRI of an atom:category scheme * @return A listing of atom:category elements that use the specified scheme */ List<Category> getCategories(String scheme); /** * Returns a copy of the complete set of categories with the scheme attribute set * * @return A listing of atom:category elements using the default scheme specified by the app:categories scheme * attribute */ List<Category> getCategoriesWithScheme(); /** * Returns a copy of the complete set of categories with the scheme attribute set as specified in 7.2.1. (child * categories that do not have a scheme attribute inherit the scheme attribute of the parent) * * @param scheme A scheme IRI * @return A listing of atom:category elements */ List<Category> getCategoriesWithScheme(String scheme); /** * Add an atom:category to the listing * * @param category The atom:category to add to the listing */ Categories addCategory(Category category); /** * Create and add an atom:category to the listing * * @param term The string term * @return The newly created atom:category */ Category addCategory(String term); /** * Create an add an atom:category to the listing * * @param scheme The scheme IRI for the newly created category * @param term The string term * @param label The human readable label for the category * @return The newly created atom:category */ Category addCategory(String scheme, String term, String label); /** * Returns true if this app:categories listing contains a category with the specified term * * @param term The term to look for * @return True if the term is found */ boolean contains(String term); /** * Returns true if this app:categories listing contains a category with the specified term and scheme * * @param term The term to look for * @param scheme The IRI scheme * @return True if the term and scheme are found */ boolean contains(String term, String scheme); /** * Returns true if the href attribute is set */ boolean isOutOfLine(); }
7,229
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/model/Generator.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.model; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.iri.IRISyntaxException; /** * <p> * Identifies the software implementation that produced the Atom feed. * </p> * <p> * Per RFC4287: * </p> * * <pre> * The "atom:generator" element's content identifies the agent used to * generate a feed, for debugging and other purposes. * The content of this element, when present, MUST be a string that is a * human-readable name for the generating agent. Entities such as * "&amp;amp;" and "&amp;lt;" represent their corresponding characters * ("&amp;" and "&lt;" respectively), not markup. * * The atom:generator element MAY have a "uri" attribute whose value * MUST be an IRI reference [RFC3987]. When dereferenced, the resulting * URI (mapped from an IRI, if necessary) SHOULD produce a * representation that is relevant to that agent. * * The atom:generator element MAY have a "version" attribute that * indicates the version of the generating agent. * </pre> */ public interface Generator extends Element { /** * The atom:generator element MAY have a "uri" attribute whose value MUST be an IRI reference [RFC3987]. When * dereferenced, the resulting URI (mapped from an IRI, if necessary) SHOULD produce a representation that is * relevant to that agent. * * @throws IRISyntaxException if the uri is malformed */ IRI getUri(); /** * Returns the fully qualified form of the generator element's uri attribute (resolved against the in-scope Base * URI) * * @return the resolved uri value * @throws IRISyntaxException if the uri is malformed */ IRI getResolvedUri(); /** * The atom:generator element MAY have a "uri" attribute whose value MUST be an IRI reference [RFC3987]. When * dereferenced, the resulting URI (mapped from an IRI, if necessary) SHOULD produce a representation that is * relevant to that agent. * * @param uri The URI attribute value * @throws IRISyntaxException if the uri is malformed */ Generator setUri(String uri); /** * The atom:generator element MAY have a "version" attribute that indicates the version of the generating agent. * * @return The version attribute value */ String getVersion(); /** * The atom:generator element MAY have a "version" attribute that indicates the version of the generating agent. * * @param version The version attribute */ Generator setVersion(String version); }
7,230
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/filter/ListParseFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.filter; import javax.xml.namespace.QName; /** * A ParseFilter that is based on an internal collection of QName's. */ public interface ListParseFilter extends ParseFilter { /** * Add an element QName to the parse filter */ ListParseFilter add(QName qname); /** * Returns true if the given qname has been added to the filter */ boolean contains(QName qname); /** * Adds an attribute to the parse filter */ ListParseFilter add(QName parent, QName attribute); /** * Returns true if the given attribute has been added to the filter */ boolean contains(QName qname, QName attribute); }
7,231
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/filter/ParseFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.filter; import java.io.Serializable; import javax.xml.namespace.QName; /** * ParseFilter's determine which elements and attributes are acceptable within a parsed document. They are set via the * ParserOptions.setParseFilter method. */ public interface ParseFilter extends Cloneable, Serializable { /** * Clone this ParseFilter */ Object clone() throws CloneNotSupportedException; /** * Returns true if elements with the given QName are acceptable */ boolean acceptable(QName qname); /** * Returns true if attributes with the given qname appearing on elements with the given qname are acceptable */ boolean acceptable(QName qname, QName attribute); /** * Return true if the parser should ignore comments */ boolean getIgnoreComments(); /** * Return true if the parser should ignore insignificant whitespace */ boolean getIgnoreWhitespace(); /** * Return true if the parser should ignore processing instructions */ boolean getIgnoreProcessingInstructions(); /** * True if the parser should ignore comments */ ParseFilter setIgnoreComments(boolean ignore); /** * True if the parser should ignore insignificant whitespace */ ParseFilter setIgnoreWhitespace(boolean ignore); /** * True if the parser should ignore processing instructions */ ParseFilter setIgnoreProcessingInstructions(boolean ignore); }
7,232
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/factory/ExtensionFactory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.factory; import org.apache.abdera.model.Base; import org.apache.abdera.model.Element; /** * <p> * Extension Factories are used to provide a means of dynamically resolving builders for namespaced extension elements * </p> * <p> * There are four ways of supporting extension elements. * </p> * <ol> * <li>Implement your own Factory (hard)</li> * <li>Subclass the default Axiom-based Factory (also somewhat difficult)</li> * <li>Implement and register an ExtensionFactory (wonderfully simple)</li> * <li>Use the Feed Object Model's dynamic support for extensions (also very simple)</li> * </ol> * <p> * Registering an Extension Factory requires generally nothing more than implementing ExtensionFactory and then creating * a file called META-INF/services/org.apache.abdera.factory.ExtensionFactory and listing the class names of each * ExtensionFactory you wish to register. * </p> * <p> * ExtensionFactory implementations are assumed to be threadsafe * </p> */ public interface ExtensionFactory { /** * Returns true if this extension factory handles the specified namespace * * @param namespace The XML namespace of the extension * @return True if the namespace is supported by the ExtensionFactory */ boolean handlesNamespace(String namespace); /** * Returns the Namespace URIs handled by this Extension Factory * * @return A List of Namespace URIs Supported by this Extension */ String[] getNamespaces(); /** * Abdera's support for static extensions is based on a simple delegation model. Static extension interfaces wrap * the dynamic extension API. ExtensionFactory's are handed the internal dynamic element instance and are expected * to hand back an object wrapper. * * @param internal The Abdera element that needs to be wrapped * @return The wrapper element */ <T extends Element> T getElementWrapper(Element internal); /** * Retrieve the mime type for the element * * @param base An Abdera object * @return A MIME media type for the object */ <T extends Base> String getMimeType(T base); }
7,233
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/factory/ExtensionFactoryMap.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.factory; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.apache.abdera.model.Base; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; /** * A utility implementation of ExtensionFactory used internally by Abdera. It maintains the collection ExtensionFactory * instances discovered on the classpath and a cache of Internal-Wrapper mappings. */ public class ExtensionFactoryMap implements ExtensionFactory { private final List<ExtensionFactory> factories; public ExtensionFactoryMap(List<ExtensionFactory> factories) { this.factories = Collections.synchronizedList(factories); } @SuppressWarnings("unchecked") public <T extends Element> T getElementWrapper(Element internal) { if (internal == null) return null; T t = null; synchronized (factories) { for (ExtensionFactory factory : factories) { t = (T)factory.getElementWrapper(internal); if (t != null && t != internal) { return t; } } } return (t != null) ? t : (T)internal; } public String[] getNamespaces() { List<String> ns = new ArrayList<String>(); synchronized (factories) { for (ExtensionFactory factory : factories) { String[] namespaces = factory.getNamespaces(); for (String uri : namespaces) { if (!ns.contains(uri)) ns.add(uri); } } } return ns.toArray(new String[ns.size()]); } public boolean handlesNamespace(String namespace) { synchronized (factories) { for (ExtensionFactory factory : factories) { if (factory.handlesNamespace(namespace)) return true; } } return false; } public ExtensionFactoryMap addFactory(ExtensionFactory factory) { if (!factories.contains(factory)) factories.add(factory); return this; } public <T extends Base> String getMimeType(T base) { Element element = base instanceof Element ? (Element)base : ((Document<?>)base).getRoot(); String namespace = element.getQName().getNamespaceURI(); synchronized (factories) { for (ExtensionFactory factory : factories) { if (factory.handlesNamespace(namespace)) return factory.getMimeType(base); } } return null; } public String[] listExtensionFactories() { List<String> names = new ArrayList<String>(); synchronized (factories) { for (ExtensionFactory factory : factories) { String name = factory.getClass().getName(); if (!names.contains(name)) names.add(name); } } return names.toArray(new String[names.size()]); } }
7,234
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/factory/StreamBuilder.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.factory; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Writer; import java.nio.channels.WritableByteChannel; import java.util.Date; import java.util.Locale; import javax.activation.DataHandler; import javax.xml.namespace.QName; import org.apache.abdera.Abdera; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.rfc4646.Lang; import org.apache.abdera.model.Base; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.model.Content.Type; import org.apache.abdera.util.AbstractStreamWriter; /** * StreamBuilder is a special implementation of the StreamWriter interface that can be used to create Feed Object Model * instances using the StreamWriter interface. StreamBuilder provides an additional method (getBase) for returning the * FOM Base element that was built. The StreamWriter methods indent(), flush(), close(), setWriter(), setInputStream, * setAutoclose(), setAutoflush(), setAutoIndent(), and setChannel() have no effect on this StreamWriter implementation * * <pre> * StreamBuilder sw = new StreamBuilder(); * Entry entry = * sw.startElement(Constants.ENTRY).writeBase(&quot;http://example.org&quot;).writeLanguage(&quot;en-US&quot;) * .writeId(&quot;http://example.org&quot;).writeTitle(&quot;testing&quot;).writeUpdated(new Date()).endElement().getBase(); * entry.writeTo(System.out); * </pre> */ @SuppressWarnings("unchecked") public class StreamBuilder extends AbstractStreamWriter { private final Abdera abdera; private Base root = null; private Base current = null; public StreamBuilder() { this(Abdera.getInstance()); } public StreamBuilder(Abdera abdera) { super(abdera, "fom"); this.abdera = abdera; } public <T extends Base> T getBase() { return (T)root; } public StreamBuilder startDocument(String xmlversion, String charset) { if (root != null) throw new IllegalStateException("Document already started"); root = abdera.getFactory().newDocument(); ((Document)root).setCharset(charset); current = root; return this; } public StreamBuilder startDocument(String xmlversion) { return startDocument(xmlversion, "UTF-8"); } private static QName getQName(String name, String namespace, String prefix) { if (prefix != null) return new QName(namespace, name, prefix); else if (namespace != null) return new QName(namespace, name); else return new QName(name); } public StreamBuilder startElement(String name, String namespace, String prefix) { current = abdera.getFactory().newElement(getQName(name, namespace, prefix), current); if (root == null) root = current; return this; } public StreamBuilder endElement() { current = current instanceof Element ? ((Element)current).getParentElement() : null; return this; } public StreamBuilder writeAttribute(String name, String namespace, String prefix, String value) { if (!(current instanceof Element)) throw new IllegalStateException("Not currently an element"); ((Element)current).setAttributeValue(getQName(name, namespace, prefix), value); return this; } public StreamBuilder writeComment(String value) { current.addComment(value); return this; } public StreamBuilder writeElementText(String value) { if (!(current instanceof Element)) throw new IllegalStateException("Not currently an element"); Element element = (Element)current; String text = element.getText(); element.setText(text + value); return this; } public StreamBuilder writeId() { return writeId(abdera.getFactory().newUuidUri()); } public StreamBuilder writePI(String value) { return writePI(value, null); } public StreamBuilder writePI(String value, String target) { if (!(current instanceof Document)) throw new IllegalStateException("Not currently a document"); ((Document)current).addProcessingInstruction(target != null ? target : "", value); return this; } public void close() throws IOException { } public StreamBuilder flush() { // non-op return this; } public StreamBuilder indent() { // non-op return this; } public StreamBuilder setOutputStream(OutputStream out) { // non-op return this; } public StreamBuilder setOutputStream(OutputStream out, String charset) { // non-op return this; } public StreamBuilder setWriter(Writer writer) { // non-op return this; } public StreamBuilder endAuthor() { return (StreamBuilder)super.endAuthor(); } public StreamBuilder endCategories() { return (StreamBuilder)super.endCategories(); } public StreamBuilder endCategory() { return (StreamBuilder)super.endCategory(); } public StreamBuilder endCollection() { return (StreamBuilder)super.endCollection(); } public StreamBuilder endContent() { return (StreamBuilder)super.endContent(); } public StreamBuilder endContributor() { return (StreamBuilder)super.endContributor(); } public StreamBuilder endControl() { return (StreamBuilder)super.endControl(); } public StreamBuilder endDocument() { return (StreamBuilder)super.endDocument(); } public StreamBuilder endEntry() { return (StreamBuilder)super.endEntry(); } public StreamBuilder endFeed() { return (StreamBuilder)super.endFeed(); } public StreamBuilder endGenerator() { return (StreamBuilder)super.endGenerator(); } public StreamBuilder endLink() { return (StreamBuilder)super.endLink(); } public StreamBuilder endPerson() { return (StreamBuilder)super.endPerson(); } public StreamBuilder endService() { return (StreamBuilder)super.endService(); } public StreamBuilder endSource() { return (StreamBuilder)super.endSource(); } public StreamBuilder endText() { return (StreamBuilder)super.endText(); } public StreamBuilder endWorkspace() { return (StreamBuilder)super.endWorkspace(); } public StreamBuilder setAutoclose(boolean auto) { return (StreamBuilder)super.setAutoclose(auto); } public StreamBuilder setAutoflush(boolean auto) { return (StreamBuilder)super.setAutoflush(auto); } public StreamBuilder setAutoIndent(boolean indent) { return (StreamBuilder)super.setAutoIndent(indent); } public StreamBuilder setChannel(WritableByteChannel channel, String charset) { return (StreamBuilder)super.setChannel(channel, charset); } public StreamBuilder setChannel(WritableByteChannel channel) { return (StreamBuilder)super.setChannel(channel); } public StreamBuilder startAuthor() { return (StreamBuilder)super.startAuthor(); } public StreamBuilder startCategories() { return (StreamBuilder)super.startCategories(); } public StreamBuilder startCategories(boolean fixed, String scheme) { return (StreamBuilder)super.startCategories(fixed, scheme); } public StreamBuilder startCategories(boolean fixed) { return (StreamBuilder)super.startCategories(fixed); } public StreamBuilder startCategory(String term, String scheme, String label) { return (StreamBuilder)super.startCategory(term, scheme, label); } public StreamBuilder startCategory(String term, String scheme) { return (StreamBuilder)super.startCategory(term, scheme); } public StreamBuilder startCategory(String term) { return (StreamBuilder)super.startCategory(term); } public StreamBuilder startCollection(String href) { return (StreamBuilder)super.startCollection(href); } public StreamBuilder startContent(String type, String src) { return (StreamBuilder)super.startContent(type, src); } public StreamBuilder startContent(String type) { return (StreamBuilder)super.startContent(type); } public StreamBuilder startContent(Type type, String src) { return (StreamBuilder)super.startContent(type, src); } public StreamBuilder startContent(Type type) { return (StreamBuilder)super.startContent(type); } public StreamBuilder startContributor() { return (StreamBuilder)super.startContributor(); } public StreamBuilder startControl() { return (StreamBuilder)super.startControl(); } public StreamBuilder startDocument() { return (StreamBuilder)super.startDocument(); } public StreamBuilder startElement(QName qname) { return (StreamBuilder)super.startElement(qname); } public StreamBuilder startElement(String name, String namespace) { return (StreamBuilder)super.startElement(name, namespace); } public StreamBuilder startElement(String name) { return (StreamBuilder)super.startElement(name); } public StreamBuilder startEntry() { return (StreamBuilder)super.startEntry(); } public StreamBuilder startFeed() { return (StreamBuilder)super.startFeed(); } public StreamBuilder startGenerator(String version, String uri) { return (StreamBuilder)super.startGenerator(version, uri); } public StreamBuilder startLink(String iri, String rel, String type, String title, String hreflang, long length) { return (StreamBuilder)super.startLink(iri, rel, type, title, hreflang, length); } public StreamBuilder startLink(String iri, String rel, String type) { return (StreamBuilder)super.startLink(iri, rel, type); } public StreamBuilder startLink(String iri, String rel) { return (StreamBuilder)super.startLink(iri, rel); } public StreamBuilder startLink(String iri) { return (StreamBuilder)super.startLink(iri); } public StreamBuilder startPerson(QName qname) { return (StreamBuilder)super.startPerson(qname); } public StreamBuilder startPerson(String name, String namespace, String prefix) { return (StreamBuilder)super.startPerson(name, namespace, prefix); } public StreamBuilder startPerson(String name, String namespace) { return (StreamBuilder)super.startPerson(name, namespace); } public StreamBuilder startPerson(String name) { return (StreamBuilder)super.startPerson(name); } public StreamBuilder startService() { return (StreamBuilder)super.startService(); } public StreamBuilder startSource() { return (StreamBuilder)super.startSource(); } public StreamBuilder startText(QName qname, org.apache.abdera.model.Text.Type type) { return (StreamBuilder)super.startText(qname, type); } public StreamBuilder startText(String name, String namespace, String prefix, org.apache.abdera.model.Text.Type type) { return (StreamBuilder)super.startText(name, namespace, prefix, type); } public StreamBuilder startText(String name, String namespace, org.apache.abdera.model.Text.Type type) { return (StreamBuilder)super.startText(name, namespace, type); } public StreamBuilder startText(String name, org.apache.abdera.model.Text.Type type) { return (StreamBuilder)super.startText(name, type); } public StreamBuilder startWorkspace() { return (StreamBuilder)super.startWorkspace(); } public StreamBuilder writeAccepts(String... accepts) { return (StreamBuilder)super.writeAccepts(accepts); } public StreamBuilder writeAcceptsEntry() { return (StreamBuilder)super.writeAcceptsEntry(); } public StreamBuilder writeAcceptsNothing() { return (StreamBuilder)super.writeAcceptsNothing(); } public StreamBuilder writeAttribute(QName qname, Date value) { return (StreamBuilder)super.writeAttribute(qname, value); } public StreamBuilder writeAttribute(QName qname, double value) { return (StreamBuilder)super.writeAttribute(qname, value); } public StreamBuilder writeAttribute(QName qname, int value) { return (StreamBuilder)super.writeAttribute(qname, value); } public StreamBuilder writeAttribute(QName qname, long value) { return (StreamBuilder)super.writeAttribute(qname, value); } public StreamBuilder writeAttribute(QName qname, String value) { return (StreamBuilder)super.writeAttribute(qname, value); } public StreamBuilder writeAttribute(String name, Date value) { return (StreamBuilder)super.writeAttribute(name, value); } public StreamBuilder writeAttribute(String name, double value) { return (StreamBuilder)super.writeAttribute(name, value); } public StreamBuilder writeAttribute(String name, int value) { return (StreamBuilder)super.writeAttribute(name, value); } public StreamBuilder writeAttribute(String name, long value) { return (StreamBuilder)super.writeAttribute(name, value); } public StreamBuilder writeAttribute(String name, String namespace, Date value) { return (StreamBuilder)super.writeAttribute(name, namespace, value); } public StreamBuilder writeAttribute(String name, String namespace, double value) { return (StreamBuilder)super.writeAttribute(name, namespace, value); } public StreamBuilder writeAttribute(String name, String namespace, int value) { return (StreamBuilder)super.writeAttribute(name, namespace, value); } public StreamBuilder writeAttribute(String name, String namespace, long value) { return (StreamBuilder)super.writeAttribute(name, namespace, value); } public StreamBuilder writeAttribute(String name, String namespace, String prefix, Date value) { return (StreamBuilder)super.writeAttribute(name, namespace, prefix, value); } public StreamBuilder writeAttribute(String name, String namespace, String prefix, double value) { return (StreamBuilder)super.writeAttribute(name, namespace, prefix, value); } public StreamBuilder writeAttribute(String name, String namespace, String prefix, int value) { return (StreamBuilder)super.writeAttribute(name, namespace, prefix, value); } public StreamBuilder writeAttribute(String name, String namespace, String prefix, long value) { return (StreamBuilder)super.writeAttribute(name, namespace, prefix, value); } public StreamBuilder writeAttribute(String name, String namespace, String value) { return (StreamBuilder)super.writeAttribute(name, namespace, value); } public StreamBuilder writeAttribute(String name, String value) { return (StreamBuilder)super.writeAttribute(name, value); } public StreamBuilder writeAuthor(String name, String email, String uri) { return (StreamBuilder)super.writeAuthor(name, email, uri); } public StreamBuilder writeAuthor(String name) { return (StreamBuilder)super.writeAuthor(name); } public StreamBuilder writeBase(IRI iri) { return (StreamBuilder)super.writeBase(iri); } public StreamBuilder writeBase(String iri) { return (StreamBuilder)super.writeBase(iri); } public StreamBuilder writeCategory(String term, String scheme, String label) { return (StreamBuilder)super.writeCategory(term, scheme, label); } public StreamBuilder writeCategory(String term, String scheme) { return (StreamBuilder)super.writeCategory(term, scheme); } public StreamBuilder writeCategory(String term) { return (StreamBuilder)super.writeCategory(term); } public StreamBuilder writeContent(String type, String value) { return (StreamBuilder)super.writeContent(type, value); } public StreamBuilder writeContent(Type type, DataHandler value) throws IOException { return (StreamBuilder)super.writeContent(type, value); } public StreamBuilder writeContent(Type type, InputStream value) throws IOException { return (StreamBuilder)super.writeContent(type, value); } public StreamBuilder writeContent(Type type, String value) { return (StreamBuilder)super.writeContent(type, value); } public StreamBuilder writeContributor(String name, String email, String uri) { return (StreamBuilder)super.writeContributor(name, email, uri); } public StreamBuilder writeContributor(String name) { return (StreamBuilder)super.writeContributor(name); } public StreamBuilder writeDate(QName qname, Date date) { return (StreamBuilder)super.writeDate(qname, date); } public StreamBuilder writeDate(QName qname, String date) { return (StreamBuilder)super.writeDate(qname, date); } public StreamBuilder writeDate(String name, Date date) { return (StreamBuilder)super.writeDate(name, date); } public StreamBuilder writeDate(String name, String namespace, Date date) { return (StreamBuilder)super.writeDate(name, namespace, date); } public StreamBuilder writeDate(String name, String namespace, String prefix, Date date) { return (StreamBuilder)super.writeDate(name, namespace, prefix, date); } public StreamBuilder writeDate(String name, String namespace, String prefix, String date) { return (StreamBuilder)super.writeDate(name, namespace, prefix, date); } public StreamBuilder writeDate(String name, String namespace, String date) { return (StreamBuilder)super.writeDate(name, namespace, date); } public StreamBuilder writeDate(String name, String date) { return (StreamBuilder)super.writeDate(name, date); } public StreamBuilder writeDraft(boolean draft) { return (StreamBuilder)super.writeDraft(draft); } public StreamBuilder writeEdited(Date date) { return (StreamBuilder)super.writeEdited(date); } public StreamBuilder writeEdited(String date) { return (StreamBuilder)super.writeEdited(date); } public StreamBuilder writeElementText(DataHandler value) throws IOException { return (StreamBuilder)super.writeElementText(value); } public StreamBuilder writeElementText(Date value) { return (StreamBuilder)super.writeElementText(value); } public StreamBuilder writeElementText(double value) { return (StreamBuilder)super.writeElementText(value); } public StreamBuilder writeElementText(InputStream value) throws IOException { return (StreamBuilder)super.writeElementText(value); } public StreamBuilder writeElementText(int value) { return (StreamBuilder)super.writeElementText(value); } public StreamBuilder writeElementText(long value) { return (StreamBuilder)super.writeElementText(value); } public StreamBuilder writeElementText(String format, Object... args) { return (StreamBuilder)super.writeElementText(format, args); } public StreamBuilder writeGenerator(String version, String uri, String value) { return (StreamBuilder)super.writeGenerator(version, uri, value); } public StreamBuilder writeIcon(IRI iri) { return (StreamBuilder)super.writeIcon(iri); } public StreamBuilder writeIcon(String iri) { return (StreamBuilder)super.writeIcon(iri); } public StreamBuilder writeId(IRI iri) { return (StreamBuilder)super.writeId(iri); } public StreamBuilder writeId(String iri) { return (StreamBuilder)super.writeId(iri); } public StreamBuilder writeIRIElement(QName qname, IRI iri) { return (StreamBuilder)super.writeIRIElement(qname, iri); } public StreamBuilder writeIRIElement(QName qname, String iri) { return (StreamBuilder)super.writeIRIElement(qname, iri); } public StreamBuilder writeIRIElement(String name, IRI iri) { return (StreamBuilder)super.writeIRIElement(name, iri); } public StreamBuilder writeIRIElement(String name, String namespace, IRI iri) { return (StreamBuilder)super.writeIRIElement(name, namespace, iri); } public StreamBuilder writeIRIElement(String name, String namespace, String prefix, IRI iri) { return (StreamBuilder)super.writeIRIElement(name, namespace, prefix, iri); } public StreamBuilder writeIRIElement(String name, String namespace, String prefix, String iri) { return (StreamBuilder)super.writeIRIElement(name, namespace, prefix, iri); } public StreamBuilder writeIRIElement(String name, String namespace, String iri) { return (StreamBuilder)super.writeIRIElement(name, namespace, iri); } public StreamBuilder writeIRIElement(String name, String iri) { return (StreamBuilder)super.writeIRIElement(name, iri); } public StreamBuilder writeLanguage(Lang lang) { return (StreamBuilder)super.writeLanguage(lang); } public StreamBuilder writeLanguage(Locale locale) { return (StreamBuilder)super.writeLanguage(locale); } public StreamBuilder writeLanguage(String lang) { return (StreamBuilder)super.writeLanguage(lang); } public StreamBuilder writeLink(String iri, String rel, String type, String title, String hreflang, long length) { return (StreamBuilder)super.writeLink(iri, rel, type, title, hreflang, length); } public StreamBuilder writeLink(String iri, String rel, String type) { return (StreamBuilder)super.writeLink(iri, rel, type); } public StreamBuilder writeLink(String iri, String rel) { return (StreamBuilder)super.writeLink(iri, rel); } public StreamBuilder writeLink(String iri) { return (StreamBuilder)super.writeLink(iri); } public StreamBuilder writeLogo(IRI iri) { return (StreamBuilder)super.writeLogo(iri); } public StreamBuilder writeLogo(String iri) { return (StreamBuilder)super.writeLogo(iri); } public StreamBuilder writePerson(QName qname, String name, String email, String uri) { return (StreamBuilder)super.writePerson(qname, name, email, uri); } public StreamBuilder writePerson(String localname, String namespace, String prefix, String name, String email, String uri) { return (StreamBuilder)super.writePerson(localname, namespace, prefix, name, email, uri); } public StreamBuilder writePerson(String localname, String namespace, String name, String email, String uri) { return (StreamBuilder)super.writePerson(localname, namespace, name, email, uri); } public StreamBuilder writePerson(String localname, String name, String email, String uri) { return (StreamBuilder)super.writePerson(localname, name, email, uri); } public StreamBuilder writePersonEmail(String email) { return (StreamBuilder)super.writePersonEmail(email); } public StreamBuilder writePersonName(String name) { return (StreamBuilder)super.writePersonName(name); } public StreamBuilder writePersonUri(String uri) { return (StreamBuilder)super.writePersonUri(uri); } public StreamBuilder writePublished(Date date) { return (StreamBuilder)super.writePublished(date); } public StreamBuilder writePublished(String date) { return (StreamBuilder)super.writePublished(date); } public StreamBuilder writeRights(String value) { return (StreamBuilder)super.writeRights(value); } public StreamBuilder writeRights(org.apache.abdera.model.Text.Type type, String value) { return (StreamBuilder)super.writeRights(type, value); } public StreamBuilder writeSubtitle(String value) { return (StreamBuilder)super.writeSubtitle(value); } public StreamBuilder writeSubtitle(org.apache.abdera.model.Text.Type type, String value) { return (StreamBuilder)super.writeSubtitle(type, value); } public StreamBuilder writeSummary(String value) { return (StreamBuilder)super.writeSummary(value); } public StreamBuilder writeSummary(org.apache.abdera.model.Text.Type type, String value) { return (StreamBuilder)super.writeSummary(type, value); } public StreamBuilder writeText(QName qname, org.apache.abdera.model.Text.Type type, String value) { return (StreamBuilder)super.writeText(qname, type, value); } public StreamBuilder writeText(String name, String namespace, String prefix, org.apache.abdera.model.Text.Type type, String value) { return (StreamBuilder)super.writeText(name, namespace, prefix, type, value); } public StreamBuilder writeText(String name, String namespace, org.apache.abdera.model.Text.Type type, String value) { return (StreamBuilder)super.writeText(name, namespace, type, value); } public StreamBuilder writeText(String name, org.apache.abdera.model.Text.Type type, String value) { return (StreamBuilder)super.writeText(name, type, value); } public StreamBuilder writeTitle(String value) { return (StreamBuilder)super.writeTitle(value); } public StreamBuilder writeTitle(org.apache.abdera.model.Text.Type type, String value) { return (StreamBuilder)super.writeTitle(type, value); } public StreamBuilder writeUpdated(Date date) { return (StreamBuilder)super.writeUpdated(date); } public StreamBuilder writeUpdated(String date) { return (StreamBuilder)super.writeUpdated(date); } public StreamBuilder setPrefix(String prefix, String uri) { if (!(current instanceof Element)) throw new IllegalStateException("Not currently an element"); ((Element)current).declareNS(uri, prefix); return this; } public StreamBuilder writeNamespace(String prefix, String uri) { return setPrefix(prefix, uri); } }
7,235
0
Create_ds/abdera/core/src/main/java/org/apache/abdera
Create_ds/abdera/core/src/main/java/org/apache/abdera/factory/Factory.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.factory; import javax.activation.MimeType; import javax.xml.namespace.QName; import org.apache.abdera.Abdera; import org.apache.abdera.model.Base; import org.apache.abdera.model.Categories; import org.apache.abdera.model.Category; import org.apache.abdera.model.Collection; import org.apache.abdera.model.Content; import org.apache.abdera.model.Control; import org.apache.abdera.model.DateTime; import org.apache.abdera.model.Div; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.model.Generator; import org.apache.abdera.model.IRIElement; import org.apache.abdera.model.Link; import org.apache.abdera.model.Person; import org.apache.abdera.model.Service; import org.apache.abdera.model.Source; import org.apache.abdera.model.Text; import org.apache.abdera.model.Workspace; import org.apache.abdera.parser.Parser; /** * The Factory interface is the primary means by which Feed Object Model instances are built. Factories are specific to * parser implementations. Users will generally not have to know anything about the Factory implementation, which will * be automatically selected based on the Abdera configuration options. */ public interface Factory { /** * Create a new Parser instance. * * @return A new instance of the Parser associated with this Factory */ Parser newParser(); /** * Create a new Document instance with a root Element of type T. * * @return A new instance of a Document */ <T extends Element> Document<T> newDocument(); /** * Create a new Service element. * * @return A newly created Service element */ Service newService(); /** * Create a new Service element as a child of the given Base. * * @param parent The element or document to which the new Service should be added as a child * @return A newly created Service element */ Service newService(Base parent); /** * Create a new Workspace element. * * @return A newly created Workspace element */ Workspace newWorkspace(); /** * Create a new Workspace element as a child of the given Element. * * @param parent The element to which the new Workspace should be added as a child * @return A newly created Workspace element */ Workspace newWorkspace(Element parent); /** * Create a new Collection element. * * @return A newly created Collection element */ Collection newCollection(); /** * Create a new Collection element as a child of the given Element. * * @param parent The element to which the new Collection should be added as a child * @return A newly created Collection element */ Collection newCollection(Element parent); /** * Create a new Feed element. A new Document containing the Feed will be created automatically * * @return A newly created Feed element. */ Feed newFeed(); /** * Create a new Feed element as a child of the given Base. * * @param parent The element or document to which the new Feed should be added as a child * @return A newly created Feed element */ Feed newFeed(Base parent); /** * Create a new Entry element. A new Document containing the Entry will be created automatically * * @return A newly created Entry element */ Entry newEntry(); /** * Create a new Entry element as a child of the given Base. * * @param parent The element or document to which the new Entry should be added as a child * @return A newly created Entry element */ Entry newEntry(Base parent); /** * Create a new Category element. * * @return A newly created Category element */ Category newCategory(); /** * Create a new Category element as a child of the given Element. * * @param parent The element to which the new Category should be added as a child * @return A newly created Category element */ Category newCategory(Element parent); /** * Create a new Content element. * * @return A newly created Content element with type="text" */ Content newContent(); /** * Create a new Content element of the given Content.Type. * * @param type The Content.Type for the newly created Content element. * @return A newly created Content element using the specified type */ Content newContent(Content.Type type); /** * Create a new Content element of the given Content.Type as a child of the given Element. * * @param type The Content.Type for the newly created Content element. * @param parent The element to which the new Content should be added as a child * @return A newly created Content element using the specified type */ Content newContent(Content.Type type, Element parent); /** * Create a new Content element of the given MediaType. * * @param mediaType The MIME media type to be specified by the type attribute * @return A newly created Content element using the specified MIME type */ Content newContent(MimeType mediaType); /** * Create a new Content element of the given MediaType as a child of the given Element. * * @param mediaType The MIME media type to be specified by the type attribute * @param parent The element to which the new Content should be added as a child * @return A newly created Content element using the specified mediatype. */ Content newContent(MimeType mediaType, Element parent); /** * Create a new published element. * * @return A newly created atom:published element */ DateTime newPublished(); /** * Create a new published element as a child of the given Element. * * @param parent The element to which the new Published element should be added as a child * @return A newly created atom:published element */ DateTime newPublished(Element parent); /** * Create a new updated element. * * @return A newly created atom:updated element */ DateTime newUpdated(); /** * create a new updated element as a child of the given Element. * * @param parent The element to which the new Updated element should be added as a child * @return A newly created atom:updated element */ DateTime newUpdated(Element parent); /** * Create a new app:edited element. The app:edited element is defined by the Atom Publishing Protocol specification * for use in atom:entry elements created and edited using that protocol. The element should only ever appear as a * child of atom:entry. * * @return A newly created app:edited element */ DateTime newEdited(); /** * Create a new app:edited element. The app:edited element is defined by the Atom Publishing Protocol specification * for use in atom:entry elements created and edited using that protocol. The element should only ever appear as a * child of atom:entry. * * @param parent The element to which the new Edited element should be added as a child * @return A newly created app:edited element */ DateTime newEdited(Element parent); /** * Create a new DateTime element with the given QName as a child of the given Element. RFC4287 provides the abstract * Atom Date Construct as a reusable component. Any extension element whose value is a Date/Time SHOULD reuse this * construct to maintain consistency with the base specification. * * @param qname The XML QName of the Atom Date element to create * @param parent The element to which the new Atom Date element should be added as a child * @return The newly created Atom Date Construct element */ DateTime newDateTime(QName qname, Element parent); /** * Create a new Generator with Abdera's default name and version. * * @return A newly created and pre-populated atom:generator element */ Generator newDefaultGenerator(); /** * Create a new Generator using Abdera's default name and version as a child of the given Element. * * @param parent The element to which the new Generator element should be added as a child * @return A newly created and pre-populated atom:generator element */ Generator newDefaultGenerator(Element parent); /** * Create a new Generator element. * * @return A newly created atom:generator element */ Generator newGenerator(); /** * Create a new Generator element as a child of the given Element. * * @param parent The element to which the new Generator element should be added as a child * @return A newly creatd atom:generator element */ Generator newGenerator(Element parent); /** * Create a new id element. * * @return A newly created atom:id element */ IRIElement newID(); /** * Create a new id element as a child of the given Element. * * @param parent The element to which the new ID element should be added as a child * @return A newly created atom:id element */ IRIElement newID(Element parent); /** * Create a new icon element. * * @return A newly created atom:icon element */ IRIElement newIcon(); /** * Create a new icon element as a child of the given Element. * * @param parent The element to which the new Icon element should be added as a child * @return A newly created atom:icon element */ IRIElement newIcon(Element parent); /** * Create a new logo element. * * @return A newly created atom:logo element */ IRIElement newLogo(); /** * Create a new logo element as a child of the given Element. * * @param parent The element to which the new Logo element should be added as a child * @return A newly created atom:logo element */ IRIElement newLogo(Element parent); /** * Create a new uri element. * * @return A newly created atom:uri element */ IRIElement newUri(); /** * Create a new uri element as a child of the given Element. * * @param parent The element to which the new URI element should be added as a child * @return A newly created atom:uri element */ IRIElement newUri(Element parent); /** * Create a new IRI element with the given QName as a child of the given Element. * * @param qname The XML QName of the new IRI element * @param parent The element to which the new generic IRI element should be added as a child * @return A newly created element whose text value can be an IRI */ IRIElement newIRIElement(QName qname, Element parent); /** * Create a new Link element. * * @return A newly created atom:link element */ Link newLink(); /** * Create a new Link element as a child of the given Element. * * @param parent The element to which the new Link element should be added as a child * @return A newly created atom:uri element */ Link newLink(Element parent); /** * Create a new author element. * * @return A newly created atom:author element */ Person newAuthor(); /** * Create a new author element as a child of the given Element. * * @param parent The element to which the new Author element should be added as a child * @return A newly created atom:author element */ Person newAuthor(Element parent); /** * Create a new contributor element. * * @return A newly created atom:contributor element */ Person newContributor(); /** * Create a new contributor element as a child of the given Element. * * @param parent The element to which the new Contributor element should be added as a child * @return A newly created atom:contributor element */ Person newContributor(Element parent); /** * Create a new Person element with the given QName as a child of the given Element. RFC4287 provides the abstract * Atom Person Construct to represent people and other entities within an Atom Document. Extensions that wish to * represent people SHOULD reuse this construct. * * @param qname The XML QName of the newly created Person element * @param parent The element to which the new Person element should be added as a child * @return A newly created Atom Person Construct element */ Person newPerson(QName qname, Element parent); /** * Create a new Source element. * * @return A newly created atom:source element */ Source newSource(); /** * Create a new Source element as a child of the given Element. * * @param parent The element to which the new Source element should be added as a child * @return A newly created atom:source element */ Source newSource(Element parent); /** * Create a new Text element with the given QName and Text.Type. RFC4287 provides the abstract Text Construct to * represent simple Text, HTML or XHTML within a document. This construct is used by Atom core elements like * atom:title, atom:summary, atom:rights, atom:subtitle, etc and SHOULD be reused by extensions that need a way of * embedding text in a document. * * @param qname The XML QName of the Text element to create * @param type The type of text (plain text, HTML or XHTML) * @return A newly created Atom Text Construct element */ Text newText(QName qname, Text.Type type); /** * Create a new Text element with the given QName and Text.Type as a child of the given Element. * * @param qname The XML QName of the Text element to create * @param type The type of text (plain text, HTML or XHTML) * @param parent The element to which the new Updated element should be added as a child * @return A newly created Atom Text Construct element */ Text newText(QName qname, Text.Type type, Element parent); /** * Create a new title element. * * @return A newly created atom:title element */ Text newTitle(); /** * Create a new title element as a child of the given Element. * * @param parent The element to which the new Title element should be added as a child * @return A newly created atom:title element */ Text newTitle(Element parent); /** * Create a new title element with the given Text.Type. * * @param type The type of text used in the title (plain text, HTML, XHTML) * @return A newly created atom:title element */ Text newTitle(Text.Type type); /** * Create a new title element with the given Text.Type as a child of the given Element. * * @param type The type of text used in the title (plain text, HTML, XHTML) * @param parent The element to which the new Updated element should be added as a child * @return A newly created atom:title element */ Text newTitle(Text.Type type, Element parent); /** * Create a new subtitle element. * * @return A newly created atom:subtitle element */ Text newSubtitle(); /** * Create a new subtitle element as a child of the given Element. * * @param parent The element to which the new Subtitle element should be added as a child * @return A newly created atom:subtitle element */ Text newSubtitle(Element parent); /** * Create a new subtitle element with the given Text.Type. * * @param type The type of text used in the subtitle (plain text, HTML, XHTML) * @return A newly created atom:subtitle element */ Text newSubtitle(Text.Type type); /** * Create a new subtitle element with the given Text.Type as a child of the given Element. * * @param type The type of text used i the subtitle (plain text, HTML, XHTML) * @param parent The element to which the new Subtitle element should be added as a child * @return A newly created atom:subtitle element */ Text newSubtitle(Text.Type type, Element parent); /** * Create a new summary element. * * @return A newly created atom:summary element */ Text newSummary(); /** * Create a new summary element as a child of the given Element. * * @param parent The element to which the new Summary element should be added as a child * @return A newly created atom:summary element */ Text newSummary(Element parent); /** * Create a new summary element with the given Text.Type. * * @param type The type of text used in the summary (plain text, HTML, XHTML) * @return A newly created atom:summary element */ Text newSummary(Text.Type type); /** * Create a new summary element with the given Text.Type as a child of the given Element. * * @param type The type of text used in the summary (plain text, HTML, XHTML) * @param parent The element to which the new Summary element should be added as a child * @return A newly created atom:summary element */ Text newSummary(Text.Type type, Element parent); /** * Create a new rights element. * * @return A newly created atom:rights element */ Text newRights(); /** * Create a new rights element as a child of the given Element. * * @param parent The element to which the new Rights element should be added as a child * @return A newly created atom:rights element */ Text newRights(Element parent); /** * Create a new rights element with the given Text.Type. * * @param type The type of text used in the Rights (plain text, HTML, XHTML) * @return A newly created atom:rights element */ Text newRights(Text.Type type); /** * Create a new rights element with the given Text.Type as a child of the given Element. * * @param type The type of text used in the Rights (plain text, HTML, XHTML) * @param parent The element to which the new Rights element should be added as a child * @return A newly created atom:rights element */ Text newRights(Text.Type type, Element parent); /** * Create a new name element. * * @return A newly created atom:name element */ Element newName(); /** * Create a new name element as a child of the given Element. * * @param parent The element to which the new Name element should be added as a child * @return A newly created atom:summary element */ Element newName(Element parent); /** * Create a new email element. * * @return A newly created atom:email element */ Element newEmail(); /** * Create a new email element as a child of the given Element. * * @param parent The element to which the new Email element should be added as a child * @return A newly created atom:email element */ Element newEmail(Element parent); /** * Create a new Element with the given QName. * * @return A newly created element */ <T extends Element> T newElement(QName qname); /** * Create a new Element with the given QName as a child of the given Base. * * @param qname The XML QName of the element to create * @param parent The element or document to which the new element should be added as a child * @return A newly created element */ <T extends Element> T newElement(QName qname, Base parent); /** * Create a new extension element with the given QName. * * @param qname The XML QName of the element to create * @return A newly created element */ <T extends Element> T newExtensionElement(QName qname); /** * Create a new extension element with the given QName as a child of the given Base. * * @param qname The XML QName of the element to create * @param parent The element or document to which the new element should be added as a child * @return A newly created element */ <T extends Element> T newExtensionElement(QName qname, Base parent); /** * Create a new Control element. The app:control element is introduced by the Atom Publishing Protocol as a means of * allowing publishing clients to provide metadata to a server affecting the way an entry is published. The control * element SHOULD only ever appear as a child of the atom:entry and MUST only ever appear once. * * @return A newly app:control element */ Control newControl(); /** * Create a new Control element as a child of the given Element. * * @param parent The element to which the new Control element should be added as a child * @return A newly app:control element */ Control newControl(Element parent); /** * Create a new Div element. * * @return A newly xhtml:div element */ Div newDiv(); /** * Create a new Div element as a child of the given Base. * * @param parent The element or document to which the new XHTML div element should be added as a child * @return A newly xhtml:div element */ Div newDiv(Base parent); /** * Registers an extension factory for this Factory instance only * * @param extensionFactory An ExtensionFactory instance */ Factory registerExtension(ExtensionFactory extensionFactory); /** * Create a new Categories element. The app:categories element is introduced by the Atom Publishing Protocol as a * means of providing a listing of atom:category's that can be used by entries in a collection. * * @return A newly app:categories element */ Categories newCategories(); /** * Create a new Categories element. The app:categories element is introduced by the Atom Publishing Protocol as a * means of providing a listing of atom:category's that can be used by entries in a collection. * * @param parent The element or document to which the new Categories element should be added as a child * @return A newly app:categories element */ Categories newCategories(Base parent); /** * Generate a new random UUID URI */ String newUuidUri(); /** * Get the Abdera instance for this factory */ Abdera getAbdera(); /** * Get the mime type for the specified extension element / document */ <T extends Base> String getMimeType(T base); /** * Returns a listing of extension factories registered */ String[] listExtensionFactories(); }
7,236
0
Create_ds/abdera/security/src/test/java/org/apache/abdera/test
Create_ds/abdera/security/src/test/java/org/apache/abdera/test/security/DigitalSignatureTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.test.security; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.security.KeyStore; import java.security.PrivateKey; import java.security.cert.X509Certificate; import javax.xml.namespace.QName; import org.apache.abdera.Abdera; import org.apache.abdera.factory.Factory; import org.apache.abdera.model.Document; import org.apache.abdera.model.Entry; import org.apache.abdera.security.AbderaSecurity; import org.apache.abdera.security.Signature; import org.apache.abdera.security.SignatureOptions; import org.junit.Test; public class DigitalSignatureTest { private static final String keystoreFile = "/key.jks"; private static final String keystoreType = "JKS"; private static final String keystorePass = "testing"; private static final String privateKeyAlias = "James"; private static final String privateKeyPass = "testing"; private static final String certificateAlias = "James"; @Test public void testSignEntry() throws Exception { // Initialize the keystore KeyStore ks = KeyStore.getInstance(keystoreType); assertNotNull(ks); InputStream in = DigitalSignatureTest.class.getResourceAsStream(keystoreFile); assertNotNull(in); ks.load(in, keystorePass.toCharArray()); PrivateKey signingKey = (PrivateKey)ks.getKey(privateKeyAlias, privateKeyPass.toCharArray()); X509Certificate cert = (X509Certificate)ks.getCertificate(certificateAlias); assertNotNull(signingKey); assertNotNull(cert); // Create the entry to sign Abdera abdera = new Abdera(); AbderaSecurity absec = new AbderaSecurity(abdera); Factory factory = abdera.getFactory(); Entry entry = factory.newEntry(); entry.setId("http://example.org/foo/entry"); entry.setUpdated(new java.util.Date()); entry.setTitle("This is an entry"); entry.setContentAsXhtml("This <b>is</b> <i>markup</i>"); entry.addAuthor("James"); entry.addLink("http://www.example.org"); // Prepare the digital signature options Signature sig = absec.getSignature(); SignatureOptions options = sig.getDefaultSignatureOptions(); options.setCertificate(cert); options.setSigningKey(signingKey); // Sign the entry entry = sig.sign(entry, options); assertNotNull(entry.getFirstChild(new QName("http://www.w3.org/2000/09/xmldsig#", "Signature"))); X509Certificate[] certs = sig.getValidSignatureCertificates(entry, options); assertNotNull(certs); assertEquals(1, certs.length); assertEquals("CN=James M Snell, OU=WebAhead, O=IBM, L=Hanford, ST=California, C=US", certs[0].getSubjectDN() .getName()); // Check the round trip ByteArrayOutputStream out = new ByteArrayOutputStream(); entry.writeTo(out); // do not use the pretty writer, it will break the signature ByteArrayInputStream bais = new ByteArrayInputStream(out.toByteArray()); Document<Entry> entry_doc = abdera.getParser().parse(bais); entry = entry_doc.getRoot(); assertTrue(sig.verify(entry, null)); // the signature better still be valid entry.setTitle("Change the title"); assertFalse(sig.verify(entry, null)); // the signature better be invalid } }
7,237
0
Create_ds/abdera/security/src/test/java/org/apache/abdera/test
Create_ds/abdera/security/src/test/java/org/apache/abdera/test/security/EncryptionTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.test.security; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.security.Provider; import java.security.Security; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.xml.namespace.QName; import org.apache.abdera.Abdera; import org.apache.abdera.factory.Factory; import org.apache.abdera.model.Document; import org.apache.abdera.model.Entry; import org.apache.abdera.security.AbderaSecurity; import org.apache.abdera.security.Encryption; import org.apache.abdera.security.EncryptionOptions; import org.junit.Test; @SuppressWarnings("unchecked") public class EncryptionTest { /** * The bouncy castle JCE provider is required to run this test */ @Test public void testEncryption() throws Exception { Abdera abdera = new Abdera(); try { String jce = abdera.getConfiguration().getConfigurationOption("jce.provider", "org.bouncycastle.jce.provider.BouncyCastleProvider"); Class provider = Class.forName(jce); Provider p = (Provider)provider.newInstance(); Security.addProvider(p); } catch (Exception e) { // the configured jce provider is not available, try to proceed anyway } // Generate Encryption Key String jceAlgorithmName = "AES"; KeyGenerator keyGenerator = KeyGenerator.getInstance(jceAlgorithmName); keyGenerator.init(128); SecretKey key = keyGenerator.generateKey(); // Create the entry to encrypt AbderaSecurity absec = new AbderaSecurity(abdera); Factory factory = abdera.getFactory(); Entry entry = factory.newEntry(); entry.setId("http://example.org/foo/entry"); entry.setUpdated(new java.util.Date()); entry.setTitle("This is an entry"); entry.setContentAsXhtml("This <b>is</b> <i>markup</i>"); entry.addAuthor("James"); entry.addLink("http://www.example.org"); // Prepare the encryption options Encryption enc = absec.getEncryption(); EncryptionOptions options = enc.getDefaultEncryptionOptions(); options.setDataEncryptionKey(key); // Encrypt the document using the generated key Document enc_doc = enc.encrypt(entry.getDocument(), options); assertEquals(new QName("http://www.w3.org/2001/04/xmlenc#", "EncryptedData"), enc_doc.getRoot().getQName()); // Decrypt the document using the generated key Document<Entry> entry_doc = enc.decrypt(enc_doc, options); assertTrue(entry_doc.getRoot() instanceof Entry); assertEquals("http://example.org/foo/entry", entry_doc.getRoot().getId().toString()); } }
7,238
0
Create_ds/abdera/security/src/test/java/org/apache/abdera/test
Create_ds/abdera/security/src/test/java/org/apache/abdera/test/security/TestSuite.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.test.security; import java.security.Provider; import java.security.Security; import org.apache.abdera.test.security.filter.SecurityFilterTest; import org.junit.internal.TextListener; import org.junit.runner.JUnitCore; public class TestSuite { public static void main(String[] args) throws Exception { Security.addProvider(getProvider(args[0])); JUnitCore runner = new JUnitCore(); runner.addListener(new TextListener(System.out)); runner.run(DigitalSignatureTest.class, EncryptionTest.class, SecurityFilterTest.class); } private static Provider getProvider(String provider) throws Exception { return (Provider)Class.forName(provider).newInstance(); } }
7,239
0
Create_ds/abdera/security/src/test/java/org/apache/abdera/test/security
Create_ds/abdera/security/src/test/java/org/apache/abdera/test/security/filter/CustomProvider.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.test.security.filter; import org.apache.abdera.protocol.server.CollectionAdapter; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.TargetType; import org.apache.abdera.protocol.server.impl.AbstractWorkspaceProvider; import org.apache.abdera.protocol.server.impl.RouteManager; import org.apache.abdera.protocol.server.impl.SimpleWorkspaceInfo; import org.apache.abdera.security.util.filters.SignedRequestFilter; import org.apache.abdera.security.util.filters.SignedResponseFilter; public class CustomProvider extends AbstractWorkspaceProvider { private final SimpleAdapter adapter; private static final String keystoreFile = "/key.jks"; private static final String keystorePass = "testing"; private static final String privateKeyAlias = "James"; private static final String privateKeyPass = "testing"; private static final String certificateAlias = "James"; public CustomProvider() { this.adapter = new SimpleAdapter(); RouteManager rm = new RouteManager().addRoute("service", "/", TargetType.TYPE_SERVICE).addRoute("collection", "/:collection", TargetType.TYPE_COLLECTION) .addRoute("entry", "/:collection/:entry", TargetType.TYPE_ENTRY); setTargetBuilder(rm); setTargetResolver(rm); SimpleWorkspaceInfo workspace = new SimpleWorkspaceInfo(); workspace.setTitle("A Simple Workspace"); workspace.addCollection(adapter); addWorkspace(workspace); addFilter(new SignedRequestFilter(), new SignedResponseFilter(keystoreFile, keystorePass, privateKeyAlias, privateKeyPass, certificateAlias, null)); } public CollectionAdapter getCollectionAdapter(RequestContext request) { return adapter; } }
7,240
0
Create_ds/abdera/security/src/test/java/org/apache/abdera/test/security
Create_ds/abdera/security/src/test/java/org/apache/abdera/test/security/filter/SecurityFilterTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.test.security.filter; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.io.InputStream; import java.security.KeyStore; import java.security.PrivateKey; import java.security.cert.X509Certificate; import java.util.Date; import org.apache.abdera.Abdera; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.model.Entry; import org.apache.abdera.protocol.Response.ResponseType; import org.apache.abdera.protocol.client.AbderaClient; import org.apache.abdera.protocol.client.ClientResponse; import org.apache.abdera.security.AbderaSecurity; import org.apache.abdera.security.Signature; import org.apache.abdera.security.SignatureOptions; import org.apache.abdera.test.security.DigitalSignatureTest; import org.apache.axiom.testutils.PortAllocator; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; public class SecurityFilterTest { private static int port; private static JettyServer server; private static Abdera abdera = Abdera.getInstance(); private static AbderaClient client = new AbderaClient(); @BeforeClass public static void setUp() throws Exception { port = PortAllocator.allocatePort(); server = new JettyServer(port); server.start(CustomProvider.class); } @AfterClass public static void tearDown() throws Exception { server.stop(); } @Test public void testSignedResponseFilter() throws Exception { ClientResponse resp = client.get("http://localhost:" + port + "/"); Document<Element> doc = resp.getDocument(); Element root = doc.getRoot(); AbderaSecurity security = new AbderaSecurity(abdera); Signature sig = security.getSignature(); assertTrue(sig.isSigned(root)); assertTrue(sig.verify(root, sig.getDefaultSignatureOptions())); } private static final String keystoreFile = "/key.jks"; private static final String keystoreType = "JKS"; private static final String keystorePass = "testing"; private static final String privateKeyAlias = "James"; private static final String privateKeyPass = "testing"; private static final String certificateAlias = "James"; @Test public void testSignedRequestFilter() throws Exception { Entry entry = abdera.newEntry(); entry.setId("http://localhost:" + port + "/feed/entries/1"); entry.setTitle("test entry"); entry.setContent("Test Content"); entry.addLink("http://example.org"); entry.setUpdated(new Date()); entry.addAuthor("James"); ClientResponse resp = client.post("http://localhost:" + port + "/feed", entry); assertNotNull(resp); assertEquals(ResponseType.CLIENT_ERROR, resp.getType()); // Initialize the keystore AbderaSecurity security = new AbderaSecurity(abdera); KeyStore ks = KeyStore.getInstance(keystoreType); assertNotNull(ks); InputStream in = DigitalSignatureTest.class.getResourceAsStream(keystoreFile); assertNotNull(in); ks.load(in, keystorePass.toCharArray()); PrivateKey signingKey = (PrivateKey)ks.getKey(privateKeyAlias, privateKeyPass.toCharArray()); X509Certificate cert = (X509Certificate)ks.getCertificate(certificateAlias); assertNotNull(signingKey); assertNotNull(cert); Signature sig = security.getSignature(); SignatureOptions options = sig.getDefaultSignatureOptions(); options.setCertificate(cert); options.setSigningKey(signingKey); // Sign the entry entry = sig.sign(entry, options); resp = client.post("http://localhost:" + port + "/feed", entry); assertNotNull(resp); assertEquals(ResponseType.SUCCESS, resp.getType()); } }
7,241
0
Create_ds/abdera/security/src/test/java/org/apache/abdera/test/security
Create_ds/abdera/security/src/test/java/org/apache/abdera/test/security/filter/JettyServer.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.test.security.filter; import org.apache.abdera.protocol.server.Provider; import org.apache.abdera.protocol.server.ServiceManager; import org.apache.abdera.protocol.server.servlet.AbderaServlet; import org.mortbay.jetty.Server; import org.mortbay.jetty.servlet.Context; import org.mortbay.jetty.servlet.ServletHolder; public class JettyServer { public static final int DEFAULT_PORT = 9002; private final int port; private Server server; public JettyServer() { this(DEFAULT_PORT); } public JettyServer(int port) { this.port = port; } public void start(Class<? extends Provider> _class) throws Exception { server = new Server(port); Context context = new Context(server, "/", Context.SESSIONS); ServletHolder servletHolder = new ServletHolder(new AbderaServlet()); servletHolder.setInitParameter(ServiceManager.PROVIDER, _class.getName()); context.addServlet(servletHolder, "/*"); server.start(); } public void stop() throws Exception { server.stop(); } public void join() throws Exception { server.join(); } }
7,242
0
Create_ds/abdera/security/src/test/java/org/apache/abdera/test/security
Create_ds/abdera/security/src/test/java/org/apache/abdera/test/security/filter/SimpleAdapter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.test.security.filter; import java.io.IOException; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.apache.abdera.Abdera; import org.apache.abdera.i18n.text.UrlEncoding; import org.apache.abdera.model.Document; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.parser.ParseException; import org.apache.abdera.protocol.server.ProviderHelper; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.ResponseContext; import org.apache.abdera.protocol.server.TargetType; import org.apache.abdera.protocol.server.RequestContext.Scope; import org.apache.abdera.protocol.server.context.BaseResponseContext; import org.apache.abdera.protocol.server.context.ResponseContextException; import org.apache.abdera.protocol.server.context.StreamWriterResponseContext; import org.apache.abdera.protocol.server.impl.AbstractCollectionAdapter; import org.apache.abdera.util.Constants; import org.apache.abdera.writer.StreamWriter; @SuppressWarnings("unchecked") public class SimpleAdapter extends AbstractCollectionAdapter { @Override public String getAuthor(RequestContext request) throws ResponseContextException { return "Simple McGee"; } @Override public String getId(RequestContext request) { return "tag:example.org,2008:feed"; } public String getHref(RequestContext request) { Map<String, Object> params = new HashMap<String, Object>(); params.put("collection", "feed"); return request.urlFor("feed", params); } public String getTitle(RequestContext request) { return "A simple feed"; } public ResponseContext extensionRequest(RequestContext request) { return ProviderHelper.notallowed(request, "Method Not Allowed", ProviderHelper.getDefaultMethods(request)); } private Document<Feed> getFeedDocument(RequestContext context) throws ResponseContextException { Feed feed = (Feed)context.getAttribute(Scope.SESSION, "feed"); if (feed == null) { feed = createFeedBase(context); feed.setBaseUri(getHref(context)); context.setAttribute(Scope.SESSION, "feed", feed); } return feed.getDocument(); } public ResponseContext getFeed(RequestContext request) { Document<Feed> feed; try { feed = getFeedDocument(request); } catch (ResponseContextException e) { return e.getResponseContext(); } return ProviderHelper.returnBase(feed, 200, feed.getRoot().getUpdated()).setEntityTag(ProviderHelper .calculateEntityTag(feed.getRoot())); } public ResponseContext deleteEntry(RequestContext request) { Entry entry = getAbderaEntry(request); if (entry != null) entry.discard(); return ProviderHelper.nocontent(); } public ResponseContext getEntry(RequestContext request) { Entry entry = (Entry)getAbderaEntry(request); if (entry != null) { Feed feed = entry.getParentElement(); entry = (Entry)entry.clone(); entry.setSource(feed.getAsSource()); Document<Entry> entry_doc = entry.getDocument(); return ProviderHelper.returnBase(entry_doc, 200, entry.getEdited()).setEntityTag(ProviderHelper .calculateEntityTag(entry)); } else { return ProviderHelper.notfound(request); } } public ResponseContext postEntry(RequestContext request) { Abdera abdera = request.getAbdera(); try { Document<Entry> entry_doc = (Document<Entry>)request.getDocument(abdera.getParser()).clone(); if (entry_doc != null) { Entry entry = entry_doc.getRoot(); if (!ProviderHelper.isValidEntry(entry)) return ProviderHelper.badrequest(request); setEntryDetails(request, entry, abdera.getFactory().newUuidUri()); Feed feed = getFeedDocument(request).getRoot(); feed.insertEntry(entry); feed.setUpdated(new Date()); BaseResponseContext rc = (BaseResponseContext)ProviderHelper.returnBase(entry, 201, entry.getEdited()); return rc.setLocation(ProviderHelper.resolveBase(request).resolve(entry.getEditLinkResolvedHref()) .toString()).setContentLocation(rc.getLocation().toString()).setEntityTag(ProviderHelper .calculateEntityTag(entry)); } else { return ProviderHelper.badrequest(request); } } catch (ParseException pe) { return ProviderHelper.notsupported(request); } catch (ClassCastException cce) { return ProviderHelper.notsupported(request); } catch (Exception e) { return ProviderHelper.badrequest(request); } } private void setEntryDetails(RequestContext request, Entry entry, String id) { entry.setUpdated(new Date()); entry.setEdited(entry.getUpdated()); entry.getIdElement().setValue(id); entry.addLink(getEntryLink(request, entry.getId().toASCIIString()), "edit"); } private String getEntryLink(RequestContext request, String entryid) { Map<String, String> params = new HashMap<String, String>(); params.put("collection", request.getTarget().getParameter("collection")); params.put("entry", entryid); return request.urlFor("entry", params); } public ResponseContext putEntry(RequestContext request) { Abdera abdera = request.getAbdera(); Entry orig_entry = getAbderaEntry(request); if (orig_entry != null) { try { Document<Entry> entry_doc = (Document<Entry>)request.getDocument(abdera.getParser()).clone(); if (entry_doc != null) { Entry entry = entry_doc.getRoot(); if (!entry.getId().equals(orig_entry.getId())) return ProviderHelper.conflict(request); if (!ProviderHelper.isValidEntry(entry)) return ProviderHelper.badrequest(request); setEntryDetails(request, entry, orig_entry.getId().toString()); orig_entry.discard(); Feed feed = getFeedDocument(request).getRoot(); feed.insertEntry(entry); feed.setUpdated(new Date()); return ProviderHelper.nocontent(); } else { return ProviderHelper.badrequest(request); } } catch (ParseException pe) { return ProviderHelper.notsupported(request); } catch (ClassCastException cce) { return ProviderHelper.notsupported(request); } catch (Exception e) { return ProviderHelper.badrequest(request); } } else { return ProviderHelper.notfound(request); } } private Entry getAbderaEntry(RequestContext request) { try { return getFeedDocument(request).getRoot().getEntry(getResourceName(request)); } catch (Exception e) { } return null; } public String getResourceName(RequestContext request) { if (request.getTarget().getType() != TargetType.TYPE_ENTRY) return null; String[] segments = request.getUri().toString().split("/"); return UrlEncoding.decode(segments[segments.length - 1]); } public ResponseContext getCategories(RequestContext request) { return new StreamWriterResponseContext(request.getAbdera()) { protected void writeTo(StreamWriter sw) throws IOException { sw.startDocument().startCategories(false).writeCategory("foo").writeCategory("bar") .writeCategory("baz").endCategories().endDocument(); } }.setStatus(200).setContentType(Constants.CAT_MEDIA_TYPE); } }
7,243
0
Create_ds/abdera/security/src/main/java/org/apache/abdera
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/SecurityOptions.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security; import org.apache.abdera.parser.Parser; /** * Base interface for EncryptionOptions and SignatureOptions */ public interface SecurityOptions { Parser getParser(); <T extends SecurityOptions> T setParser(Parser parser); }
7,244
0
Create_ds/abdera/security/src/main/java/org/apache/abdera
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/Signature.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security; import java.security.cert.X509Certificate; import org.apache.abdera.model.Element; import org.apache.xml.security.keys.KeyInfo; /** * Interface used for digitally signing and verifying Abdera elements */ public interface Signature { /** * Return true if the element has been digitally signed */ <T extends Element> boolean isSigned(T element) throws SecurityException; /** * Adds a digital signature to the specified element */ <T extends Element> T sign(T element, SignatureOptions options) throws SecurityException; /** * Verifies that the digitally signed element is valid */ <T extends Element> boolean verify(T element, SignatureOptions options) throws SecurityException; /** * Returns a listing of X.509 certificates of valid digital signatures in the element */ <T extends Element> X509Certificate[] getValidSignatureCertificates(T element, SignatureOptions options) throws SecurityException; <T extends Element> KeyInfo getSignatureKeyInfo(T element, SignatureOptions options) throws SecurityException; /** * Returns the default signing options * * @see org.apache.abdera.security.SignatureOptions */ SignatureOptions getDefaultSignatureOptions() throws SecurityException; <T extends Element> T removeInvalidSignatures(T element, SignatureOptions options) throws SecurityException; }
7,245
0
Create_ds/abdera/security/src/main/java/org/apache/abdera
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/SecurityException.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security; public class SecurityException extends Exception { private static final long serialVersionUID = 7981088993260681788L; public SecurityException() { super(); } public SecurityException(String message) { super(message); } public SecurityException(String message, Throwable cause) { super(message, cause); } public SecurityException(Throwable cause) { super(cause); } }
7,246
0
Create_ds/abdera/security/src/main/java/org/apache/abdera
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/EncryptionOptions.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security; import java.security.Key; /** * Provides access to the information necessary to encrypt or decrypt a document */ public interface EncryptionOptions extends SecurityOptions { /** * Return the secret key used to encrypt/decrypt the document content */ Key getDataEncryptionKey(); /** * Set the secret key used to encrypt/decrypt the document content */ EncryptionOptions setDataEncryptionKey(Key key); /** * Return the secret key used to encrypt/decrypt the data encryption key */ Key getKeyEncryptionKey(); /** * Set the secret key used to encrypt/decrypt the data encryption key */ EncryptionOptions setKeyEncryptionKey(Key key); /** * Return the cipher algorithm used to decrypt/encrypt the data encryption key The default is * "http://www.w3.org/2001/04/xmlenc#kw-aes128" */ String getKeyCipherAlgorithm(); /** * Set the cipher algorithm used to decrypt/encrypt the data encryption key The default is * "http://www.w3.org/2001/04/xmlenc#kw-aes128" */ EncryptionOptions setKeyCipherAlgorithm(String alg); /** * Return the cipher algorithm used to decrypt/encrypt the document content The default is * "http://www.w3.org/2001/04/xmlenc#aes128-cbc" */ String getDataCipherAlgorithm(); /** * Set the cipher algorithm used to decyrpt/encrypt the document content The default is * "http://www.w3.org/2001/04/xmlenc#aes128-cbc" */ EncryptionOptions setDataCipherAlgorithm(String alg); /** * Return true if the encryption should include information about the key The default is false */ boolean includeKeyInfo(); /** * Set whether the encryption should include information about the key The default is false */ EncryptionOptions setIncludeKeyInfo(boolean includeKeyInfo); }
7,247
0
Create_ds/abdera/security/src/main/java/org/apache/abdera
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/SignatureOptions.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.X509Certificate; /** * Provides access to the information necessary to signed an Abdera element */ public interface SignatureOptions extends SecurityOptions { String getSigningAlgorithm(); SignatureOptions setSigningAlgorithm(String algorithm); /** * Return the private key with which to sign the element */ PrivateKey getSigningKey(); /** * Set the private key with which to sign the element */ SignatureOptions setSigningKey(PrivateKey privateKey); /** * Return the X.509 cert to associated with the signature */ X509Certificate getCertificate(); /** * Set the X.509 cert to associate with the signature */ SignatureOptions setCertificate(X509Certificate cert); /** * Get the public key associated with the signature */ PublicKey getPublicKey(); /** * Set the public key to associate with the signature */ SignatureOptions setPublicKey(PublicKey publickey); SignatureOptions addReference(String href); String[] getReferences(); /** * True if atom:link/@href and atom:content/@src targets should be included in the signature */ SignatureOptions setSignLinks(boolean signlinks); /** * True if atom:link/@href and atom:content/@src targets should be included in the signature */ boolean isSignLinks(); /** * Only sign links whose link rels match those provided in the list */ SignatureOptions setSignedLinkRels(String... rel); /** * Get the list of link relations to sign */ String[] getSignLinkRels(); }
7,248
0
Create_ds/abdera/security/src/main/java/org/apache/abdera
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/Encryption.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security; import org.apache.abdera.model.Document; /** * Interface used for encrypting/decrypting Abdera documents. */ @SuppressWarnings("unchecked") public interface Encryption { /** * Encrypt the document using the specified options * * @param doc The document to encrypt * @param options The encryption options * @return The encrypted document * @throws org.apache.abdera.security.SecurityException if the encryption failed */ Document encrypt(Document doc, EncryptionOptions options) throws SecurityException; /** * Decrypt the document using the specified options * * @param doc The document to decrypt * @param options The decryption options * @return The decrypted document * @throws org.apache.abdera.security.SecurityException if the decryption failed */ Document decrypt(Document doc, EncryptionOptions options) throws SecurityException; /** * Returns true if this specified document has been encrypted */ boolean isEncrypted(Document doc) throws SecurityException; /** * Returns the default encryption/decryption options * * @see org.apache.abdera.security.EncryptionOptions */ EncryptionOptions getDefaultEncryptionOptions(); }
7,249
0
Create_ds/abdera/security/src/main/java/org/apache/abdera
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/AbderaSecurity.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security; import org.apache.abdera.Abdera; import org.apache.abdera.util.Configuration; import org.apache.abdera.util.Discover; /** * The AbderaSecurity class provides the entry point for using XML Digital Signatures and XML Encryption with Abdera. */ public class AbderaSecurity { private final Abdera abdera; private final Encryption encryption; private final Signature signature; public AbderaSecurity() { this(new Abdera()); } public AbderaSecurity(Abdera abdera) { this.abdera = abdera; this.encryption = newEncryption(); this.signature = newSignature(); } public AbderaSecurity(Configuration config) { this(new Abdera(config)); } private Abdera getAbdera() { return abdera; } /** * Acquire a new XML Encryption provider instance */ public Encryption newEncryption() { return (Encryption)Discover.locate("org.apache.abdera.security.Encryption", "org.apache.abdera.security.xmlsec.XmlEncryption", getAbdera()); } /** * Acquire a shared XML Encryption provider instance */ public Encryption getEncryption() { return encryption; } /** * Acquire a new XML Digital Signature provider instance */ public Signature newSignature() { return (Signature)Discover.locate("org.apache.abdera.security.Signature", "org.apache.abdera.security.xmlsec.XmlSignature", getAbdera()); } /** * Acquire a shared XML Digital Signature provider instance */ public Signature getSignature() { return signature; } }
7,250
0
Create_ds/abdera/security/src/main/java/org/apache/abdera/security
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/util/DHContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security.util; import java.io.Serializable; import java.math.BigInteger; import java.security.AlgorithmParameterGenerator; import java.security.AlgorithmParameters; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.security.spec.InvalidParameterSpecException; import java.security.spec.X509EncodedKeySpec; import javax.crypto.KeyAgreement; import javax.crypto.spec.DHParameterSpec; import org.apache.abdera.security.Encryption; import org.apache.abdera.security.EncryptionOptions; import org.apache.axiom.util.base64.Base64Utils; import org.apache.xml.security.encryption.XMLCipher; /** * Implements the Diffie-Hellman Key Exchange details for both parties Party A: DHContext context_a = new DHContext(); * String req = context_a.getRequestString(); Party B: DHContext context_b = new DHContext(req); EncryptionOptions * options = context_b.getEncryptionOptions(enc); // encrypt String ret = context_b.getResponseString(); Party A: * context_a.setPublicKey(ret); EncryptionOptions options = context_a.getEncryptionOptions(enc); // decrypt */ public class DHContext implements Cloneable, Serializable { private static final long serialVersionUID = 9145945368596071015L; BigInteger p = null, g = null; int l = 0; private KeyPair keyPair; private Key publicKey; public DHContext() { try { init(); } catch (Exception e) { } } public DHContext(String dh) { try { init(dh); } catch (Exception e) { } } private DHContext(KeyPair keyPair, BigInteger p, BigInteger g, int l) { this.keyPair = keyPair; this.p = p; this.g = g; this.l = l; } public String getRequestString() { StringBuilder buf = new StringBuilder(); buf.append("DH "); buf.append("p="); buf.append(p.toString()); buf.append(", "); buf.append("g="); buf.append(g.toString()); buf.append(", "); buf.append("k="); buf.append(Base64Utils.encode(keyPair.getPublic().getEncoded())); return buf.toString(); } public String getResponseString() { StringBuilder buf = new StringBuilder(); buf.append("DH "); buf.append("k="); buf.append(Base64Utils.encode(keyPair.getPublic().getEncoded())); return buf.toString(); } private void init() throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidParameterSpecException, InvalidKeySpecException { AlgorithmParameterGenerator pgen = AlgorithmParameterGenerator.getInstance("DH"); pgen.init(512); AlgorithmParameters params = pgen.generateParameters(); DHParameterSpec dhspec = (DHParameterSpec)params.getParameterSpec(DHParameterSpec.class); KeyPairGenerator keypairgen = KeyPairGenerator.getInstance("DH"); keypairgen.initialize(dhspec); keyPair = keypairgen.generateKeyPair(); p = dhspec.getP(); g = dhspec.getG(); l = dhspec.getL(); } private void init(String dh) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeySpecException { String[] segments = dh.split("\\s+", 2); if (!segments[0].equalsIgnoreCase("DH")) throw new IllegalArgumentException(); String[] params = segments[1].split("\\s*,\\s*"); byte[] key = null; for (String param : params) { String name = param.substring(0, param.indexOf("=")); String value = param.substring(param.indexOf("=") + 1); if (name.equalsIgnoreCase("p")) p = new BigInteger(value); else if (name.equalsIgnoreCase("g")) g = new BigInteger(value); else if (name.equalsIgnoreCase("k")) key = Base64Utils.decode(value); } init(p, g, l, key); } private void init(BigInteger p, BigInteger g, int l, byte[] key) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, InvalidKeySpecException { DHParameterSpec spec = new DHParameterSpec(p, g, l); KeyPairGenerator keypairgen = KeyPairGenerator.getInstance("DH"); keypairgen.initialize(spec); keyPair = keypairgen.generateKeyPair(); publicKey = decode(key); } public KeyPair getKeyPair() { return keyPair; } public Key getPublicKey() { return publicKey; } private Key decode(byte[] key) throws NoSuchAlgorithmException, InvalidKeySpecException { X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key); KeyFactory keyFact = KeyFactory.getInstance("DH"); return keyFact.generatePublic(x509KeySpec); } public DHContext setPublicKey(String dh) throws NoSuchAlgorithmException, InvalidKeySpecException { String[] segments = dh.split("\\s+", 2); if (!segments[0].equalsIgnoreCase("DH")) throw new IllegalArgumentException(); String[] tokens = segments[1].split("\\s*,\\s*"); byte[] key = null; for (String token : tokens) { String name = token.substring(0, token.indexOf("=")); String value = token.substring(token.indexOf("=") + 1); if (name.equalsIgnoreCase("k")) key = Base64Utils.decode(value); } publicKey = decode(key); return this; } public Key generateSecret() throws NoSuchAlgorithmException, InvalidKeyException { KeyAgreement ka = KeyAgreement.getInstance("DH"); ka.init(keyPair.getPrivate()); ka.doPhase(publicKey, true); return ka.generateSecret("DESede"); } public EncryptionOptions getEncryptionOptions(Encryption enc) throws InvalidKeyException, NoSuchAlgorithmException { EncryptionOptions options = enc.getDefaultEncryptionOptions(); options.setDataEncryptionKey(generateSecret()); options.setDataCipherAlgorithm(XMLCipher.TRIPLEDES); return options; } @Override public Object clone() throws CloneNotSupportedException { if (publicKey != null) throw new CloneNotSupportedException(); // create a copy, not an actual clone return new DHContext(keyPair, p, g, l); } }
7,251
0
Create_ds/abdera/security/src/main/java/org/apache/abdera/security
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/util/SecurityBase.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security.util; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.apache.abdera.Abdera; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.security.SecurityOptions; @SuppressWarnings("unchecked") public abstract class SecurityBase { protected final Abdera abdera; protected SecurityBase(Abdera abdera) { this.abdera = abdera; } protected Abdera getAbdera() { return abdera; } protected org.w3c.dom.Document fomToDom(Document doc, SecurityOptions options) { org.w3c.dom.Document dom = null; if (doc != null) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); doc.writeTo(out); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); dom = db.parse(in); } catch (Exception e) { } } return dom; } protected Document domToFom(org.w3c.dom.Document dom, SecurityOptions options) { Document doc = null; if (dom != null) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); t.transform(new DOMSource(dom), new StreamResult(out)); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); doc = options.getParser().parse(in); } catch (Exception e) { } } return doc; } protected org.w3c.dom.Element fomToDom(Element element, SecurityOptions options) { org.w3c.dom.Element dom = null; if (element != null) { try { ByteArrayInputStream in = new ByteArrayInputStream(element.toString().getBytes()); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); dom = db.parse(in).getDocumentElement(); } catch (Exception e) { } } return dom; } protected Element domToFom(org.w3c.dom.Element element, SecurityOptions options) { Element el = null; if (element != null) { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(); t.transform(new DOMSource(element), new StreamResult(out)); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); el = options.getParser().parse(in).getRoot(); } catch (Exception e) { } } return el; } }
7,252
0
Create_ds/abdera/security/src/main/java/org/apache/abdera/security
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/util/EncryptionBase.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security.util; import org.apache.abdera.Abdera; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.security.Encryption; import org.apache.abdera.security.SecurityException; @SuppressWarnings("unchecked") public abstract class EncryptionBase extends SecurityBase implements Encryption { public EncryptionBase(Abdera abdera) { super(abdera); } public boolean isEncrypted(Document doc) throws SecurityException { Element el = doc.getRoot(); return el.getQName().equals(Constants.ENCRYPTEDDATA); } }
7,253
0
Create_ds/abdera/security/src/main/java/org/apache/abdera/security
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/util/KeyHelper.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security.util; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.cert.Certificate; import java.security.Key; import java.security.KeyFactory; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.NoSuchProviderException; import java.security.PublicKey; import java.security.SecureRandom; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.security.spec.X509EncodedKeySpec; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import org.apache.commons.codec.binary.Hex; public class KeyHelper { public static void saveKeystore(KeyStore ks, String file, String password) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException { ks.store(new FileOutputStream(file), password.toCharArray()); } public static KeyStore loadKeystore(String file, String pass) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(file); if (in == null) in = new FileInputStream(file); ks.load(in, pass.toCharArray()); return ks; } public static KeyStore loadKeystore(String type, String file, String pass) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore ks = KeyStore.getInstance(type); InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(file); if (in == null) in = new FileInputStream(file); ks.load(in, pass.toCharArray()); return ks; } @SuppressWarnings("unchecked") public static <T extends Key> T getKey(KeyStore ks, String alias, String pass) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException { return (T)ks.getKey(alias, pass.toCharArray()); } @SuppressWarnings("unchecked") public static <T extends Certificate> T getCertificate(KeyStore ks, String alias) throws KeyStoreException { return (T)ks.getCertificate(alias); } public static KeyPair generateKeyPair(String type, int size) throws NoSuchAlgorithmException, NoSuchProviderException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance(type); SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); keyGen.initialize(size, random); random.setSeed(System.currentTimeMillis()); return keyGen.generateKeyPair(); } public static KeyPair generateKeyPair(String type, int size, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { KeyPairGenerator keyGen = KeyPairGenerator.getInstance(type, provider); SecureRandom random = SecureRandom.getInstance("SHA1PRNG", provider); keyGen.initialize(size, random); random.setSeed(System.currentTimeMillis()); return keyGen.generateKeyPair(); } public static SecretKey generateSecretKey(String type, int size) throws NoSuchAlgorithmException, NoSuchProviderException { KeyGenerator keyGenerator = KeyGenerator.getInstance(type); keyGenerator.init(size); return keyGenerator.generateKey(); } public static Key generateKey(String type) throws NoSuchAlgorithmException { KeyGenerator keygen = KeyGenerator.getInstance(type); keygen.init(new SecureRandom()); return keygen.generateKey(); } public static SecretKey generateSecretKey(String type, int size, String provider) throws NoSuchAlgorithmException, NoSuchProviderException { KeyGenerator keyGenerator = KeyGenerator.getInstance(type, provider); keyGenerator.init(size); return keyGenerator.generateKey(); } public static PublicKey generatePublicKey(String hex) { try { if (hex == null || hex.trim().length() == 0) return null; byte[] data = Hex.decodeHex(hex.toCharArray()); X509EncodedKeySpec keyspec = new X509EncodedKeySpec(data); KeyFactory keyfactory = KeyFactory.getInstance("RSA"); return keyfactory.generatePublic(keyspec); } catch (Exception e) { return null; } } }
7,254
0
Create_ds/abdera/security/src/main/java/org/apache/abdera/security
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/util/Constants.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security.util; import javax.xml.namespace.QName; public final class Constants { public static final String CONTENT_ENCRYPTED = "Content-Encrypted"; public static final String ACCEPT_ENCRYPTION = "Accept-Encryption"; Constants() { } public static final String DSIG_NS = "http://www.w3.org/2000/09/xmldsig#"; public static final String XENC_NS = "http://www.w3.org/2001/04/xmlenc#"; public static final String LN_SIGNATURE = "Signature"; public static final String LN_ENCRYPTEDDATA = "EncryptedData"; public static final String DSIG_PREFIX = "dsig"; public static final String XENC_PREFIX = "xenc"; public static final QName SIGNATURE = new QName(DSIG_NS, LN_SIGNATURE, DSIG_PREFIX); public static final QName ENCRYPTEDDATA = new QName(XENC_NS, LN_ENCRYPTEDDATA, XENC_PREFIX); }
7,255
0
Create_ds/abdera/security/src/main/java/org/apache/abdera/security
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/util/SignatureBase.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security.util; import org.apache.abdera.Abdera; import org.apache.abdera.model.Element; import org.apache.abdera.model.ExtensibleElement; import org.apache.abdera.security.SecurityException; import org.apache.abdera.security.Signature; public abstract class SignatureBase extends SecurityBase implements Signature { protected SignatureBase(Abdera abdera) { super(abdera); } public <T extends Element> boolean isSigned(T entry) throws SecurityException { return _isSigned(entry); } private <T extends Element> boolean _isSigned(T element) { if (element instanceof ExtensibleElement) return ((ExtensibleElement)element).getExtension(Constants.SIGNATURE) != null; else return false; } }
7,256
0
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/util
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/util/filters/AESEncryptedResponseFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security.util.filters; import java.security.PublicKey; import java.security.cert.X509Certificate; import java.security.interfaces.RSAPublicKey; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.ResponseContext; import org.apache.abdera.protocol.server.RequestContext.Scope; import org.apache.abdera.security.Encryption; import org.apache.abdera.security.EncryptionOptions; import org.apache.abdera.security.util.KeyHelper; import org.apache.xml.security.encryption.XMLCipher; /** * <pre> * &lt;filter> * &lt;filter-name>enc filter&lt;/filter-name> * &lt;filter-class>com.test.EncryptedResponseFilter&lt;/filter-class> * &lt;/filter> * &lt;filter-mapping> * &lt;filter-name>enc filter&lt;/filter-name> * &lt;servlet-name>TestServlet&lt;/servlet-name> * &lt;/filter-mapping> * </pre> */ public class AESEncryptedResponseFilter extends AbstractEncryptedResponseFilter { public static final String PUBLICKEY = "X-PublicKey"; protected X509Certificate[] getCerts(RequestContext request) { return (X509Certificate[])request.getAttribute(Scope.REQUEST, "javax.servlet.request.X509Certificate"); } protected PublicKey getPublicKey(RequestContext request) { String header = request.getHeader(PUBLICKEY); PublicKey pkey = KeyHelper.generatePublicKey(header); if (pkey == null) pkey = retrievePublicKey(request); return pkey; } protected boolean doEncryption(RequestContext request, Object arg) { return arg != null && arg instanceof RSAPublicKey; } protected Object initArg(RequestContext request) { return getPublicKey(request); } protected PublicKey retrievePublicKey(RequestContext request) { X509Certificate[] cert = getCerts(request); return cert != null ? cert[0].getPublicKey() : null; } protected EncryptionOptions initEncryptionOptions(RequestContext request, ResponseContext response, Encryption enc, Object arg) { try { EncryptionOptions options = enc.getDefaultEncryptionOptions(); options.setDataEncryptionKey(KeyHelper.generateKey("AES")); options.setKeyEncryptionKey((PublicKey)arg); options.setKeyCipherAlgorithm(XMLCipher.RSA_v1dot5); options.setIncludeKeyInfo(true); return options; } catch (Exception e) { return null; } } }
7,257
0
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/util
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/util/filters/SignedResponseFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security.util.filters; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.security.KeyStore; import java.security.PrivateKey; import java.security.cert.X509Certificate; import org.apache.abdera.Abdera; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.protocol.server.Filter; import org.apache.abdera.protocol.server.FilterChain; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.ResponseContext; import org.apache.abdera.protocol.server.context.ResponseContextWrapper; import org.apache.abdera.security.AbderaSecurity; import org.apache.abdera.security.SecurityException; import org.apache.abdera.security.Signature; import org.apache.abdera.security.SignatureOptions; import org.apache.abdera.writer.Writer; /** * <p> * This HTTP Servlet Filter will add an XML Digital Signature to Abdera documents * </p> * * <pre> * &lt;filter> * &lt;filter-name>signing filter&lt;/filter-name> * &lt;filter-class>org.apache.abdera.security.util.servlet.SignedResponseFilter&lt;/filter-class> * &lt;init-param> * &lt;param-name>org.apache.abdera.security.util.servlet.Keystore&lt;/param-name> * &lt;param-value>/key.jks&lt;/param-value> * &lt;/init-param> * &lt;init-param> * &lt;param-name>org.apache.abdera.security.util.servlet.KeystorePassword&lt;/param-name> * &lt;param-value>testing&lt;/param-value> * &lt;/init-param> * &lt;init-param> * &lt;param-name>org.apache.abdera.security.util.servlet.PrivateKeyAlias&lt;/param-name> * &lt;param-value>James&lt;/param-value> * &lt;/init-param> * &lt;init-param> * &lt;param-name>org.apache.abdera.security.util.servlet.PrivateKeyPassword&lt;/param-name> * &lt;param-value>testing&lt;/param-value> * &lt;/init-param> * &lt;init-param> * &lt;param-name>org.apache.abdera.security.util.servlet.CertificateAlias&lt;/param-name> * &lt;param-value>James&lt;/param-value> * &lt;/init-param> * &lt;init-param> * &lt;param-name>org.apache.abdera.security.util.servlet.SigningAlgorithm&lt;/param-name> * &lt;param-value>http://www.w3.org/2000/09/xmldsig#rsa-sha1&lt;/param-value> * &lt;/init-param> * &lt;/filter> * &lt;filter-mapping id="signing-filter"> * &lt;filter-name>signing filter&lt;/filter-name> * &lt;servlet-name>Abdera&lt;/servlet-name> * &lt;/filter-mapping> * </pre> */ public class SignedResponseFilter implements Filter { private static final String keystoreType = "JKS"; private String keystoreFile = null; private String keystorePass = null; private String privateKeyAlias = null; private String privateKeyPass = null; private String certificateAlias = null; private String algorithm = null; private PrivateKey signingKey = null; private X509Certificate cert = null; public SignedResponseFilter(String keystoreFile, String keystorePass, String privateKeyAlias, String privateKeyPass, String certificateAlias, String algorithm) { this.keystoreFile = keystoreFile; this.keystorePass = keystorePass; this.privateKeyAlias = privateKeyAlias; this.privateKeyPass = privateKeyPass; this.certificateAlias = certificateAlias; this.algorithm = algorithm; try { KeyStore ks = KeyStore.getInstance(keystoreType); InputStream in = SignedResponseFilter.class.getResourceAsStream(keystoreFile); ks.load(in, keystorePass.toCharArray()); signingKey = (PrivateKey)ks.getKey(privateKeyAlias, privateKeyPass.toCharArray()); cert = (X509Certificate)ks.getCertificate(certificateAlias); } catch (Exception e) { e.printStackTrace(); } } public ResponseContext filter(RequestContext request, FilterChain chain) { return new SigningResponseContextWrapper(request.getAbdera(), chain.next(request)); } private Document<Element> signDocument(Abdera abdera, Document<Element> doc) throws SecurityException { AbderaSecurity security = new AbderaSecurity(abdera); if (signingKey == null || cert == null) return doc; // pass through Signature sig = security.getSignature(); SignatureOptions options = sig.getDefaultSignatureOptions(); options.setCertificate(cert); options.setSigningKey(signingKey); if (algorithm != null) options.setSigningAlgorithm(algorithm); Element element = doc.getRoot(); element = sig.sign(element, options); return element.getDocument(); } private class SigningResponseContextWrapper extends ResponseContextWrapper { private final Abdera abdera; public SigningResponseContextWrapper(Abdera abdera, ResponseContext response) { super(response); this.abdera = abdera; } public void writeTo(OutputStream out, Writer writer) throws IOException { try { sign(out, null); } catch (Exception se) { throw new RuntimeException(se); } } public void writeTo(OutputStream out) throws IOException { try { sign(out, null); } catch (Exception se) { throw new RuntimeException(se); } } private void sign(OutputStream aout, Writer writer) throws Exception { Document<Element> doc = null; try { ByteArrayOutputStream out = new ByteArrayOutputStream(); if (writer == null) super.writeTo(out); else super.writeTo(out, writer); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); doc = abdera.getParser().parse(in); } catch (Exception e) { } if (doc != null) { doc = signDocument(abdera, doc); doc.writeTo(aout); } else { super.writeTo(aout); } } } public String getKeystoreFile() { return keystoreFile; } public void setKeystoreFile(String keystoreFile) { this.keystoreFile = keystoreFile; } public String getKeystorePass() { return keystorePass; } public void setKeystorePass(String keystorePass) { this.keystorePass = keystorePass; } public String getPrivateKeyAlias() { return privateKeyAlias; } public void setPrivateKeyAlias(String privateKeyAlias) { this.privateKeyAlias = privateKeyAlias; } public String getPrivateKeyPass() { return privateKeyPass; } public void setPrivateKeyPass(String privateKeyPass) { this.privateKeyPass = privateKeyPass; } public String getCertificateAlias() { return certificateAlias; } public void setCertificateAlias(String certificateAlias) { this.certificateAlias = certificateAlias; } public String getAlgorithm() { return algorithm; } public void setAlgorithm(String algorithm) { this.algorithm = algorithm; } public PrivateKey getSigningKey() { return signingKey; } public void setSigningKey(PrivateKey signingKey) { this.signingKey = signingKey; } public X509Certificate getCert() { return cert; } public void setCert(X509Certificate cert) { this.cert = cert; } public static String getKeystoreType() { return keystoreType; } }
7,258
0
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/util
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/util/filters/DHEncryptedResponseFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security.util.filters; import org.apache.abdera.protocol.server.FilterChain; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.ResponseContext; import org.apache.abdera.security.Encryption; import org.apache.abdera.security.EncryptionOptions; import org.apache.abdera.security.util.Constants; import org.apache.abdera.security.util.DHContext; /** * A Servlet Filter that uses Diffie-Hellman Key Exchange to encrypt Atom documents. The HTTP request must include an * Accept-Encryption header in the form: Accept-Encryption: DH p={dh_p}, g={dh_g}, l={dh_l}, k={base64_pubkey} Example * AbderaClient Code: * * <pre> * DHContext context = new DHContext(); * Abdera abdera = new Abdera(); * CommonsClient client = new CommonsClient(abdera); * RequestOptions options = client.getDefaultRequestOptions(); * options.setHeader(&quot;Accept-Encryption&quot;, context.getRequestString()); * * ClientResponse response = client.get(&quot;http://localhost:8080/TestWeb/test&quot;, options); * Document&lt;Element&gt; doc = response.getDocument(); * * String dh_ret = response.getHeader(&quot;Content-Encrypted&quot;); * if (dh_ret != null) { * context.setPublicKey(dh_ret); * AbderaSecurity absec = new AbderaSecurity(abdera); * Encryption enc = absec.getEncryption(); * EncryptionOptions encoptions = context.getEncryptionOptions(enc); * doc = enc.decrypt(doc, encoptions); * } * * doc.writeTo(System.out); * </pre> * * Webapp Deployment: * * <pre> * &lt;filter> * &lt;filter-name>enc filter&lt;/filter-name> * &lt;filter-class>com.test.EncryptedResponseFilter&lt;/filter-class> * &lt;/filter> * &lt;filter-mapping> * &lt;filter-name>enc filter&lt;/filter-name> * &lt;servlet-name>TestServlet&lt;/servlet-name> * &lt;/filter-mapping> * </pre> */ public class DHEncryptedResponseFilter extends AbstractEncryptedResponseFilter { protected boolean doEncryption(RequestContext request, Object arg) { return arg != null; } protected Object initArg(RequestContext request) { return getDHContext(request); } protected EncryptionOptions initEncryptionOptions(RequestContext request, ResponseContext response, Encryption enc, Object arg) { EncryptionOptions options = null; try { DHContext context = (DHContext)arg; options = context.getEncryptionOptions(enc); returnPublicKey(response, context); } catch (Exception e) { } return options; } public ResponseContext filter(RequestContext request, FilterChain chain) { ResponseContext response = super.filter(request, chain); DHContext context = getDHContext(request); response.setHeader(Constants.CONTENT_ENCRYPTED, context.getResponseString()); return response; } private void returnPublicKey(ResponseContext response, DHContext context) { response.setHeader(Constants.CONTENT_ENCRYPTED, context.getResponseString()); } private DHContext getDHContext(RequestContext request) { try { String dh_req = request.getHeader(Constants.ACCEPT_ENCRYPTION); if (dh_req == null || dh_req.length() == 0) return null; return new DHContext(dh_req); } catch (Exception e) { return null; } } }
7,259
0
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/util
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/util/filters/AbstractEncryptedRequestFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security.util.filters; import java.io.IOException; import java.security.Provider; import java.security.Security; import java.util.ArrayList; import java.util.List; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.parser.ParseException; import org.apache.abdera.parser.Parser; import org.apache.abdera.parser.ParserOptions; import org.apache.abdera.protocol.server.Filter; import org.apache.abdera.protocol.server.FilterChain; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.ResponseContext; import org.apache.abdera.protocol.server.context.RequestContextWrapper; import org.apache.abdera.security.AbderaSecurity; import org.apache.abdera.security.Encryption; import org.apache.abdera.security.EncryptionOptions; public abstract class AbstractEncryptedRequestFilter implements Filter { // The methods that allow encrypted bodies protected final List<String> methods = new ArrayList<String>(); protected AbstractEncryptedRequestFilter() { this("POST", "PUT"); } protected AbstractEncryptedRequestFilter(String... methods) { for (String method : methods) this.methods.add(method); initProvider(); } protected void initProvider() { } protected void addProvider(Provider provider) { if (Security.getProvider(provider.getName()) == null) Security.addProvider(provider); } public ResponseContext filter(RequestContext request, FilterChain chain) { bootstrap(request); String method = request.getMethod(); if (methods.contains(method.toUpperCase())) { return chain.next(new DecryptingRequestContextWrapper(request)); } else return chain.next(request); } protected abstract void bootstrap(RequestContext request); protected abstract Object initArg(RequestContext request); protected abstract EncryptionOptions initEncryptionOptions(RequestContext request, Encryption encryption, Object arg); private class DecryptingRequestContextWrapper extends RequestContextWrapper { public DecryptingRequestContextWrapper(RequestContext request) { super(request); } @SuppressWarnings("unchecked") public <T extends Element> Document<T> getDocument(Parser parser, ParserOptions options) throws ParseException, IOException { Document<Element> doc = super.getDocument(); try { if (doc != null) { AbderaSecurity security = new AbderaSecurity(getAbdera()); Encryption enc = security.getEncryption(); if (enc.isEncrypted(doc)) { Object arg = initArg(request); EncryptionOptions encoptions = initEncryptionOptions(request, enc, arg); doc = enc.decrypt(doc, encoptions); } } } catch (Exception e) { } return (Document<T>)doc; } } }
7,260
0
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/util
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/util/filters/DHEncryptedRequestFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security.util.filters; import org.apache.abdera.protocol.server.FilterChain; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.ResponseContext; import org.apache.abdera.protocol.server.RequestContext.Scope; import org.apache.abdera.security.Encryption; import org.apache.abdera.security.EncryptionOptions; import org.apache.abdera.security.util.Constants; import org.apache.abdera.security.util.DHContext; /** * A filter implementation that allows requests to be encrypted using Diffie-Hellman key negotiation. A client first * uses GET/HEAD/OPTIONS to get the servers DH information, then sends an encrypted request containing it's DH * information. The server can then decrypt and process the request. Note: this is currently untested. */ public class DHEncryptedRequestFilter extends AbstractEncryptedRequestFilter { public DHEncryptedRequestFilter() { super(); } public DHEncryptedRequestFilter(String... methods) { super(methods); } public void bootstrap(RequestContext request) { } public ResponseContext filter(RequestContext request, FilterChain chain) { ResponseContext response = super.filter(request, chain); String method = request.getMethod(); // include a Accept-Encryption header in the response to GET, HEAD and OPTIONS requests // the header will specify all the information the client needs to construct // it's own DH context and encrypt the request if ("GET".equalsIgnoreCase(method) || "HEAD".equalsIgnoreCase(method) || "OPTIONS".equalsIgnoreCase(method)) { DHContext context = (DHContext)request.getAttribute(Scope.SESSION, "dhcontext"); if (context == null) { context = new DHContext(); request.setAttribute(Scope.SESSION, "dhcontext", context); } response.setHeader(Constants.ACCEPT_ENCRYPTION, context.getRequestString()); } return response; } protected Object initArg(RequestContext request) { DHContext context = (DHContext)request.getAttribute(Scope.SESSION, "dhcontext"); String dh = request.getHeader(Constants.CONTENT_ENCRYPTED); if (context != null && dh != null && dh.length() > 0) { try { context.setPublicKey(dh); } catch (Exception e) { } } return context; } protected EncryptionOptions initEncryptionOptions(RequestContext request, Encryption encryption, Object arg) { EncryptionOptions options = null; if (arg != null && arg instanceof DHContext) { try { options = ((DHContext)arg).getEncryptionOptions(encryption); } catch (Exception e) { } } return options; } }
7,261
0
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/util
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/util/filters/AbstractEncryptedResponseFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security.util.filters; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.security.Provider; import java.security.Security; import org.apache.abdera.Abdera; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.protocol.server.Filter; import org.apache.abdera.protocol.server.FilterChain; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.ResponseContext; import org.apache.abdera.protocol.server.context.ResponseContextWrapper; import org.apache.abdera.security.AbderaSecurity; import org.apache.abdera.security.Encryption; import org.apache.abdera.security.EncryptionOptions; import org.apache.abdera.writer.Writer; @SuppressWarnings("unchecked") public abstract class AbstractEncryptedResponseFilter implements Filter { public AbstractEncryptedResponseFilter() { initProvider(); } protected void initProvider() { } protected void addProvider(Provider provider) { if (Security.getProvider(provider.getName()) == null) Security.addProvider(provider); } public ResponseContext filter(RequestContext request, FilterChain chain) { Object arg = initArg(request); if (doEncryption(request, arg)) { return new EncryptingResponseContext(request.getAbdera(), request, chain.next(request), arg); } else { return chain.next(request); } } protected abstract boolean doEncryption(RequestContext request, Object arg); protected abstract EncryptionOptions initEncryptionOptions(RequestContext request, ResponseContext response, Encryption enc, Object arg); protected abstract Object initArg(RequestContext request); private class EncryptingResponseContext extends ResponseContextWrapper { private final RequestContext request; private final AbderaSecurity security; private final Abdera abdera; private final Object arg; public EncryptingResponseContext(Abdera abdera, RequestContext request, ResponseContext response, Object arg) { super(response); this.abdera = abdera; this.request = request; this.security = new AbderaSecurity(abdera); this.arg = arg; } public void writeTo(OutputStream out, Writer writer) throws IOException { try { encrypt(out, null); } catch (Exception se) { throw new RuntimeException(se); } } public void writeTo(OutputStream out) throws IOException { try { encrypt(out, null); } catch (Exception se) { throw new RuntimeException(se); } } private void encrypt(OutputStream aout, Writer writer) throws Exception { Document<Element> doc = null; try { ByteArrayOutputStream out = new ByteArrayOutputStream(); if (writer == null) super.writeTo(out); else super.writeTo(out, writer); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); doc = abdera.getParser().parse(in); } catch (Exception e) { } if (doc != null) { Encryption enc = security.getEncryption(); EncryptionOptions options = initEncryptionOptions(request, response, enc, arg); doc = enc.encrypt(doc, options); } if (doc != null) doc.writeTo(aout); else throw new RuntimeException("There was an error encrypting the response"); } } }
7,262
0
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/util
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/util/filters/SignedRequestFilter.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security.util.filters; import org.apache.abdera.i18n.text.Localizer; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.protocol.server.Filter; import org.apache.abdera.protocol.server.FilterChain; import org.apache.abdera.protocol.server.ProviderHelper; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.ResponseContext; import org.apache.abdera.security.AbderaSecurity; import org.apache.abdera.security.Signature; /** * Servlet Filter that verifies that an Atom document received by the server via PUT or POST contains a valid XML * Digital Signature. */ public class SignedRequestFilter implements Filter { public static final String VALID = "org.apache.abdera.security.util.servlet.SignedRequestFilter.valid"; public static final String CERTS = "org.apache.abdera.security.util.servlet.SignedRequestFilter.certs"; public ResponseContext filter(RequestContext request, FilterChain chain) { AbderaSecurity security = new AbderaSecurity(request.getAbdera()); Signature sig = security.getSignature(); String method = request.getMethod(); if (method.equals("POST") || method.equals("PUT")) { try { Document<Element> doc = request.getDocument(); boolean valid = sig.verify(doc.getRoot(), null); if (!valid) return ProviderHelper.badrequest(request, Localizer.get("VALID.SIGNATURE.REQUIRED")); request.setAttribute(VALID, valid); request.setAttribute(CERTS, sig.getValidSignatureCertificates(doc.getRoot(), null)); } catch (Exception e) { } } return chain.next(request); } }
7,263
0
Create_ds/abdera/security/src/main/java/org/apache/abdera/security
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/xmlsec/XmlSignatureOptions.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security.xmlsec; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import org.apache.abdera.Abdera; import org.apache.abdera.security.SignatureOptions; public class XmlSignatureOptions extends XmlSecurityOptions implements SignatureOptions { private PrivateKey signingKey = null; private PublicKey publickey = null; private X509Certificate cert = null; private String[] linkrels = null; private boolean signlinks = false; private List<String> references = null; private String algo = "http://www.w3.org/2000/09/xmldsig#dsa-sha1"; public String getSigningAlgorithm() { return algo; } public SignatureOptions setSigningAlgorithm(String algorithm) { this.algo = algorithm; return this; } protected XmlSignatureOptions(Abdera abdera) { super(abdera); references = new ArrayList<String>(); } public PrivateKey getSigningKey() { return signingKey; } public SignatureOptions setSigningKey(PrivateKey privateKey) { this.signingKey = privateKey; return this; } public X509Certificate getCertificate() { return cert; } public SignatureOptions setCertificate(X509Certificate cert) { this.cert = cert; return this; } public SignatureOptions addReference(String href) { if (!references.contains(href)) references.add(href); return this; } public String[] getReferences() { return references.toArray(new String[references.size()]); } public PublicKey getPublicKey() { return publickey; } public SignatureOptions setPublicKey(PublicKey publickey) { this.publickey = publickey; return this; } public boolean isSignLinks() { return signlinks; } public SignatureOptions setSignLinks(boolean signlinks) { this.signlinks = signlinks; return this; } public String[] getSignLinkRels() { return this.linkrels; } public SignatureOptions setSignedLinkRels(String... rel) { this.linkrels = rel; return this; } }
7,264
0
Create_ds/abdera/security/src/main/java/org/apache/abdera/security
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/xmlsec/XmlSecurityOptions.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security.xmlsec; import org.apache.abdera.Abdera; import org.apache.abdera.parser.Parser; import org.apache.abdera.security.SecurityOptions; public abstract class XmlSecurityOptions implements SecurityOptions { protected Parser parser = null; protected final Abdera abdera; protected XmlSecurityOptions(Abdera abdera) { this.abdera = abdera; } public Parser getParser() { return (parser != null) ? parser : abdera.getParser(); } @SuppressWarnings("unchecked") public <T extends SecurityOptions> T setParser(Parser parser) { this.parser = parser; return (T)this; } }
7,265
0
Create_ds/abdera/security/src/main/java/org/apache/abdera/security
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/xmlsec/XmlSignature.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security.xmlsec; import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.List; import org.apache.abdera.Abdera; import org.apache.abdera.model.Content; import org.apache.abdera.model.Element; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Link; import org.apache.abdera.model.Source; import org.apache.abdera.security.SecurityException; import org.apache.abdera.security.SignatureOptions; import org.apache.abdera.security.util.Constants; import org.apache.abdera.security.util.SignatureBase; import org.apache.abdera.i18n.iri.IRI; import org.apache.xml.security.exceptions.XMLSecurityException; import org.apache.xml.security.keys.KeyInfo; import org.apache.xml.security.signature.XMLSignature; import org.apache.xml.security.signature.XMLSignatureException; import org.apache.xml.security.transforms.Transforms; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class XmlSignature extends SignatureBase { static { if (!org.apache.xml.security.Init.isInitialized()) org.apache.xml.security.Init.init(); } public XmlSignature() { super(new Abdera()); } public XmlSignature(Abdera abdera) { super(abdera); } @SuppressWarnings("unchecked") private <T extends Element> T _sign(T element, SignatureOptions options) throws XMLSecurityException { element.setBaseUri(element.getResolvedBaseUri()); org.w3c.dom.Element dom = fomToDom((Element)element.clone(), options); org.w3c.dom.Document domdoc = dom.getOwnerDocument(); PrivateKey signingKey = options.getSigningKey(); X509Certificate cert = options.getCertificate(); PublicKey pkey = options.getPublicKey(); IRI baseUri = element.getResolvedBaseUri(); XMLSignature sig = new XMLSignature(domdoc, (baseUri != null) ? baseUri.toString() : "", options.getSigningAlgorithm()); dom.appendChild(sig.getElement()); Transforms transforms = new Transforms(domdoc); transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE); transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS); sig.addDocument("", transforms, org.apache.xml.security.utils.Constants.ALGO_ID_DIGEST_SHA1); String[] refs = options.getReferences(); for (String ref : refs) sig.addDocument(ref); if (options.isSignLinks()) { String[] rels = options.getSignLinkRels(); List<Link> links = null; Content content = null; if (element instanceof Source) { links = (rels == null) ? ((Source)element).getLinks() : ((Source)element).getLinks(rels); } else if (element instanceof Entry) { links = (rels == null) ? ((Entry)element).getLinks() : ((Entry)element).getLinks(rels); content = ((Entry)element).getContentElement(); } if (links != null) { for (Link link : links) { sig.addDocument(link.getResolvedHref().toASCIIString()); } } if (content != null && content.getResolvedSrc() != null) sig.addDocument(content.getResolvedSrc().toASCIIString()); } if (cert != null) sig.addKeyInfo(cert); if (pkey != null) sig.addKeyInfo(pkey); sig.sign(signingKey); return (T)domToFom(dom, options); } public <T extends Element> T sign(T entry, SignatureOptions options) throws SecurityException { try { return (T)_sign(entry, options); } catch (Exception e) { throw new SecurityException(e); } } private boolean is_valid_signature(XMLSignature sig, SignatureOptions options) throws XMLSignatureException, XMLSecurityException { KeyInfo ki = sig.getKeyInfo(); if (ki != null) { X509Certificate cert = ki.getX509Certificate(); if (cert != null) { return sig.checkSignatureValue(cert); } else { PublicKey key = ki.getPublicKey(); if (key != null) { return sig.checkSignatureValue(key); } } } else if (options != null) { PublicKey key = options.getPublicKey(); X509Certificate cert = options.getCertificate(); if (key != null) return sig.checkSignatureValue(key); if (cert != null) return sig.checkSignatureValue(cert); } return false; } private <T extends Element> X509Certificate[] _getcerts(T element, SignatureOptions options) throws XMLSignatureException, XMLSecurityException { List<X509Certificate> certs = new ArrayList<X509Certificate>(); org.w3c.dom.Element dom = fomToDom((Element)element, options); NodeList children = dom.getChildNodes(); for (int n = 0; n < children.getLength(); n++) { try { Node node = children.item(n); if (node.getNodeType() == Node.ELEMENT_NODE) { org.w3c.dom.Element el = (org.w3c.dom.Element)node; if (Constants.DSIG_NS.equals(el.getNamespaceURI()) && Constants.LN_SIGNATURE.equals(el .getLocalName())) { IRI baseUri = element.getResolvedBaseUri(); XMLSignature sig = new XMLSignature(el, (baseUri != null) ? baseUri.toString() : ""); if (is_valid_signature(sig, options)) { KeyInfo ki = sig.getKeyInfo(); if (ki != null) { X509Certificate cert = ki.getX509Certificate(); if (cert != null) certs.add(cert); } } } } } catch (Exception e) { } } return certs.toArray(new X509Certificate[certs.size()]); } public <T extends Element> X509Certificate[] getValidSignatureCertificates(T element, SignatureOptions options) throws SecurityException { try { return _getcerts(element, options); } catch (Exception e) { } return null; } public <T extends Element> KeyInfo getSignatureKeyInfo(T element, SignatureOptions options) throws SecurityException { KeyInfo ki = null; org.w3c.dom.Element dom = fomToDom((Element)element, options); NodeList children = dom.getChildNodes(); for (int n = 0; n < children.getLength(); n++) { try { Node node = children.item(n); if (node.getNodeType() == Node.ELEMENT_NODE) { org.w3c.dom.Element el = (org.w3c.dom.Element)node; if (Constants.DSIG_NS.equals(el.getNamespaceURI()) && Constants.LN_SIGNATURE.equals(el .getLocalName())) { IRI baseUri = element.getResolvedBaseUri(); XMLSignature sig = new XMLSignature(el, (baseUri != null) ? baseUri.toString() : ""); ki = sig.getKeyInfo(); } } } catch (Exception e) { } } return ki; } private boolean _verify(Element element, SignatureOptions options) throws XMLSignatureException, XMLSecurityException { boolean answer = false; org.w3c.dom.Element dom = fomToDom((Element)element, options); NodeList children = dom.getChildNodes(); for (int n = 0; n < children.getLength(); n++) { Node node = children.item(n); if (node.getNodeType() == Node.ELEMENT_NODE) { org.w3c.dom.Element el = (org.w3c.dom.Element)node; if (Constants.DSIG_NS.equals(el.getNamespaceURI()) && Constants.LN_SIGNATURE.equals(el.getLocalName())) { IRI baseUri = element.getResolvedBaseUri(); XMLSignature sig = new XMLSignature(el, (baseUri != null) ? baseUri.toString() : ""); answer = is_valid_signature(sig, options); } } } return answer; } public <T extends Element> boolean verify(T entry, SignatureOptions options) throws SecurityException { if (!isSigned(entry)) return false; try { return _verify(entry, options); } catch (Exception e) { throw new SecurityException(e); } } public SignatureOptions getDefaultSignatureOptions() throws SecurityException { return new XmlSignatureOptions(getAbdera()); } @SuppressWarnings("unchecked") public <T extends Element> T removeInvalidSignatures(T element, SignatureOptions options) throws SecurityException { List<org.w3c.dom.Element> remove = new ArrayList<org.w3c.dom.Element>(); org.w3c.dom.Element dom = fomToDom((Element)element, options); NodeList children = dom.getChildNodes(); for (int n = 0; n < children.getLength(); n++) { try { Node node = children.item(n); if (node.getNodeType() == Node.ELEMENT_NODE) { org.w3c.dom.Element el = (org.w3c.dom.Element)node; if (Constants.DSIG_NS.equals(el.getNamespaceURI()) && Constants.LN_SIGNATURE.equals(el .getLocalName())) { IRI baseUri = element.getResolvedBaseUri(); XMLSignature sig = new XMLSignature(el, (baseUri != null) ? baseUri.toString() : ""); if (!is_valid_signature(sig, options)) { remove.add(el); } } } } catch (Exception e) { } } for (org.w3c.dom.Element el : remove) dom.removeChild(el); return (T)domToFom(dom, options); } }
7,266
0
Create_ds/abdera/security/src/main/java/org/apache/abdera/security
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/xmlsec/XmlEncryption.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security.xmlsec; import java.security.Key; import org.apache.abdera.Abdera; import org.apache.abdera.model.Document; import org.apache.abdera.security.EncryptionOptions; import org.apache.abdera.security.SecurityException; import org.apache.abdera.security.util.EncryptionBase; import org.apache.xml.security.encryption.EncryptedData; import org.apache.xml.security.encryption.EncryptedKey; import org.apache.xml.security.encryption.XMLCipher; import org.apache.xml.security.keys.KeyInfo; @SuppressWarnings("unchecked") public class XmlEncryption extends EncryptionBase { static { if (!org.apache.xml.security.Init.isInitialized()) org.apache.xml.security.Init.init(); } public XmlEncryption() { super(new Abdera()); } public XmlEncryption(Abdera abdera) { super(abdera); } public Document encrypt(Document doc, EncryptionOptions options) throws SecurityException { try { org.w3c.dom.Document dom = fomToDom(doc, options); Key dek = options.getDataEncryptionKey(); Key kek = options.getKeyEncryptionKey(); String dalg = options.getDataCipherAlgorithm(); String kalg = options.getKeyCipherAlgorithm(); boolean includeki = options.includeKeyInfo(); EncryptedKey enckey = null; XMLCipher xmlCipher = XMLCipher.getInstance(dalg); xmlCipher.init(XMLCipher.ENCRYPT_MODE, dek); if (includeki && kek != null && dek != null) { XMLCipher keyCipher = XMLCipher.getInstance(kalg); keyCipher.init(XMLCipher.WRAP_MODE, kek); enckey = keyCipher.encryptKey(dom, dek); EncryptedData encdata = xmlCipher.getEncryptedData(); KeyInfo keyInfo = new KeyInfo(dom); keyInfo.add(enckey); encdata.setKeyInfo(keyInfo); } dom = xmlCipher.doFinal(dom, dom.getDocumentElement(), false); return domToFom(dom, options); } catch (Exception e) { throw new SecurityException(e); } } public Document decrypt(Document doc, EncryptionOptions options) throws SecurityException { if (!isEncrypted(doc)) return null; try { org.w3c.dom.Document dom = fomToDom(doc, options); Key kek = options.getKeyEncryptionKey(); Key dek = options.getDataEncryptionKey(); org.w3c.dom.Element element = dom.getDocumentElement(); XMLCipher xmlCipher = XMLCipher.getInstance(); xmlCipher.init(XMLCipher.DECRYPT_MODE, dek); xmlCipher.setKEK(kek); dom = xmlCipher.doFinal(dom, element); return domToFom(dom, options); } catch (Exception e) { throw new SecurityException(e); } } public EncryptionOptions getDefaultEncryptionOptions() { return new XmlEncryptionOptions(getAbdera()); } }
7,267
0
Create_ds/abdera/security/src/main/java/org/apache/abdera/security
Create_ds/abdera/security/src/main/java/org/apache/abdera/security/xmlsec/XmlEncryptionOptions.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.security.xmlsec; import java.security.Key; import org.apache.abdera.Abdera; import org.apache.abdera.security.EncryptionOptions; public class XmlEncryptionOptions extends XmlSecurityOptions implements EncryptionOptions { private Key dek = null; private Key kek = null; private String kca = "http://www.w3.org/2001/04/xmlenc#kw-aes128"; private String dca = "http://www.w3.org/2001/04/xmlenc#aes128-cbc"; private boolean setki = false; protected XmlEncryptionOptions(Abdera abdera) { super(abdera); } public Key getDataEncryptionKey() { return dek; } public EncryptionOptions setDataEncryptionKey(Key key) { this.dek = key; return this; } public Key getKeyEncryptionKey() { return kek; } public EncryptionOptions setKeyEncryptionKey(Key key) { this.kek = key; return this; } public String getKeyCipherAlgorithm() { return kca; } public EncryptionOptions setKeyCipherAlgorithm(String alg) { this.kca = alg; return this; } public String getDataCipherAlgorithm() { return dca; } public EncryptionOptions setDataCipherAlgorithm(String alg) { this.dca = alg; return this; } public boolean includeKeyInfo() { return setki; } public EncryptionOptions setIncludeKeyInfo(boolean includeKeyInfo) { this.setki = includeKeyInfo; return this; } }
7,268
0
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test/templates/TestTemplate.java
package org.apache.abdera.i18n.test.templates; import static org.junit.Assert.assertEquals; import java.util.HashMap; import java.util.Map; import org.apache.abdera.i18n.templates.Template; import org.junit.Test; public class TestTemplate { @Test public void testTemplateNeg() { Template t = new Template("*http://cnn.com/{-neg|all|foo,bar}"); Map m = new HashMap(); m.put("foo", "value"); String out = t.expand(m); assertEquals("*http://cnn.com/", out); } }
7,269
0
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test/iri/TestTemplate.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.test.iri; import static org.junit.Assert.assertEquals; import java.io.ByteArrayInputStream; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.abdera.i18n.templates.HashMapContext; import org.apache.abdera.i18n.templates.Template; import org.apache.abdera.i18n.templates.URITemplate; import org.junit.Test; public final class TestTemplate extends TestBase { @Test public void test1() throws Exception { String t = "http://bitworking.org/news/{entry}"; String e = "http://bitworking.org/news/RESTLog_Specification"; HashMapContext c = new HashMapContext(); c.put("entry", "RESTLog_Specification"); eval(t, e, c); } @Test public void test2() throws Exception { String t = "http://example.org/wiki/{entry=FrontPage}"; String e = "http://example.org/wiki/FrontPage"; HashMapContext c = new HashMapContext(); eval(t, e, c); } @Test public void test3() throws Exception { String t = "http://bitworking.org/news/{-list|/|entry}"; String e = "http://bitworking.org/news/240/Newsqueak"; HashMapContext c = new HashMapContext(); c.put("entry", new String[] {"240", "Newsqueak"}); eval(t, e, c); } @Test public void test4() throws Exception { String t = "http://technorati.com/search/{term}"; String e = "http://technorati.com/search/240%2FNewsqueak"; HashMapContext c = new HashMapContext(); c.put("term", "240/Newsqueak"); eval(t, e, c); } @Test public void test5() throws Exception { String t = "http://example.org/{fruit=orange}/"; String e = "http://example.org/apple/"; String f = "http://example.org/orange/"; HashMapContext c = new HashMapContext(); c.put("fruit", "apple"); eval(t, e, c); c.remove("fruit"); eval(t, f, c); } @Test public void test6() throws Exception { String t = "bar{-prefix|/|var}/"; String e = "bar/foo/"; HashMapContext c = new HashMapContext(); c.put("var", "foo"); eval(t, e, c); } @Test public void test7() throws Exception { String t = "bar/{-suffix|#home|var}"; String e = "bar/foo#home"; HashMapContext c = new HashMapContext(); c.put("var", "foo"); eval(t, e, c); } @Test public void test8() throws Exception { String t = "{-join|&|name,location,age}"; String e = "name=joe&location=NYC"; HashMapContext c = new HashMapContext(); c.put("name", "joe"); c.put("location", "NYC"); eval(t, e, c); } @Test public void test9() throws Exception { String t = "{-list|/|segments}"; String e = "a/b/c"; HashMapContext c = new HashMapContext(); c.put("segments", new String[] {"a", "b", "c"}); eval(t, e, c); } @Test public void test10() throws Exception { String t = "{-opt|/|segments}"; String e = "/"; HashMapContext c = new HashMapContext(); c.put("segments", new String[] {"a", "b", "c"}); eval(t, e, c); } @Test public void test11() throws Exception { String t = "{-neg|/|segments}"; String e = ""; HashMapContext c = new HashMapContext(); c.put("segments", new String[] {"a", "b", "c"}); eval(t, e, c); } @Test public void test12() throws Exception { String t = "http://www.google.com/search?q={term}"; String e = "http://www.google.com/search?q=ben%26jerrys"; HashMapContext c = new HashMapContext(); c.put("term", "ben&jerrys"); eval(t, e, c); t = "http://www.google.com/search?q={term}"; e = "http://www.google.com/search?q=2%2B2%3D5"; c = new HashMapContext(); c.put("term", "2+2=5"); eval(t, e, c); t = "http://www.google.com/base/feeds/snippets/?{-join|&|author}"; e = "http://www.google.com/base/feeds/snippets/?author=test%40example.com"; c = new HashMapContext(); c.put("author", "test@example.com"); eval(t, e, c); } @Test public void test13() throws Exception { String t = "http://www.google.com/search?q={term}"; String e = "http://www.google.com/search?q=%C3%8E%C3%B1%C5%A3%C3%A9r%C3%B1%C3%A5%C5%A3%C3%AE%C3%B6%C3%B1%C3%A5%C4%BC%C3%AE%C5%BE%C3%A5%C5%A3%C3%AE%C3%B6%C3%B1"; HashMapContext c = new HashMapContext(); c .put("term", "\u00ce\u00f1\u0163\u00e9\u0072\u00f1\u00e5\u0163\u00ee\u00f6\u00f1\u00e5\u013c\u00ee\u017e\u00e5\u0163\u00ee\u00f6\u00f1"); eval(t, e, c); } @Test public void test14() throws Exception { String t = "{-opt|/-/|categories}{-list|/|categories}"; String e = "/-/A%7C-B/-C"; HashMapContext c = new HashMapContext(); c.put("categories", new String[] {"A|-B", "-C"}); eval(t, e, c); } @Test public void test15() throws Exception { String t = "http://www.google.com/notebook/feeds/{userID}{-prefix|/notebooks/|notebookID}{-opt|/-/|categories}{-list|/|categories}?{-join|&|updated-min,updated-max,alt,start-index,max-results,entryID,orderby}"; String e = "http://www.google.com/notebook/feeds/a/notebooks/b?updated-min=c&max-results=d"; HashMapContext c = new HashMapContext(); c.put("userID", "a"); c.put("notebookID", "b"); c.put("updated-min", "c"); c.put("max-results", "d"); eval(t, e, c); } @Test public void test16() throws Exception { String t = "http://www.google.com/search?q={term}"; String e = "http://www.google.com/search?q=\u00ce\u00f1\u0163\u00e9\u0072\u00f1\u00e5\u0163\u00ee\u00f6\u00f1\u00e5\u013c\u00ee\u017e\u00e5\u0163\u00ee\u00f6\u00f1"; HashMapContext c = new HashMapContext(); c.setIri(true); c .put("term", "\u00ce\u00f1\u0163\u00e9\u0072\u00f1\u00e5\u0163\u00ee\u00f6\u00f1\u00e5\u013c\u00ee\u017e\u00e5\u0163\u00ee\u00f6\u00f1"); eval(t, e, c); // use the IriEvaluator so that pct-encoding is done correctly for IRI's } @Test public void test17() throws Exception { String t = new String("bar{-prefix|/é/|var}/".getBytes("UTF-8"), "UTF-8"); String e = new String("bar/é/foo/".getBytes("UTF-8"), "UTF-8"); HashMapContext c = new HashMapContext(); c.setIri(true); c.put("var", "foo"); eval(t, e, c); } @Test public void test18() throws Exception { String t = "http://www.google.com/notebook/feeds/{userID}{-prefix|/notebooks/|notebookID}{-opt|/-/|categories}{-list|/|categories}?{-join|&|updated-min,updated-max,alt,start-index,max-results,entryID,orderby}"; Template template = new Template(t); String[] variables = template.getVariables(); assertEquals("userID", variables[0]); assertEquals("notebookID", variables[1]); assertEquals("categories", variables[2]); assertEquals("updated-min", variables[3]); assertEquals("updated-max", variables[4]); assertEquals("alt", variables[5]); assertEquals("start-index", variables[6]); assertEquals("max-results", variables[7]); assertEquals("entryID", variables[8]); assertEquals("orderby", variables[9]); } @Test public void test19() throws Exception { String t = "http://www.google.com/notebook/feeds/{userID}{-prefix|/notebooks/|notebookID}{-opt|/-/|categories}{-list|/|categories}?{-join|&|updated-min,updated-max,alt,start-index,max-results,entryID,orderby}"; Template template = new Template(t); Template t2 = template.clone(); assertEquals(t2, template); assertEquals(t2.hashCode(), template.hashCode()); } @Test public void test20() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("a", "foo"); map.put("b", "bar"); map.put("data", "10,20,30"); map.put("points", new String[] {"10", "20", "30"}); map.put("list0", new String[0]); map.put("str0", ""); map.put("reserved", ":/?#[]@!$&'()*+,;="); map.put("u", "\u2654\u2655"); map.put("a_b", "baz"); map.put("bytes", new byte[] {'a', 'b', 'c'}); map.put("stream", new ByteArrayInputStream(new byte[] {'a', 'b', 'c'})); map.put("chars", new char[] {'a', 'b', 'c', '/'}); map.put("ints", new int[] {1, 2, 3}); Map<String, String> tests = new HashMap<String, String>(); tests.put("http://example.org/?q={a}", "http://example.org/?q=foo"); tests.put("http://example.org/{foo}", "http://example.org/"); tests.put("relative/{reserved}/", "relative/%3A%2F%3F%23%5B%5D%40%21%24%26%27%28%29%2A%2B%2C%3B%3D/"); tests.put("http://example.org/{foo=fred}", "http://example.org/fred"); tests.put("http://example.org/{foo=%25}/", "http://example.org/%25/"); tests.put("/{-prefix|#|foo}", "/"); tests.put("./{-prefix|#|str0}", "./"); tests.put("/{-suffix|/|a}{-opt|data|points}{-neg|@|a}{-prefix|#|b}", "/foo/data#bar"); tests.put("http://example.org/q={u}", "http://example.org/q=%E2%99%94%E2%99%95"); tests.put("http://example.org/?{-join|&|a,data}", "http://example.org/?a=foo&data=10%2C20%2C30"); tests.put("http://example.org/?d={-list|,|points}&{-join|&|a,b}", "http://example.org/?d=10,20,30&a=foo&b=bar"); tests.put("http://example.org/?d={-list|,|list0}&{-join|&|foo}", "http://example.org/?d=&"); tests.put("http://example.org/?d={-list|&d=|points}", "http://example.org/?d=10&d=20&d=30"); tests.put("http://example.org/{a}{b}/{a_b}", "http://example.org/foobar/baz"); tests.put("http://example.org/{a}{-prefix|/-/|a}/", "http://example.org/foo/-/foo/"); tests.put("{bytes}", "%61%62%63"); tests.put("{stream}", "%61%62%63"); tests.put("{chars}", "abc%2F"); tests.put("{ints}", "1%2C2%2C3"); for (String t : tests.keySet()) assertEquals(tests.get(t), Template.expand(t, map)); } @Test public void test21() throws Exception { String t = "http://example.org/{foo}/{bar}{-opt|/|categories}{-list|/|categories}?{-join|&|baz,tag}"; String e = "http://example.org/abc/xyz/a/b?baz=true&tag=x&tag=y&tag=z"; assertEquals(e, Template.expand(t, new MyObject())); } @Test public void test22() throws Exception { String e = "http://example.org/abc/xyz/a/b?baz=true&tag=x&tag=y&tag=z"; assertEquals(e, Template.expandAnnotated(new MyObject())); } @Test public void test23() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("foo", "\u03d3"); map.put("bar", "fred"); map.put("baz", new int[] {10, 20, 30}); map.put("qux", new String[] {"10", "20", "30"}); map.put("corge", new String[0]); map.put("garply", "a/b/c"); map.put("grault", ""); map.put("waldo", "ben & jerrys"); map.put("fred", new String[] {"fred", "", "wilma"}); map.put("plugh", new String[] {"\u017F\u0307", "\u0073\u0307"}); map.put("1-a_b.c", 200); String[] templates = {"http://example.org/?q={bar}", "http://example.org/?q=fred", "/{xyzzy}", "/", "http://example.org/?{-join|&|foo,bar,xyzzy,baz}", "http://example.org/?foo=%CE%8E&bar=fred&baz=10%2C20%2C30", "http://example.org/?d={-list|,|qux}", "http://example.org/?d=10,20,30", "http://example.org/?d={-list|&d=|qux}", "http://example.org/?d=10&d=20&d=30", "http://example.org/{bar}{bar}/{garply}", "http://example.org/fredfred/a%2Fb%2Fc", "http://example.org/{bar}{-prefix|/|fred}", "http://example.org/fred/fred//wilma", "{-neg|:|corge}{-suffix|:|plugh}", ":%E1%B9%A1:%E1%B9%A1:", "../{waldo}/", "../ben%20%26%20jerrys/", "telnet:192.0.2.16{-opt|:80|grault}", "telnet:192.0.2.16:80", ":{1-a_b.c}:", ":200:"}; for (int n = 0; n < templates.length; n = n + 2) { assertEquals(templates[n + 1], Template.expand(templates[n], map)); } } @Test public void test24() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("foo", "fred"); map.put("bar", new String[] {"fee", "fi", "fo", "fum"}); map.put("baz", new String[0]); String[] templates = {"{-suffix|/|foo}", "fred/", "{-suffix|/|bar}", "fee/fi/fo/fum/", "{-suffix|/|baz}", "", "{-suffix|/|qux}", ""}; for (int n = 0; n < templates.length; n = n + 2) { assertEquals(templates[n + 1], Template.expand(templates[n], map)); } } @Test public void test25() throws Exception { Map<String, Object> map = new HashMap<String, Object>(); map.put("foo", "fred"); map.put("bar", new String[] {"fee", "fi", "fo", "fum"}); map.put("baz", new String[0]); String[] templates = {"{-prefix|/|foo}", "/fred", "{-prefix|/|bar}", "/fee/fi/fo/fum", "{-prefix|/|baz}", "", "{-prefix|/|qux}", ""}; for (int n = 0; n < templates.length; n = n + 2) { assertEquals(templates[n + 1], Template.expand(templates[n], map)); } } @URITemplate("http://example.org/{foo}/{bar}{-opt|/|categories}{-list|/|categories}?{-join|&|baz,tag}") public static class MyObject { public String foo = "abc"; public String getBar() { return "xyz"; } public boolean isBaz() { return true; } public String[] getCategories() { return new String[] {"a", "b"}; } public List<String> getTag() { return Arrays.asList(new String[] {"x", "y", "z"}); } } private static void eval(String t, String e, HashMapContext c) { assertEquals(e, Template.expand(t, c)); } }
7,270
0
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test/iri/TestPunycode.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.test.iri; import static org.junit.Assert.fail; import org.apache.abdera.i18n.text.Punycode; public class TestPunycode extends TestBase { enum Test { A("Arabic (Egyption)", "\u0644\u064A\u0647\u0645\u0627\u0628\u062A\u0643\u0644\u0645\u0648\u0634\u0639\u0631\u0628\u064A\u061F", "egbpdaj6bu4bxfgehfvwxn"), B("Chinese (simplified)", "\u4ED6\u4EEC\u4E3A\u4EC0\u4E48\u4E0D\u8BF4\u4E2D\u6587", "ihqwcrb4cv8a8dqg056pqjye"), C( "Chinese (traditional)", "\u4ED6\u5011\u7232\u4EC0\u9EBD\u4E0D\u8AAA\u4E2D\u6587", "ihqwctvzc91f659drss3x8bo0yb"), D( "Czech: Pro<ccaron>prost<ecaron>nemluv<iacute><ccaron>esky", "\u0050\u0072\u006F\u010D\u0070\u0072\u006F\u0073\u0074\u011B\u006E\u0065\u006D\u006C\u0075\u0076\u00ED\u010D\u0065\u0073\u006B\u0079", "Proprostnemluvesky-uyb24dma41a"), E( "Hebrew", "\u05DC\u05DE\u05D4\u05D4\u05DD\u05E4\u05E9\u05D5\u05D8\u05DC\u05D0\u05DE\u05D3\u05D1\u05E8\u05D9\u05DD\u05E2\u05D1\u05E8\u05D9\u05EA", "4dbcagdahymbxekheh6e0a7fei0b"), F( "Hindi (Devanagari)", "\u092F\u0939\u0932\u094B\u0917\u0939\u093F\u0928\u094D\u0926\u0940\u0915\u094D\u092F\u094B\u0902\u0928\u0939\u0940\u0902\u092C\u094B\u0932\u0938\u0915\u0924\u0947\u0939\u0948\u0902", "i1baa7eci9glrd9b2ae1bj0hfcgg6iyaf8o0a1dig0cd"), G( "Japanese (kanji and hiragana)", "\u306A\u305C\u307F\u3093\u306A\u65E5\u672C\u8A9E\u3092\u8A71\u3057\u3066\u304F\u308C\u306A\u3044\u306E\u304B", "n8jok5ay5dzabd5bym9f0cm5685rrjetr6pdxa"), H( "Korean (Hangul syllables)", "\uC138\uACC4\uC758\uBAA8\uB4E0\uC0AC\uB78C\uB4E4\uC774\uD55C\uAD6D\uC5B4\uB97C\uC774\uD574\uD55C\uB2E4\uBA74\uC5BC\uB9C8\uB098\uC88B\uC744\uAE4C", "989aomsvi5e83db1d2a355cv1e0vak1dwrv93d5xbh15a0dt30a5jpsd879ccm6fea98c"), I( "Russian (Cyrillic)", "\u043F\u043E\u0447\u0435\u043C\u0443\u0436\u0435\u043E\u043D\u0438\u043D\u0435\u0433\u043E\u0432\u043E\u0440\u044F\u0442\u043F\u043E\u0440\u0443\u0441\u0441\u043A\u0438", "b1abfaaepdrnnbgefbadotcwatmq2g4l"), J( "Spanish Porqu<eacute>nopuedensimplementehablarenEspa<ntilde>ol", "\u0050\u006F\u0072\u0071\u0075\u00E9\u006E\u006F\u0070\u0075\u0065\u0064\u0065\u006E\u0073\u0069\u006D\u0070\u006C\u0065\u006D\u0065\u006E\u0074\u0065\u0068\u0061\u0062\u006C\u0061\u0072\u0065\u006E\u0045\u0073\u0070\u0061\u00F1\u006F\u006C", "PorqunopuedensimplementehablarenEspaol-fmd56a"), K( "Vietnamese", "\u0054\u1EA1\u0069\u0073\u0061\u006F\u0068\u1ECD\u006B\u0068\u00F4\u006E\u0067\u0074\u0068\u1EC3\u0063\u0068\u1EC9\u006E\u00F3\u0069\u0074\u0069\u1EBF\u006E\u0067\u0056\u0069\u1EC7\u0074", "TisaohkhngthchnitingVit-kjcr8268qyxafd2f1b9g"), L("3<nen>B<gumi><kinpachi><sensei>", "\u0033\u5E74\u0042\u7D44\u91D1\u516B\u5148\u751F", "3B-ww4c5e180e575a65lsy2b"), M( "<amuro><namie>-with-SUPER-MONKEYS", "\u5B89\u5BA4\u5948\u7F8E\u6075\u002D\u0077\u0069\u0074\u0068\u002D\u0053\u0055\u0050\u0045\u0052\u002D\u004D\u004F\u004E\u004B\u0045\u0059\u0053", "-with-SUPER-MONKEYS-pc58ag80a8qai00g7n9n"), N( "Hello-Another-Way-<sorezore><no><basho>", "\u0048\u0065\u006C\u006C\u006F\u002D\u0041\u006E\u006F\u0074\u0068\u0065\u0072\u002D\u0057\u0061\u0079\u002D\u305D\u308C\u305E\u308C\u306E\u5834\u6240", "Hello-Another-Way--fc4qua05auwb3674vfr0b"), O("<hitotsu><yane><no><shita>2", "\u3072\u3068\u3064\u5C4B\u6839\u306E\u4E0B\u0032", "2-u9tlzr9756bt3uc0v"), P( "Maji<de>Koi<suru>5<byou><mae>", "\u004D\u0061\u006A\u0069\u3067\u004B\u006F\u0069\u3059\u308B\u0035\u79D2\u524D", "MajiKoi5-783gue6qz075azm5e"), Q("<pafii>de<runba>", "\u30D1\u30D5\u30A3\u30FC\u0064\u0065\u30EB\u30F3\u30D0", "de-jg4avhby1noc0d"), R("<sono><supiido><de>", "\u305D\u306E\u30B9\u30D4\u30FC\u30C9\u3067", "d9juau41awczczp"), S("-> $1.00 <-", "\u002D\u003E\u0020\u0024\u0031\u002E\u0030\u0030\u0020\u003C\u002D", "-> $1.00 <--"); String name; String in; String out; int rc; Test(String name, String in, String out) { this(name, in, out, 0); } Test(String name, String in, String out, int rc) { this.name = name; this.in = in; this.out = out; this.rc = rc; } } @org.junit.Test public void testPunycode() throws Exception { for (Test test : Test.values()) { String out = Punycode.encode(test.in); String in = Punycode.decode(out); if (!out.equals(test.out)) fail("Failure in test #" + test); if (!in.equals(test.in)) fail("Failure in test #" + test); } } }
7,271
0
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test/iri/TestIRI.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.test.iri; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import java.net.URI; import java.net.URISyntaxException; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.text.Normalizer; import org.junit.Test; public class TestIRI extends TestBase { @Test public void testSimple() throws Exception { IRI iri = new IRI("http://validator.w3.org/check?uri=http%3A%2F%2Fr\u00E9sum\u00E9.example.org"); assertEquals("http://validator.w3.org/check?uri=http%3A%2F%2Fr\u00E9sum\u00E9.example.org", iri.toString()); assertEquals("http://validator.w3.org/check?uri=http%3A%2F%2Fr%C3%A9sum%C3%A9.example.org", iri.toURI() .toString()); } @Test public void testIpv4() throws URISyntaxException{ IRI iri = new IRI("http://127.0.0.1"); assertEquals("http://127.0.0.1", iri.toURI().toString()); } @Test public void testIpv6() throws URISyntaxException{ IRI iri = new IRI("http://[2001:0db8:85a3:08d3:1319:8a2e:0370:7344]"); assertEquals("http://[2001:0db8:85a3:08d3:1319:8a2e:0370:7344]", iri.toURI().toString()); } @Test public void testUnderscore() throws URISyntaxException{ IRI iri = new IRI("http://its_gbsc.cn.ibm.com/"); assertEquals("http://its_gbsc.cn.ibm.com/", iri.toURI().toString()); } @Test(expected=URISyntaxException.class) public void testIpv6Invalid() throws URISyntaxException{ IRI iri = new IRI("http://[2001:0db8:85a3:08d3:1319:8a2e:0370:734o]"); iri.toURI().toString(); } @Test public void testFile() throws Exception { IRI iri = new IRI("file:///tmp/test/foo"); assertEquals("file:///tmp/test/foo", iri.toURI().toString()); } @Test public void testSimple2() throws Exception { IRI iri = new IRI("http://www.example.org/red%09ros\u00E9#red"); assertEquals("http://www.example.org/red%09ros%C3%A9#red", iri.toURI().toString()); } @Test public void testNotSoSimple() throws Exception { IRI iri = new IRI("http://example.com/\uD800\uDF00\uD800\uDF01\uD800\uDF02"); assertEquals("http://example.com/%F0%90%8C%80%F0%90%8C%81%F0%90%8C%82", iri.toURI().toString()); } @Test public void testIRItoURI() throws Exception { IRI iri = new IRI("http://\u7D0D\u8C46.example.org/%E2%80%AE"); URI uri = iri.toURI(); assertEquals("http://xn--99zt52a.example.org/%E2%80%AE", uri.toString()); } @Test public void testComparison() throws Exception { IRI iri1 = new IRI("http://www.example.org/"); IRI iri2 = new IRI("http://www.example.org/.."); IRI iri3 = new IRI("http://www.Example.org:80"); assertFalse(iri1.equals(iri2)); // false assertFalse(iri1.equals(iri3)); // false assertFalse(iri2.equals(iri1)); // false assertFalse(iri2.equals(iri3)); // false assertFalse(iri3.equals(iri1)); // false assertFalse(iri3.equals(iri2)); // false assertTrue(iri1.normalize().equals(iri2.normalize())); assertTrue(iri1.normalize().equals(iri3.normalize())); assertTrue(iri2.normalize().equals(iri1.normalize())); assertTrue(iri2.normalize().equals(iri3.normalize())); assertTrue(iri3.normalize().equals(iri1.normalize())); assertTrue(iri3.normalize().equals(iri2.normalize())); } @Test public void testUCN() throws Exception { IRI iri1 = new IRI("http://www.example.org/r\u00E9sum\u00E9.html"); IRI iri2 = new IRI("http://www.example.org/re\u0301sume\u0301.html", Normalizer.Form.C); assertEquals(iri2, iri1); } @Test public void testPercent() throws Exception { IRI iri1 = new IRI("http://example.org/%7e%2Fuser?%2f"); IRI iri2 = new IRI("http://example.org/%7E%2fuser?/"); assertTrue(iri1.normalize().equals(iri2.normalize())); } @Test public void testIDN() throws Exception { IRI iri1 = new IRI("http://r\u00E9sum\u00E9.example.org"); assertEquals("xn--rsum-bpad.example.org", iri1.getASCIIHost()); } @Test public void testRelative() throws Exception { IRI base = new IRI("http://example.org/foo/"); assertEquals("http://example.org/", base.resolve("/").toString()); assertEquals("http://example.org/test", base.resolve("/test").toString()); assertEquals("http://example.org/foo/test", base.resolve("test").toString()); assertEquals("http://example.org/test", base.resolve("../test").toString()); assertEquals("http://example.org/foo/test", base.resolve("./test").toString()); assertEquals("http://example.org/foo/", base.resolve("test/test/../../").toString()); assertEquals("http://example.org/foo/?test", base.resolve("?test").toString()); assertEquals("http://example.org/foo/#test", base.resolve("#test").toString()); assertEquals("http://example.org/foo/", base.resolve(".").toString()); } /** * Try a variety of URI schemes. If any problematic schemes pop up, we should add a test for 'em here */ @Test public void testSchemes() throws Exception { IRI iri = new IRI("http://a:b@c.org:80/d/e?f#g"); assertEquals("http", iri.getScheme()); assertEquals("a:b", iri.getUserInfo()); assertEquals("c.org", iri.getHost()); assertEquals(80, iri.getPort()); assertEquals("/d/e", iri.getPath()); assertEquals("f", iri.getQuery()); assertEquals("g", iri.getFragment()); iri = new IRI("https://a:b@c.org:80/d/e?f#g"); assertEquals("https", iri.getScheme()); assertEquals("a:b", iri.getUserInfo()); assertEquals("c.org", iri.getHost()); assertEquals(80, iri.getPort()); assertEquals("/d/e", iri.getPath()); assertEquals("f", iri.getQuery()); assertEquals("g", iri.getFragment()); iri = new IRI("ftp://a:b@c.org:80/d/e?f#g"); assertEquals("ftp", iri.getScheme()); assertEquals("a:b", iri.getUserInfo()); assertEquals("c.org", iri.getHost()); assertEquals(80, iri.getPort()); assertEquals("/d/e", iri.getPath()); assertEquals("f", iri.getQuery()); assertEquals("g", iri.getFragment()); iri = new IRI("mailto:joe@example.org?subject=foo"); assertEquals("mailto", iri.getScheme()); assertEquals(null, iri.getUserInfo()); assertEquals(null, iri.getHost()); assertEquals(-1, iri.getPort()); assertEquals("joe@example.org", iri.getPath()); assertEquals("subject=foo", iri.getQuery()); assertEquals(null, iri.getFragment()); iri = new IRI("tag:example.org,2006:foo"); assertEquals("tag", iri.getScheme()); assertEquals(null, iri.getUserInfo()); assertEquals(null, iri.getHost()); assertEquals(-1, iri.getPort()); assertEquals("example.org,2006:foo", iri.getPath()); assertEquals(null, iri.getQuery()); assertEquals(null, iri.getFragment()); iri = new IRI("urn:lsid:ibm.com:example:82437234964354895798234d"); assertEquals("urn", iri.getScheme()); assertEquals(null, iri.getUserInfo()); assertEquals(null, iri.getHost()); assertEquals(-1, iri.getPort()); assertEquals("lsid:ibm.com:example:82437234964354895798234d", iri.getPath()); assertEquals(null, iri.getQuery()); assertEquals(null, iri.getFragment()); iri = new IRI("data:image/gif;base64,R0lGODdhMAAwAPAAAAAAAP"); assertEquals("data", iri.getScheme()); assertEquals(null, iri.getUserInfo()); assertEquals(null, iri.getHost()); assertEquals(-1, iri.getPort()); assertEquals("image/gif;base64,R0lGODdhMAAwAPAAAAAAAP", iri.getPath()); assertEquals(null, iri.getQuery()); assertEquals(null, iri.getFragment()); } }
7,272
0
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test/iri/TestNameprep.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.test.iri; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import org.apache.abdera.i18n.text.CharUtils; import org.apache.abdera.i18n.text.Nameprep; public class TestNameprep extends TestBase { enum Test { A("Map to nothing", string('f', 'o', 'o', 0xC2, 0xAD, 0xCD, 0x8F, 0xE1, 0xA0, 0x86, 0xE1, 0xA0, 0x8B, 'b', 'a', 'r', 0xE2, 0x80, 0x8B, 0xE2, 0x81, 0xA0, 'b', 'a', 'z', 0xEF, 0xB8, 0x80, 0xEF, 0xB8, 0x88, 0xEF, 0xB8, 0x8F, 0xEF, 0xBB, 0xBF), "foobarbaz"), B("Case folding ASCII U+0043 U+0041 U+0046 U+0045", "CAFE", "cafe"), C("Case folding 8bit U+00DF (german sharp s)", string(0xC3, 0x9F), "ss"), D( "Case folding U+0130 (turkish capital I with dot)", string(0xC4, 0xB0), string('i', 0xCC, 0x87)), E( "Case folding multibyte U+0143 U+037A", string(0xC5, 0x83, 0xCD, 0xBA), string(0xC5, 0x84, 0x20, 0xCE, 0xB9)), F("Case folding U+2121 U+33C6 U+1D7BB", string(0xE2, 0x84, 0xA1, 0xE3, 0x8F, 0x86, 0xF0, 0x9D, 0x9E, 0xBB), string('t', 'e', 'l', 'c', 0xE2, 0x88, 0x95, 'k', 'g', 0xCF, 0x83)), G( "Normalization of U+006a U+030c U+00A0 U+00AA", string(0x6A, 0xCC, 0x8C, 0xC2, 0xA0, 0xC2, 0xAA), string(0xC7, 0xB0, 'a')), H("Case folding U+1FB7 and normalization", string(0xE1, 0xBE, 0xB7), string(0xE1, 0xBE, 0xB6, 0xCE, 0xB9)), I( "Self-reverting case folding U+01F0 and normalization", string(0xC7, 0xB0), string(0xC7, 0xB0)), J( "Self-reverting case folding U+0390 and normalization", string(0xCE, 0x90), string(0xCE, 0x90)), K( "Self-reverting case folding U+03B0 and normalization", string(0xCE, 0xB0), string(0xCE, 0xB0)), L( "Self-reverting case folding U+1E96 and normalization", string(0xE1, 0xBA, 0x96), string(0xE1, 0xBA, 0x96)), M( "Self-reverting case folding U+1F56 and normalization", string(0xE1, 0xBD, 0x96), string(0xE1, 0xBD, 0x96)), N( "ASCII space character U+0020", "\u0020", "\u0020"), O("Non-ASCII 8bit space character U+00A0", "\u00A0", ""), P("Non-ASCII multibyte space character U+1680", "\u1680", null, -1), Q( "Non-ASCII multibyte space character U+2000", "\u2000", "\u0020", -1), R("Zero Width Space U+200b", "\u200B", ""), S("Non-ASCII multibyte space character U+3000", "\u3000", "\u0020", -1), T( "ASCII control characters U+0010 U+007F", "\u0010\u007F", "\u0010\u007F"), U( "Non-ASCII 8bit control character U+0085", "\u0085", null, -1), V( "Non-ASCII multibyte control character U+180E", "\u180E", null, -1), W("Zero Width No-Break Space U+FEFF", "\uFEFF", ""), X("Non-ASCII control character U+1D175", new String(new char[] {CharUtils.getHighSurrogate(0x1D175), CharUtils.getLowSurrogate(0x1D175)}), null, -1), Y( "Plane 0 private use character U+F123", "\uF123", null, -1), Z("Plane 15 private use character U+F1234", string(0xF3, 0xB1, 0x88, 0xB4), null, -1), AA("Plane 16 private use character U+10F234", string(0xF4, 0x8F, 0x88, 0xB4), null, -1), AB("Non-character code point U+8FFFE", "\ud9ff\udffe", null, -1), AC( "Non-character code point U+10FFFF", string(0xF4, 0x8F, 0x8F, 0x8F), null, -1), AD("Surrogate code U+DF42", string(0xED, 0xBD, 0x82), null, -1), AE("Non-plain text character U+FFFD", string(0xEF, 0xBF, 0xBD), null, -1), AF("Ideographic description character U+2FF5", string(0xE2, 0xBF, 0xB5), null, -1), AG( "Display property character U+0341", string(0xCD, 0x81), string(0xCC, 0x81), -1), AH( "Left-to-right mark U+200E", string(0xE2, 0x80, 0x8E), null, -1), AI("Deprecated U+202A", string(0xE2, 0x80, 0xAA), null, -1), AJ("Language tagging character U+E0001", string(0xF3, 0xA0, 0x80, 0x81), null, -1), AK( "Language tagging character U+E0042", string(0xF3, 0xA0, 0x81, 0x82), null, -1), AL( "Bidi: RandALCat character U+05BE and LCat characters", string('f', 'o', 'o', 0xD6, 0xBE), null, -1), AM( "Bidi: RandALCat character U+FD50 and LCat characters", string('f', 'o', 'o', 0xEF, 0xB5, 0x90), null, -1), AN( "Bidi: RandALCat character U+FB38 and LCat characters", string('f', 'o', 'o', 0xEF, 0xB9, 0xB6), null, -1), AO( "Bidi: RandALCat without trailing RandALCat U+0627 U+0031", string(0xD8, 0xA7, 0x31), null, -1), AP( "Bidi: RandALCat character U+0627 U+0031 U+0628", string(0xD8, 0xA7, 0x31, 0xD8, 0xA8), string(0xD8, 0xA7, 0x31, 0xD8, 0xA8)), // AQ("Unassigned code point U+E0002",string(0xF3,0xA0,0x80,0x82),null,true,-1), // AR("Larger test (shrinking)", // // {"Larger test (shrinking)","X\xC2\xAD\xC3\x9F\xC4\xB0\xE2\x84\xA1\x6a\xcc\x8c\xc2\xa0\xc2""\xaa\xce\xb0\xe2\x80\x80", // "xssi\xcc\x87" "tel\xc7\xb0 a\xce\xb0 ","Nameprep"}, // string('X',0xC2,0xAD,0xC3,0x9F,0xC4,0xB0,0xE2,0x84,0xA1,0x6a,0xc,'c',0x8c,0xc2,0xa0,0xc2), // string('x','s','s','i',0xcc,0x87,'t','e','l',0xc7,0xb0,'a',0xce,0xb0), false, 0), AS("Larger test (expanding)", string('X', 0xC3, 0x9F, 0xe3, 0x8c, 0x96, 0xC4, 0xB0, 0xE2, 0x84, 0xA1, 0xE2, 0x92, 0x9F, 0xE3, 0x8c, 0x80), string('x', 's', 's', 0xE3, 0x82, 0xAD, 0xE3, 0x83, 0xAD, 0xE3, 0x83, 0xA1, 0xE3, 0x83, 0xBC, 0xE3, 0x83, 0x88, 0xE3, 0x83, 0xAB, 'i', 0xCC, 0x87, 't', 'e', 'l', 0x28, 'd', 0x29, 0xE3, 0x82, 0xA2, 0xE3, 0x83, 0x91, 0xE3, 0x83, 0xBC, 0xE3, 0x83, 0x88)), AT("Case map + normalization", string(0xC2, 0xB5), string(0xCE, 0xBC)), AU("NFKC test", string(0xC2, 0xAA), string(0x61)), AV( "nameprep, exposed a bug in libstringprep 0.0.5", string(0xC2, 0xAA, 0x0A), string(0x61, 0x0A)), // AW("unassigned code point U+0221", "\u0221", "\u0221", true, 0), AX("unassigned code point U+0221", "\u0221", "\u0221", -1), // AY("Unassigned code point U+0236", "\u0236", "\u0236", true, 0), AZ("unassigned code point U+0236", "\u0236", "\u0236", -1), BA( "bidi both RandALCat and LCat U+0627 U+00AA U+0628", string(0xD8, 0xA7, 0xC2, 0xAA, 0xD8, 0xA8), null, -1); String comment; String in; String out; int rc; Test(String comment, String in, String out) { this.comment = comment; this.in = in; this.out = out; } Test(String comment, String in, String out, int rc) { this.comment = comment; this.in = in; this.out = out; this.rc = rc; } } @org.junit.Test public void testNameprep() throws Exception { for (Test test : Test.values()) { try { String out = Nameprep.prep(test.in); assertEquals(out, test.out); } catch (Exception e) { if (test.rc != -1) fail("Failure in Test #" + test + " not expected"); } } } }
7,273
0
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test/iri/TestLang.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.test.iri; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.Locale; import org.apache.abdera.i18n.rfc4646.Lang; import org.apache.abdera.i18n.rfc4646.Range; import org.junit.Test; @SuppressWarnings("deprecation") public class TestLang extends TestBase { @Test public void testLang() throws Exception { org.apache.abdera.i18n.lang.Lang lang = new org.apache.abdera.i18n.lang.Lang("en-US-ca"); Locale testLocale = new Locale("en", "US", "ca"); assertEquals("en", lang.getPrimary()); assertEquals("US", lang.getSubtag(0)); assertEquals("ca", lang.getSubtag(1)); assertEquals(testLocale, lang.getLocale()); assertEquals(testLocale.toString(), lang.getLocale().toString()); assertEquals(testLocale.getDisplayCountry(), lang.getLocale().getDisplayCountry()); assertEquals(testLocale.getDisplayLanguage(), lang.getLocale().getDisplayLanguage()); assertEquals(testLocale.getDisplayVariant(), lang.getLocale().getDisplayVariant()); assertTrue(lang.matches("*")); assertTrue(lang.matches("en")); assertTrue(lang.matches("EN")); assertTrue(lang.matches("en-US")); assertTrue(lang.matches("en-us")); assertTrue(lang.matches("en-US-ca")); assertTrue(lang.matches("en-us-ca")); assertFalse(lang.matches("en-US-ca-bob")); assertFalse(lang.matches("en-US-fr")); Exception e = null; try { lang = new org.apache.abdera.i18n.lang.Lang("en_US"); } catch (org.apache.abdera.i18n.lang.InvalidLangTagSyntax ex) { e = ex; } assertNotNull(e); } @Test public void test4646Lang() throws Exception { Lang lang = new Lang("en-Latn-US-valencia"); assertEquals("en", lang.getLanguage().toString()); assertEquals("US", lang.getRegion().toString()); assertEquals("Latn", lang.getScript().toString()); assertEquals("valencia", lang.getVariant().toString()); assertNull(lang.getExtLang()); assertNull(lang.getExtension()); assertNull(lang.getPrivateUse()); assertTrue(lang.isValid()); Locale locale = lang.getLocale(); assertEquals("US", locale.getCountry()); assertEquals("en", locale.getLanguage()); assertEquals("valencia", locale.getVariant()); } @Test public void test4647Matching() throws Exception { Lang lang = new Lang("en-Latn-US-valencia"); Range range1 = new Range("*", true); Range range2 = new Range("en-*", true); Range range3 = new Range("en-Latn-*", true); Range range4 = new Range("en-US-*", true); Range range5 = new Range("en-*-US-*", true); Range range6 = new Range("*-US", true); Range range7 = new Range("*-valencia", true); Range range8 = new Range("*-FR", true); assertTrue(range1.matches(lang, true)); assertTrue(range2.matches(lang, true)); assertTrue(range3.matches(lang, true)); assertTrue(range4.matches(lang, true)); assertTrue(range5.matches(lang, true)); assertTrue(range6.matches(lang, true)); assertTrue(range7.matches(lang, true)); assertFalse(range8.matches(lang, true)); } }
7,274
0
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test/iri/TestBase.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.test.iri; public abstract class TestBase { protected static String string(int... chars) { try { byte[] b = new byte[chars.length]; for (int n = 0; n < chars.length; n++) b[n] = (byte)chars[n]; return new String(b, "utf-8"); } catch (Exception e) { e.printStackTrace(); } return null; } }
7,275
0
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test/iri/TestIO.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.test.iri; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertFalse; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.StringReader; import org.apache.abdera.i18n.text.Filter; import org.apache.abdera.i18n.text.io.CharsetSniffingInputStream; import org.apache.abdera.i18n.text.io.DynamicPushbackInputStream; import org.apache.abdera.i18n.text.io.FilteredCharReader; import org.apache.abdera.i18n.text.io.PeekAheadInputStream; import org.apache.abdera.i18n.text.io.PipeChannel; import org.apache.abdera.i18n.text.io.RewindableInputStream; import org.junit.Test; public class TestIO extends TestBase { @Test public void testCharsetDetection() throws Exception { byte[] utf32be = {0x00, 0x00, 0xFFFFFFFE, 0xFFFFFFFF, 0x01, 0x02, 0x03}; byte[] utf32le = {0xFFFFFFFF, 0xFFFFFFFE, 0x00, 0x00, 0x01, 0x02, 0x03}; byte[] utf16be = {0xFFFFFFFE, 0xFFFFFFFF, 0x01, 0x02, 0x03}; byte[] utf16le = {0xFFFFFFFF, 0xFFFFFFFE, 0x01, 0x02, 0x03}; byte[] utf8 = {0xFFFFFFEF, 0xFFFFFFBB, 0xFFFFFFBF, 0x01, 0x02, 0x03}; byte[] nobom_utf32be = {0x00, 0x00, 0x00, 0x3C, 0x01, 0x02, 0x03}; byte[] nobom_utf32le = {0x3C, 0x00, 0x00, 0x00, 0x01, 0x02, 0x03}; byte[] nobom_utf16be = {0x00, 0x3C, 0x00, 0x3F, 0x01, 0x02, 0x03}; byte[] nobom_utf16le = {0x3C, 0x00, 0x3F, 0x00, 0x01, 0x02, 0x03}; ByteArrayInputStream in = new ByteArrayInputStream(utf32be); CharsetSniffingInputStream csis = new CharsetSniffingInputStream(in); assertEquals("UTF-32", csis.getEncoding()); assertTrue(csis.isBomSet()); in = new ByteArrayInputStream(utf32le); csis = new CharsetSniffingInputStream(in); assertEquals("UTF-32", csis.getEncoding()); assertTrue(csis.isBomSet()); in = new ByteArrayInputStream(utf16be); csis = new CharsetSniffingInputStream(in); assertEquals("UTF-16", csis.getEncoding()); assertTrue(csis.isBomSet()); in = new ByteArrayInputStream(utf16le); csis = new CharsetSniffingInputStream(in); assertEquals("UTF-16", csis.getEncoding()); assertTrue(csis.isBomSet()); in = new ByteArrayInputStream(utf8); csis = new CharsetSniffingInputStream(in); assertEquals("UTF-8", csis.getEncoding()); assertTrue(csis.isBomSet()); in = new ByteArrayInputStream(nobom_utf32be); csis = new CharsetSniffingInputStream(in); assertEquals("UTF-32be", csis.getEncoding()); assertFalse(csis.isBomSet()); in = new ByteArrayInputStream(nobom_utf32le); csis = new CharsetSniffingInputStream(in); assertEquals("UTF-32le", csis.getEncoding()); assertFalse(csis.isBomSet()); in = new ByteArrayInputStream(nobom_utf16be); csis = new CharsetSniffingInputStream(in); assertEquals("UTF-16be", csis.getEncoding()); assertFalse(csis.isBomSet()); in = new ByteArrayInputStream(nobom_utf16le); csis = new CharsetSniffingInputStream(in); assertEquals("UTF-16le", csis.getEncoding()); assertFalse(csis.isBomSet()); } @Test public void testDynamicPushbackInputStream() throws Exception { ByteArrayInputStream in = new ByteArrayInputStream(new byte[] {0x01, 0x02, 0x03, 0x04}); DynamicPushbackInputStream dpis = new DynamicPushbackInputStream(in); int r = dpis.read(); dpis.unread(r); int e = dpis.read(); assertEquals(r, e); dpis.unread(e); dpis.clear(); r = dpis.read(); assertFalse(e == r); } @Test public void testFilteredCharReader() throws Exception { String string = "abcdefg"; FilteredCharReader fcr = new FilteredCharReader(new StringReader(string), new Filter() { public boolean accept(int c) { return c != 'c' && c != 'd' && c != 'e'; } }); char[] buf = new char[7]; int r = fcr.read(buf); assertEquals(4, r); assertEquals("abfg", new String(buf, 0, r)); } @Test public void testPeekAheadInputStream() throws Exception { ByteArrayInputStream in = new ByteArrayInputStream(new byte[] {0x01, 0x02, 0x03, 0x04}); PeekAheadInputStream pais = new PeekAheadInputStream(in); byte[] peek = new byte[2]; byte[] read = new byte[2]; pais.peek(peek); pais.read(read); assertEquals(read[0], peek[0]); assertEquals(read[1], peek[1]); byte[] newread = new byte[2]; assertFalse(read[0] == newread[0]); assertFalse(read[1] == newread[1]); } @Test public void testRewindableInputStream() throws Exception { ByteArrayInputStream in = new ByteArrayInputStream(new byte[] {0x01, 0x02, 0x03, 0x04}); RewindableInputStream ris = new RewindableInputStream(in); byte[] buf1 = new byte[4]; byte[] buf2 = new byte[4]; ris.read(buf1); ris.rewind(); ris.read(buf2); for (int n = 0; n < 4; n++) assertEquals(buf2[n], buf1[n]); } @Test public void testPipeChannel() throws Exception { PipeChannel pc = new PipeChannel(); assertTrue(pc.isWritable()); assertFalse(pc.isReadable()); OutputStream out = pc.getOutputStream(); out.write(0x01); out.write(0x02); out.write(0x03); out.write(0x04); out.close(); assertFalse(pc.isWritable()); assertTrue(pc.isReadable()); InputStream in = pc.getInputStream(); byte[] buf = new byte[4]; in.read(buf); assertEquals(0x1, buf[0]); assertEquals(0x2, buf[1]); assertEquals(0x3, buf[2]); assertEquals(0x4, buf[3]); in.close(); assertTrue(pc.isWritable()); assertFalse(pc.isReadable()); } }
7,276
0
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test/iri/TestIDNA.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.test.iri; import static org.junit.Assert.assertTrue; import org.apache.abdera.i18n.iri.IDNA; import org.junit.Test; public class TestIDNA extends TestBase { @Test public void testPunycode() throws Exception { String o = "\u00e1\u00e9\u00ed\u00f1\u00f3\u00bd\u00a9"; String i = "12-uda5tmbya2aq8623e"; String out = IDNA.toASCII(o); String in = IDNA.toUnicode(i); assertTrue(out.equalsIgnoreCase("xn--" + i)); assertTrue(in.equalsIgnoreCase(i)); } }
7,277
0
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test/iri/TestNFKC.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.test.iri; import static org.junit.Assert.assertEquals; import org.apache.abdera.i18n.text.Normalizer; import org.junit.Test; public class TestNFKC extends TestBase { @Test public void testNFKC() throws Exception { // "\xC2\xB5", "\xCE\xBC" String s1 = Normalizer.normalize(string(0xC2, 0xB5)).toString(); String s2 = string(0xCE, 0xBC); assertEquals(s2, s1); // "\xC2\xAA", "\x61" s1 = Normalizer.normalize(string(0xC2, 0xAA)).toString(); s2 = string(0x61); assertEquals(s2, s1); } }
7,278
0
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/test/iri/TestText.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.test.iri; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.apache.abdera.i18n.text.CharUtils; import org.apache.abdera.i18n.text.Codepoint; import org.apache.abdera.i18n.text.CodepointIterator; import org.apache.abdera.i18n.text.Normalizer; import org.apache.abdera.i18n.text.Sanitizer; import org.junit.Test; public class TestText extends TestBase { @Test public void testCodepoints() throws Exception { StringBuilder buf = new StringBuilder(); CharUtils.append(buf, 0x10000); assertEquals(2, buf.length()); assertEquals(CharUtils.getHighSurrogate(0x10000), buf.charAt(0)); assertEquals(CharUtils.getLowSurrogate(0x10000), buf.charAt(1)); assertTrue(CharUtils.isSurrogatePair(buf.charAt(0), buf.charAt(1))); Codepoint codepoint = CharUtils.codepointAt(buf, 0); assertEquals(0x10000, codepoint.getValue()); assertEquals(2, codepoint.getCharCount()); assertTrue(codepoint.isSupplementary()); CharUtils.insert(buf, 0, codepoint.next()); assertEquals(4, buf.length()); assertEquals(CharUtils.codepointAt(buf, 0), codepoint.next()); } @Test public void testSetChecks() throws Exception { assertTrue(CharUtils.inRange(new char[] {'a', 'b', 'c'}, 'a', 'c')); assertFalse(CharUtils.inRange(new char[] {'a', 'b', 'c'}, 'm', 'z')); assertTrue(CharUtils.inRange(new char[] {'a', 'b', 'c'}, (int)'a', (int)'c')); assertFalse(CharUtils.inRange(new char[] {'a', 'b', 'c'}, (int)'m', (int)'z')); assertTrue(CharUtils.isBidi(CharUtils.LRE)); assertTrue(CharUtils.isBidi(CharUtils.LRM)); assertTrue(CharUtils.isBidi(CharUtils.LRO)); assertTrue(CharUtils.isBidi(CharUtils.PDF)); assertTrue(CharUtils.isBidi(CharUtils.RLE)); assertTrue(CharUtils.isBidi(CharUtils.RLM)); assertTrue(CharUtils.isBidi(CharUtils.RLO)); } @Test public void testBidi() throws Exception { String s = "abc"; String lre = CharUtils.wrapBidi(s, CharUtils.LRE); String lro = CharUtils.wrapBidi(s, CharUtils.LRO); String lrm = CharUtils.wrapBidi(s, CharUtils.LRM); String rle = CharUtils.wrapBidi(s, CharUtils.RLE); String rlo = CharUtils.wrapBidi(s, CharUtils.RLO); String rlm = CharUtils.wrapBidi(s, CharUtils.RLM); assertEquals(CharUtils.LRE, lre.charAt(0)); assertEquals(CharUtils.PDF, lre.charAt(lre.length() - 1)); assertEquals(CharUtils.LRO, lro.charAt(0)); assertEquals(CharUtils.PDF, lro.charAt(lro.length() - 1)); assertEquals(CharUtils.LRM, lrm.charAt(0)); assertEquals(CharUtils.LRM, lrm.charAt(lrm.length() - 1)); assertEquals(CharUtils.RLE, rle.charAt(0)); assertEquals(CharUtils.PDF, rle.charAt(rle.length() - 1)); assertEquals(CharUtils.RLO, rlo.charAt(0)); assertEquals(CharUtils.PDF, rlo.charAt(rlo.length() - 1)); assertEquals(CharUtils.RLM, rlm.charAt(0)); assertEquals(CharUtils.RLM, rlm.charAt(rlm.length() - 1)); assertEquals(s, CharUtils.stripBidi(lre)); assertEquals(s, CharUtils.stripBidi(lro)); assertEquals(s, CharUtils.stripBidi(lrm)); assertEquals(s, CharUtils.stripBidi(rle)); assertEquals(s, CharUtils.stripBidi(rlo)); assertEquals(s, CharUtils.stripBidi(rlm)); s = new String(new char[] {'a', CharUtils.LRM, 'b', CharUtils.LRM, 'c'}); assertEquals(5, s.length()); s = CharUtils.stripBidiInternal(s); assertEquals(3, s.length()); assertEquals("abc", s); } @Test public void testVerify() throws Exception { CharUtils.verify(new char[] {'a', 'b', 'c', 'd'}, CharUtils.Profile.ALPHA); CharUtils.verifyNot(new char[] {'1', '2', '3', '4', '-'}, CharUtils.Profile.ALPHA); } @Test public void testCodepointIterator() throws Exception { String s = "abcdefghijklmnop"; CodepointIterator ci = CodepointIterator.forCharSequence(s); while (ci.hasNext()) ci.next(); } @Test public void testSanitizer() throws Exception { String s = "\u0074\u0068\u00ed\u0073\u0020\u00ed\u0073\u0020\u00e0\u0020\u0074\u00e9\u0073\u0074"; String t = Sanitizer.sanitize(s); assertEquals("th%C3%ADs_%C3%ADs_%C3%A0_t%C3%A9st", t); t = Sanitizer.sanitize(s, "", true, Normalizer.Form.D); assertEquals("this_is_a_test", t); } }
7,279
0
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/text
Create_ds/abdera/dependencies/i18n/src/test/java/org/apache/abdera/i18n/text/io/CompressionUtilTest.java
package org.apache.abdera.i18n.text.io; import static org.junit.Assert.assertEquals; import java.util.Locale; import org.apache.abdera.i18n.text.io.CompressionUtil.CompressionCodec; import org.junit.Test; public class CompressionUtilTest { @Test public void getCodecWithTurkishLocale (){ Locale.setDefault(new Locale("tr", "", "")); CompressionCodec codec = CompressionUtil.getCodec("gzip"); assertEquals("GZIP", codec.toString()); } @Test public void compressionCodecWithTurkishLocale (){ CompressionCodec codec = CompressionCodec.value("gzip"); assertEquals("GZIP", codec.toString()); } }
7,280
0
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/rfc4646/SubtagSet.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.rfc4646; import java.io.Serializable; import java.util.Arrays; import java.util.Iterator; import java.util.LinkedList; import java.util.List; abstract class SubtagSet implements Serializable, Cloneable, Iterable<Subtag>, Comparable<SubtagSet> { protected final Subtag primary; protected SubtagSet(Subtag primary) { this.primary = primary; } public String toString() { StringBuilder buf = new StringBuilder(); for (Subtag subtag : this) { if (buf.length() > 0) buf.append('-'); buf.append(subtag.getName()); } return buf.toString(); } public Iterator<Subtag> iterator() { return new SubtagIterator(primary); } public boolean contains(Subtag subtag) { for (Subtag tag : this) if (tag.equals(subtag)) return true; return false; } public boolean contains(String tag) { return contains(tag, Subtag.Type.SIMPLE); } public boolean contains(String tag, Subtag.Type type) { return contains(new Subtag(type, tag)); } public int length() { return toString().length(); } public boolean isValid() { for (Subtag subtag : this) if (!subtag.isValid()) return false; return true; } @SuppressWarnings("unused") public int count() { int n = 0; for (Subtag tag : this) n++; return n; } public Subtag get(int index) { if (index < 0 || index > count()) throw new IndexOutOfBoundsException(); Subtag tag = primary; for (int n = 1; n <= index; n++) tag = tag.getNext(); return tag; } static class SubtagIterator implements Iterator<Subtag> { private Subtag current; SubtagIterator(Subtag current) { this.current = current; } public boolean hasNext() { return current != null; } public Subtag next() { Subtag tag = current; current = tag.getNext(); return tag; } public void remove() { throw new UnsupportedOperationException(); } } public int hashCode() { final int prime = 31; int result = 1; for (Subtag tag : this) result = prime * result + tag.hashCode(); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Lang other = (Lang)obj; return hashCode() == other.hashCode(); } public Subtag[] toArray() { List<Subtag> tags = new LinkedList<Subtag>(); for (Subtag tag : this) tags.add(tag); return tags.toArray(new Subtag[tags.size()]); } public List<Subtag> asList() { return Arrays.asList(toArray()); } public int compareTo(SubtagSet o) { Iterator<Subtag> i = iterator(); Iterator<Subtag> e = o.iterator(); for (; i.hasNext() && e.hasNext();) { Subtag inext = i.next(); Subtag enext = e.next(); int c = inext.compareTo(enext); if (c != 0) return c; } if (e.hasNext() && !i.hasNext()) return -1; if (i.hasNext() && !e.hasNext()) return 1; return 0; } }
7,281
0
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/rfc4646/Lang.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.rfc4646; import java.util.Collections; import java.util.Comparator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.abdera.i18n.rfc4646.Subtag.Type; /** * Implementation of RFC 4646 Language Tags */ public final class Lang extends SubtagSet { private static final long serialVersionUID = -7095560018906537331L; private final Locale locale; /** * Create a Lang object using the default locale */ public Lang() { this(init(Locale.getDefault())); } /** * Create a Lang object using the specified locale */ public Lang(Locale locale) { this(init(locale)); } private static Subtag init(Locale locale) { try { return parse(locale.toString()).primary; } catch (Exception e) { Subtag c = null, primary = new Subtag(Type.PRIMARY, locale.getLanguage()); String country = locale.getCountry(); String variant = locale.getVariant(); if (country != null) c = new Subtag(Type.REGION, country, primary); if (variant != null) new Subtag(Type.VARIANT, variant, c); return primary; } } /** * Create a lang object */ public Lang(String lang) { this(parse(lang).primary); } Lang(Subtag primary) { super(primary); this.locale = initLocale(); } private Locale initLocale() { Subtag primary = getLanguage(); Subtag region = getRegion(); Subtag variant = getVariant(); if (variant != null && region != null) return new Locale(primary.toString(), region.toString(), variant.toString()); else if (region != null) return new Locale(primary.toString(), region.toString()); else return new Locale(primary.toString()); } /** * Get the Language subtag */ public Subtag getLanguage() { return primary; } /** * Get a Locale object derived from this language tag */ public Locale getLocale() { return locale; } /** * Get the Extlang tag. If there are multiple extlang tags, this will return the first one. The rest can be * retrieved by following Subtag.getNext() */ public Subtag getExtLang() { for (Subtag subtag : this) { switch (subtag.getType()) { case PRIMARY: break; case EXTLANG: return subtag; default: return null; } } return null; } /** * Get the Script subtag */ public Subtag getScript() { for (Subtag subtag : this) { switch (subtag.getType()) { case PRIMARY: case EXTLANG: break; case SCRIPT: return subtag; default: return null; } } return null; } /** * Get the Region subtag */ public Subtag getRegion() { for (Subtag subtag : this) { switch (subtag.getType()) { case PRIMARY: case EXTLANG: case SCRIPT: break; case REGION: return subtag; default: return null; } } return null; } /** * Get the Variant subtag */ public Subtag getVariant() { for (Subtag subtag : this) { switch (subtag.getType()) { case PRIMARY: case EXTLANG: case SCRIPT: case REGION: break; case VARIANT: return subtag; default: return null; } } return null; } /** * Get the beginning of the extension section. This will return the first prefix subtag of the first set of * extension subtags. */ public Subtag getExtension() { for (Subtag subtag : this) { switch (subtag.getType()) { case PRIMARY: case EXTLANG: case SCRIPT: case REGION: case VARIANT: break; case EXTENSION: return subtag.getPrevious(); default: return null; } } return null; } /** * Get the beginning of the private-use section. This will return the x prefix subtag */ public Subtag getPrivateUse() { for (Subtag subtag : this) { switch (subtag.getType()) { case PRIMARY: case EXTLANG: case SCRIPT: case VARIANT: case REGION: case EXTENSION: break; case PRIVATEUSE: return subtag.getPrevious(); default: return null; } } return null; } /** * Get this Lang as a Language-Range for use with matching */ public Range asRange() { return new Range(toString()); } /** * Clone this Language tag */ public Lang clone() { return new Lang(primary.clone()); } /** * Produce a canonicalized copy of this lang tag */ public Lang canonicalize() { Subtag primary = null, current = null; int p = -1, t = -1; List<Subtag> tags = new LinkedList<Subtag>(); for (Subtag tag : this) { tags.add(tag); } List<Subtag> ext = new LinkedList<Subtag>(); for (Subtag tag : tags) { if (tag.getType() == Subtag.Type.SINGLETON) { if (!tag.getName().equalsIgnoreCase("x")) { ext.add(tag); } } } if (ext.size() > 0) { p = tags.indexOf(ext.get(0)); t = tags.indexOf(ext.get(ext.size() - 1)); } Collections.sort(ext, new Comparator<Subtag>() { public int compare(Subtag o1, Subtag o2) { return o1.getName().compareTo(o2.getName()); } }); List<Subtag> extchain = new LinkedList<Subtag>(); for (Subtag tag : ext) { extchain.add(tag); current = tag.getNext(); while (current != null && current.getType() == Subtag.Type.EXTENSION) { extchain.add(current); current = current.getNext(); } } List<Subtag> result = new LinkedList<Subtag>(); result.addAll(tags.subList(0, p)); result.addAll(extchain); result.addAll(tags.subList(t + 2, tags.size())); current = null; for (Subtag tag : result) { tag = tag.canonicalize(); if (primary == null) { primary = tag; current = primary; } else { current.setNext(tag); current = tag; } } return new Lang(primary); } /** * Return true if this lang tag contains any deprecated subtags */ public boolean isDeprecated() { for (Subtag tag : this) if (tag.isDeprecated()) return true; return false; } /** * Get a Lang tag that drops the last subtag */ public Lang getParent() { Lang lang = clone(); Subtag last = null; for (Subtag tag : lang) last = tag; if (last.getPrevious() == null) return null; last.getPrevious().setNext(null); return lang; } /** * Return true if the specified lang tag is the parent of this one */ public boolean isChildOf(Lang lang) { Range range = new Range(lang).appendWildcard(); return range.matches(this); } /** * Return true if the specified lang tag is the child of this one */ public boolean isParentOf(Lang lang) { return lang.isChildOf(this); } // Parsing Logic private static final String language = "((?:[a-zA-Z]{2,3}(?:[-_][a-zA-Z]{3}){0,3})|[a-zA-Z]{4}|[a-zA-Z]{5,8})"; private static final String script = "((?:[-_][a-zA-Z]{4})?)"; private static final String region = "((?:[-_](?:(?:[a-zA-Z]{2})|(?:[0-9]{3})))?)"; private static final String variant = "((?:[-_](?:(?:[a-zA-Z0-9]{5,8})|(?:[0-9][a-zA-Z0-9]{3})))*)"; private static final String extension = "((?:[-_][a-wy-zA-WY-Z0-9](?:[-_][a-zA-Z0-9]{2,8})+)*)"; private static final String privateuse = "[xX](?:[-_][a-zA-Z0-9]{2,8})+"; private static final String _privateuse = "((?:[-_]" + privateuse + ")?)"; private static final String grandfathered = "^(?:art[-_]lojban|cel[-_]gaulish|en[-_]GB[-_]oed|i[-_]ami|i[-_]bnn|i[-_]default|i[-_]enochian|i[-_]hak|i[-_]klingon|i[-_]lux|i[-_]mingo|i[-_]navajo|i[-_]pwn|i[-_]tao||i[-_]tay|i[-_]tsu|no[-_]bok|no[-_]nyn|sgn[-_]BE[-_]fr|sgn[-_]BE[-_]nl|sgn[-_]CH[-_]de|zh[-_]cmn|zh[-_]cmn[-_]Hans|zh[-_]cmn[-_]Hant|zh[-_]gan|zh[-_]guoyu|zh[-_]hakka|zh[-_]min|zh[-_]min[-_]nan|zh[-_]wuu|zh[-_]xiang|zh[-_]yue)$"; private static final String langtag = "^" + language + script + region + variant + extension + _privateuse + "$"; private static final Pattern p_langtag = Pattern.compile(langtag); private static final Pattern p_privateuse = Pattern.compile("^" + privateuse + "$"); private static final Pattern p_grandfathered = Pattern.compile(grandfathered); /** * Parse a Lang tag */ public static Lang parse(String lang) { Subtag primary = null; Matcher m = p_grandfathered.matcher(lang); if (m.find()) { String[] tags = lang.split("[-_]"); Subtag current = null; for (String tag : tags) { if (current == null) { primary = new Subtag(Type.GRANDFATHERED, tag, null); current = primary; } else { current = new Subtag(Type.GRANDFATHERED, tag, current); } } return new Lang(primary); } m = p_privateuse.matcher(lang); if (m.find()) { String[] tags = lang.split("[-_]"); Subtag current = null; for (String tag : tags) { if (current == null) { primary = new Subtag(Type.SINGLETON, tag, null); current = primary; } else { current = new Subtag(Type.PRIVATEUSE, tag, current); } } return new Lang(primary); } m = p_langtag.matcher(lang); if (m.find()) { String langtag = m.group(1); String script = m.group(2); String region = m.group(3); String variant = m.group(4); String extension = m.group(5); String privateuse = m.group(6); Subtag current = null; String[] tags = langtag.split("[-_]"); for (String tag : tags) { if (current == null) { primary = new Subtag(Type.PRIMARY, tag); current = primary; } else { current = new Subtag(Type.EXTLANG, tag, current); } } if (script != null && script.length() > 0) current = new Subtag(Type.SCRIPT, script.substring(1), current); if (region != null && region.length() > 0) current = new Subtag(Type.REGION, region.substring(1), current); if (variant != null && variant.length() > 0) { variant = variant.substring(1); tags = variant.split("-"); for (String tag : tags) current = new Subtag(Type.VARIANT, tag, current); } if (extension != null && extension.length() > 0) { extension = extension.substring(1); tags = extension.split("-"); current = new Subtag(Type.SINGLETON, tags[0], current); for (int i = 1; i < tags.length; i++) { String tag = tags[i]; current = new Subtag(tag.length() == 1 ? Type.SINGLETON : Type.EXTENSION, tag, current); } } if (privateuse != null && privateuse.length() > 0) { privateuse = privateuse.substring(1); tags = privateuse.split("-"); current = new Subtag(Type.SINGLETON, tags[0], current); for (int i = 1; i < tags.length; i++) { current = new Subtag(Type.PRIVATEUSE, tags[i], current); } } return new Lang(primary); } throw new IllegalArgumentException(); } public static String fromLocale(Locale locale) { return new Lang(locale).toString(); } }
7,282
0
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/rfc4646/Range.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.rfc4646; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.abdera.i18n.rfc4646.Subtag.Type; /** * A language range used for matching language tags */ public class Range extends SubtagSet { private static final long serialVersionUID = -6397227794306856431L; private final boolean extended; /** * Create a Language-Range * * @param range The language-range * @param extended true if this is an extended language range */ public Range(String range, boolean extended) { super(parse(range, extended).primary); this.extended = extended; } /** * Create a Language-Range */ public Range(String range) { this(parse(range).primary); } /** * Create a Language-Range from a Lang tag */ public Range(Lang lang) { this(lang.toString()); } /** * Create a Language-Range from a Lang tag * * @param lang The language tag * @param extended true if this is an extended language-range */ public Range(Lang lang, boolean extended) { this(lang.toString(), extended); } Range(Subtag primary) { super(primary); this.extended = !checkBasic(); } /** * Append a subtag to the range */ public Range append(Subtag subtag) { Subtag last = null; for (Subtag tag : this) last = tag; last.setNext(subtag); return this; } /** * Append a wildcard subtag to the range */ public Range appendWildcard() { return append(Subtag.newWildcard()); } /** * Copy this range */ public Range clone() { return new Range(primary.clone()); } /** * Create a basic language-range from this range */ public Range toBasicRange() { if (primary.getType() == Subtag.Type.WILDCARD) { return new Range("*"); } else { List<Subtag> list = new LinkedList<Subtag>(); for (Subtag tag : this) { if (tag.getType() != Subtag.Type.WILDCARD) list.add(tag.clone()); } Subtag primary = null, current = null; for (Subtag tag : list) { tag.setNext(null); tag.setPrevious(null); if (primary == null) { primary = tag; current = primary; } else { current.setNext(tag); current = tag; } } return new Range(primary); } } /** * True if this range is a basic range */ public boolean isBasic() { return !extended; } private boolean checkBasic() { Subtag current = primary.getNext(); while (current != null) { if (current.getType() == Subtag.Type.WILDCARD) return false; current = current.getNext(); } return true; } /** * True if the lang tag matches this range */ public boolean matches(String lang) { return matches(new Lang(lang), extended); } /** * True if the lang tag matches this range * * @param lang The language tage * @param extended True if extended matching rules should be used */ public boolean matches(String lang, boolean extended) { return matches(new Lang(lang), extended); } /** * True if the lang tag matches this range */ public boolean matches(Lang lang) { return matches(lang, false); } /** * True if the lang tag matches this range * * @param lang The language tage * @param extended True if extended matching rules should be used */ public boolean matches(Lang lang, boolean extended) { Iterator<Subtag> i = iterator(); Iterator<Subtag> e = lang.iterator(); if (isBasic() && !extended) { if (primary.getType() == Subtag.Type.WILDCARD) return true; for (; i.hasNext() && e.hasNext();) { Subtag in = i.next(); Subtag en = e.next(); if (!in.equals(en)) return false; } return true; } else { Subtag icurrent = i.next(); Subtag ecurrent = e.next(); if (!icurrent.equals(ecurrent)) return false; while (i.hasNext()) { icurrent = i.next(); while (icurrent.getType() == Subtag.Type.WILDCARD && i.hasNext()) icurrent = i.next(); // the range ends in a wildcard so it will match everything beyond this point if (icurrent.getType() == Subtag.Type.WILDCARD) return true; boolean matched = false; while (e.hasNext()) { ecurrent = e.next(); if (extended && (ecurrent.getType().ordinal() < icurrent.getType().ordinal())) continue; if (!ecurrent.equals(icurrent)) break; else { matched = true; break; } } if (!matched) return false; } return true; } } /** * Filter the given set of lang tags. Return an array of matching tags */ public Lang[] filter(Lang... lang) { List<Lang> langs = new LinkedList<Lang>(); for (Lang l : lang) if (matches(l)) langs.add(l); return langs.toArray(new Lang[langs.size()]); } /** * Filter the given set of lang tags. Return an array of matching tags */ public String[] filter(String... lang) { List<String> langs = new LinkedList<String>(); for (String l : lang) if (matches(l)) langs.add(l); return langs.toArray(new String[langs.size()]); } /** * Filter the given set of lang tags. Return an array of matching tags */ public static Lang[] filter(String range, Lang... lang) { return new Range(range).filter(lang); } /** * Filter the given set of lang tags. Return an array of matching tags */ public static String[] filter(String range, String... lang) { return new Range(range).filter(lang); } /** * True if the lang tag matches the range. * * @param range The language-range * @param lang The language tag * @param extended true to use extended match rules */ public static boolean matches(String range, Lang lang, boolean extended) { return new Range(range, extended).matches(lang); } /** * True if the lang tag matches the range. * * @param range The language-range * @param lang The language tag * @param extended true to use extended match rules */ public static boolean matches(String range, Lang lang) { return new Range(range).matches(lang); } /** * True if the lang tag matches the range. * * @param range The language-range * @param lang The language tag * @param extended true to use extended match rules */ public static boolean matches(String range, String lang, boolean extended) { return new Range(range, extended).matches(lang); } /** * True if the lang tag matches the range. * * @param range The language-range * @param lang The language tag * @param extended true to use extended match rules */ public static boolean matches(String range, String lang) { return new Range(range).matches(lang); } // Parsing logic // private static final String range = "((?:[a-zA-Z]{1,8}|\\*))((?:[-_](?:[a-zA-Z0-9]{1,8}|\\*))*)"; private static final String range_component = "[-_]((?:[a-zA-Z0-9]{1,8}|\\*))"; private static final Pattern p_range = Pattern.compile(range); private static final Pattern p_range_component = Pattern.compile(range_component); private static final String language = "((?:[a-zA-Z]{2,3}(?:[-_](?:[a-zA-Z]{3}|\\*)){0,3})|[a-zA-Z]{4}|[a-zA-Z]{5,8}|\\*)"; private static final String script = "((?:[-_](?:[a-zA-Z]{4}|\\*))?)"; private static final String region = "((?:[-_](?:(?:[a-zA-Z]{2})|(?:[0-9]{3})|\\*))?)"; private static final String variant = "((?:[-_](?:(?:[a-zA-Z0-9]{5,8})|(?:[0-9][a-zA-Z0-9]{3})|\\*))*)"; private static final String extension = "((?:[-_](?:(?:[a-wy-zA-WY-Z0-9](?:[-_][a-zA-Z0-9]{2,8})+)|\\*))*)"; private static final String privateuse = "[xX](?:[-_][a-zA-Z0-9]{2,8})+"; private static final String _privateuse = "((?:[-_](?:" + privateuse + ")+|\\*)?)"; private static final String langtag = "^" + language + script + region + variant + extension + _privateuse + "$"; private static final String grandfathered = "^(?:art[-_]lojban|cel[-_]gaulish|en[-_]GB[-_]oed|i[-_]ami|i[-_]bnn|i[-_]default|i[-_]enochian|i[-_]hak|i[-_]klingon|i[-_]lux|i[-_]mingo|i[-_]navajo|i[-_]pwn|i[-_]tao||i[-_]tay|i[-_]tsu|no[-_]bok|no[-_]nyn|sgn[-_]BE[-_]fr|sgn[-_]BE[-_]nl|sgn[-_]CH[-_]de|zh[-_]cmn|zh[-_]cmn[-_]Hans|zh[-_]cmn[-_]Hant|zh[-_]gan|zh[-_]guoyu|zh[-_]hakka|zh[-_]min|zh[-_]min[-_]nan|zh[-_]wuu|zh[-_]xiang|zh[-_]yue)$"; private static final Pattern p_privateuse = Pattern.compile("^" + privateuse + "$"); private static final Pattern p_grandfathered = Pattern.compile(grandfathered); private static final Pattern p_extended_range = Pattern.compile(langtag); /** * Parse the language-range */ public static Range parse(String range) { return parse(range, false); } /** * Parse the language-range * * @param range The language-range * @param extended true to use extended language rules */ public static Range parse(String range, boolean extended) { if (!extended) { Subtag primary = null, current = null; Matcher m = p_range.matcher(range); if (m.find()) { String first = m.group(1); String therest = m.group(2); primary = new Subtag(first.equals("*") ? Subtag.Type.WILDCARD : Subtag.Type.SIMPLE, first .toLowerCase(Locale.US)); current = primary; Matcher n = p_range_component.matcher(therest); while (n.find()) { String name = n.group(1).toLowerCase(Locale.US); current = new Subtag(name.equals("*") ? Subtag.Type.WILDCARD : Subtag.Type.SIMPLE, name, current); } } return new Range(primary); } else { Subtag primary = null; Matcher m = p_grandfathered.matcher(range); if (m.find()) { String[] tags = range.split("[-_]"); Subtag current = null; for (String tag : tags) { if (current == null) { primary = new Subtag(Type.GRANDFATHERED, tag, null); current = primary; } else { current = new Subtag(Type.GRANDFATHERED, tag, current); } } return new Range(primary); } m = p_privateuse.matcher(range); if (m.find()) { String[] tags = range.split("[-_]"); Subtag current = null; for (String tag : tags) { if (current == null) { primary = new Subtag(tag.equals("*") ? Type.WILDCARD : Type.SINGLETON, tag, null); current = primary; } else { current = new Subtag(tag.equals("*") ? Type.WILDCARD : Type.PRIVATEUSE, tag, current); } } return new Range(primary); } m = p_extended_range.matcher(range); if (m.find()) { String langtag = m.group(1); String script = m.group(2); String region = m.group(3); String variant = m.group(4); String extension = m.group(5); String privateuse = m.group(6); Subtag current = null; String[] tags = langtag.split("[-_]"); for (String tag : tags) { if (current == null) { primary = new Subtag(tag.equals("*") ? Type.WILDCARD : Type.PRIMARY, tag); current = primary; } else { current = new Subtag(tag.equals("*") ? Type.WILDCARD : Type.EXTLANG, tag, current); } } if (script != null && script.length() > 0) current = new Subtag(script.substring(1).equals("*") ? Type.WILDCARD : Type.SCRIPT, script.substring(1), current); if (region != null && region.length() > 0) current = new Subtag(region.substring(1).equals("*") ? Type.WILDCARD : Type.REGION, region.substring(1), current); if (variant != null && variant.length() > 0) { variant = variant.substring(1); tags = variant.split("-"); for (String tag : tags) current = new Subtag(tag.equals("*") ? Type.WILDCARD : Type.VARIANT, tag, current); } if (extension != null && extension.length() > 0) { extension = extension.substring(1); tags = extension.split("-"); current = new Subtag(tags[0].equals("*") ? Type.WILDCARD : Type.SINGLETON, tags[0], current); for (int i = 1; i < tags.length; i++) { String tag = tags[i]; current = new Subtag(tag.equals("*") ? Type.WILDCARD : tag.length() == 1 ? Type.SINGLETON : Type.EXTENSION, tag, current); } } if (privateuse != null && privateuse.length() > 0) { privateuse = privateuse.substring(1); tags = privateuse.split("-"); current = new Subtag(tags[0].equals("*") ? Type.WILDCARD : Type.SINGLETON, tags[0], current); for (int i = 1; i < tags.length; i++) { current = new Subtag(tags[i].equals("*") ? Type.WILDCARD : Type.PRIVATEUSE, tags[i], current); } } return new Range(primary); } } throw new IllegalArgumentException("Invalid range"); } }
7,283
0
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/rfc4646/Subtag.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.rfc4646; import java.io.Serializable; import java.util.Locale; import org.apache.abdera.i18n.rfc4646.enums.Extlang; import org.apache.abdera.i18n.rfc4646.enums.Language; import org.apache.abdera.i18n.rfc4646.enums.Region; import org.apache.abdera.i18n.rfc4646.enums.Script; import org.apache.abdera.i18n.rfc4646.enums.Singleton; import org.apache.abdera.i18n.rfc4646.enums.Variant; /** * A Lang tag subtag */ public final class Subtag implements Serializable, Cloneable, Comparable<Subtag> { private static final long serialVersionUID = -4496128268514329138L; public enum Type { /** Primary language subtag **/ PRIMARY, /** Extended Language subtag **/ EXTLANG, /** Script subtag **/ SCRIPT, /** Region subtag **/ REGION, /** Variant subtag **/ VARIANT, /** Singleton subtag **/ SINGLETON, /** Extension subtag **/ EXTENSION, /** Primary-use subtag **/ PRIVATEUSE, /** Grandfathered subtag **/ GRANDFATHERED, /** Wildcard subtag ("*") **/ WILDCARD, /** Simple subtag (ranges) **/ SIMPLE } private final Type type; private final String name; private Subtag prev; private Subtag next; /** * Create a Subtag */ public Subtag(Language language) { this(Type.PRIMARY, language.name().toLowerCase(Locale.US)); } /** * Create a Subtag */ public Subtag(Script script) { this(Type.SCRIPT, toTitleCase(script.name())); } /** * Create a Subtag */ public Subtag(Region region) { this(Type.REGION, getRegionName(region.name())); } private static String getRegionName(String name) { return name.startsWith("UN") && name.length() == 5 ? name.substring(2) : name; } /** * Create a Subtag */ public Subtag(Variant variant) { this(Type.VARIANT, getVariantName(variant.name().toLowerCase(Locale.US))); } private static String getVariantName(String name) { return name.startsWith("_") ? name.substring(1) : name; } /** * Create a Subtag */ public Subtag(Extlang extlang) { this(Type.EXTLANG, extlang.name().toLowerCase(Locale.US)); } /** * Create a Subtag */ public Subtag(Singleton singleton) { this(Type.SINGLETON, singleton.name().toLowerCase(Locale.US)); } /** * Create a Subtag */ public Subtag(Type type, String name) { this(type, name, null); } Subtag() { this(Type.WILDCARD, "*"); } /** * Create a Subtag */ public Subtag(Type type, String name, Subtag prev) { this.type = type; this.name = name; this.prev = prev; if (prev != null) prev.setNext(this); } Subtag(Type type, String name, Subtag prev, Subtag next) { this.type = type; this.name = name; this.prev = prev; this.next = next; } /** * Get the subtag type */ public Type getType() { return type; } /** * Get the subtag value */ public String getName() { return toString(); } void setPrevious(Subtag prev) { this.prev = prev; } /** * Get the previous subtag */ public Subtag getPrevious() { return prev; } void setNext(Subtag next) { this.next = next; if (next != null) next.setPrevious(this); } /** * Get the next subtag */ public Subtag getNext() { return next; } public String toString() { switch (type) { case PRIMARY: return name.toLowerCase(Locale.US); case REGION: return name.toUpperCase(Locale.US); case SCRIPT: return toTitleCase(name); default: return name.toLowerCase(Locale.US); } } private static String toTitleCase(String string) { if (string == null) return null; if (string.length() == 0) return string; char[] chars = string.toLowerCase(Locale.US).toCharArray(); chars[0] = (char)(chars[0] - 32); return new String(chars); } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.toLowerCase(Locale.US).hashCode()); result = prime * result + ((type == null) ? 0 : type.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Subtag other = (Subtag)obj; if (other.getType() == Type.WILDCARD || getType() == Type.WILDCARD) return true; if (name == null) { if (other.name != null) return false; } else if (!name.equalsIgnoreCase(other.name)) return false; if (other.getType() == Type.SIMPLE || getType() == Type.SIMPLE) return true; if (type == null) { if (other.type != null) return false; } else if (!type.equals(other.type)) return false; return true; } public Subtag clone() { try { Subtag tag = (Subtag)super.clone(); if (getNext() != null) tag.setNext(getNext().clone()); return tag; } catch (CloneNotSupportedException e) { return new Subtag(type, name, prev != null ? prev.clone() : null, next != null ? next.clone() : null); // not // going // to // happen } } /** * True if this subtag has been deprecated */ public boolean isDeprecated() { switch (type) { case PRIMARY: { Language e = getEnum(); return e.isDeprecated(); } case SCRIPT: { Script e = getEnum(); return e.isDeprecated(); } case REGION: { Region e = getEnum(); return e.isDeprecated(); } case VARIANT: { Variant e = getEnum(); return e.isDeprecated(); } case EXTLANG: { Extlang e = getEnum(); return e.isDeprecated(); } case EXTENSION: { Singleton e = getEnum(); return e.isDeprecated(); } default: return false; } } /** * Get this subtags Enum, allowing the subtag to be verified */ @SuppressWarnings("unchecked") public <T extends Enum<?>> T getEnum() { switch (type) { case PRIMARY: return (T)Language.valueOf(this); case SCRIPT: return (T)Script.valueOf(this); case REGION: return (T)Region.valueOf(this); case VARIANT: return (T)Variant.valueOf(this); case EXTLANG: return (T)Extlang.valueOf(this); case EXTENSION: return (T)Singleton.valueOf(this); default: return null; } } /** * True if this subtag is valid */ public boolean isValid() { switch (type) { case PRIMARY: case SCRIPT: case REGION: case VARIANT: case EXTLANG: try { getEnum(); return true; } catch (Exception e) { return false; } case EXTENSION: return name.matches("[A-Za-z0-9]{2,8}"); case GRANDFATHERED: return name.matches("[A-Za-z]{1,3}(?:-[A-Za-z0-9]{2,8}){1,2}"); case PRIVATEUSE: return name.matches("[A-Za-z0-9]{1,8}"); case SINGLETON: return name.matches("[A-Za-z]"); case WILDCARD: return name.equals("*"); case SIMPLE: return name.matches("[A-Za-z0-9]{1,8}"); default: return false; } } /** * Return the canonicalized version of this subtag */ public Subtag canonicalize() { switch (type) { case REGION: Region region = getEnum(); return region.getPreferred().newSubtag(); case PRIMARY: Language language = getEnum(); return language.getPreferred().newSubtag(); case SCRIPT: Script script = getEnum(); return script.getPreferred().newSubtag(); case VARIANT: Variant variant = getEnum(); return variant.getPreferred().newSubtag(); case EXTLANG: Extlang extlang = getEnum(); return extlang.getPreferred().newSubtag(); case EXTENSION: case GRANDFATHERED: case PRIVATEUSE: case SINGLETON: default: return this; } } /** * Create a new wildcard subtag */ public static Subtag newWildcard() { return new Subtag(); } public int compareTo(Subtag o) { int c = o.type.compareTo(type); return c != 0 ? c : o.name.compareTo(name); } }
7,284
0
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/rfc4646
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/rfc4646/enums/Variant.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.rfc4646.enums; import java.util.Locale; import org.apache.abdera.i18n.rfc4646.Subtag; /** * Enum constants used to validate language tags */ public enum Variant { _1606NICT(null, null, "frm", "Late Middle French (to 1606)"), _1694ACAD(null, null, "fr", "Early Modern French"), _1901( null, null, "de", "Traditional German orthography"), _1994(null, null, new String[] {"sl-rozaj", "sl-rozaj-biske", "sl-rozaj-njiva", "sl-rozaj-osojs", "sl-rozaj-solba"}, "Standardized Resian orthography"), _1996(null, null, "de", "German orthography of 1996"), AREVELA(null, null, "hy", "Eastern Armenian"), AREVMDA(null, null, "hy", "Western Armenian"), BAKU1926(null, null, new String[] {"az", "ba", "crh", "kk", "krc", "ky", "sah", "tk", "tt", "uz"}, "Unified Turkic Latin Alphabet (Historical)"), BISKE(null, null, "sl-rozaj", "The San Giorgio dialect of Resian", "The Bila dialect of Resian"), BOONT(null, null, "en", "Boontling"), FONIPA( null, null, (String)null, "International Phonetic Alphabet"), FONUPA(null, null, (String)null, "Uralic Phonetic Alphabet"), LIPAW(null, null, "sl-rozaj", "The Lipovaz dialect of Resian", "The Lipovec dialect of Resian"), MONOTON(null, null, "el", "Monotonic Greek"), NEDIS(null, null, "sl", "Natisone dialect", "Nadiza dialect"), NJIVA(null, null, "sl-rozaj", "The Gniva dialect of Resian", "The Njiva dialect of Resian"), OSOJS(null, null, "sl-rozaj", "The Oseacco dialect of Resian", "The Osojane dialect of Resian"), POLYTON(null, null, "el", "Polytonic Greek"), ROZAJ(null, null, "sl", "Resian", "Resianic", "Rezijan"), SCOTLAND(null, null, "en", "Scottish Standard English"), SCOUSE(null, null, "en", "Scouse"), SOLBA(null, null, "sl-rozaj", "The Stolvizza dialect of Resian", "The Solbica dialect of Resian"), TARASK(null, null, "be", "Belarusian in Taraskievica orthography"), VALENCIA( null, null, "ca", "Valencian"); private final String deprecated; private final String preferred; private final String[] prefixes; private final String[] descriptions; private Variant(String dep, String pref, String prefix, String... desc) { this(dep, pref, new String[] {prefix}, desc); } private Variant(String dep, String pref, String[] prefixes, String... desc) { this.deprecated = dep; this.preferred = pref; this.prefixes = prefixes; this.descriptions = desc; } public boolean isDeprecated() { return deprecated != null; } public String getDeprecated() { return deprecated; } public String getPreferredValue() { return preferred; } public Variant getPreferred() { return preferred != null ? valueOf(preferred.toUpperCase(Locale.US)) : this; } public String getPrefix() { return prefixes != null && prefixes.length > 0 ? prefixes[0] : null; } public String[] getPrefixes() { return prefixes; } public String getDescription() { return descriptions.length > 0 ? descriptions[0] : null; } public String[] getDescriptions() { return descriptions; } public Subtag newSubtag() { return new Subtag(this); } public static Variant valueOf(Subtag subtag) { if (subtag == null) return null; if (subtag.getType() == Subtag.Type.VARIANT) { String name = subtag.getName(); if (name.startsWith("1")) name = "_" + name; return valueOf(name.toUpperCase(Locale.US)); } else throw new IllegalArgumentException("Wrong subtag type"); } }
7,285
0
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/rfc4646
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/rfc4646/enums/Region.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.rfc4646.enums; import java.util.Locale; import org.apache.abdera.i18n.rfc4646.Subtag; /** * Enum constants used to validate language tags */ public enum Region { AA(null, null, "PRIVATE USE"), AD(null, null, "Andorra"), AE(null, null, "United Arab Emirates"), AF(null, null, "Afghanistan"), AG(null, null, "Antigua and Barbuda"), AI(null, null, "Anguilla"), AL(null, null, "Albania"), AM( null, null, "Armenia"), AN(null, null, "Netherlands Antilles"), AO(null, null, "Angola"), AQ(null, null, "Antarctica"), AR(null, null, "Argentina"), AS(null, null, "American Samoa"), AT(null, null, "Austria"), AU( null, null, "Australia"), AW(null, null, "Aruba"), AX(null, null, "&#xC5;land Islands"), AZ(null, null, "Azerbaijan"), BA(null, null, "Bosnia and Herzegovina"), BB(null, null, "Barbados"), BD(null, null, "Bangladesh"), BE(null, null, "Belgium"), BF(null, null, "Burkina Faso"), BG(null, null, "Bulgaria"), BH(null, null, "Bahrain"), BI(null, null, "Burundi"), BJ(null, null, "Benin"), BL(null, null, "Saint Barth&#xE9;lemy"), BM( null, null, "Bermuda"), BN(null, null, "Brunei Darussalam"), BO(null, null, "Bolivia"), BR(null, null, "Brazil"), BS( null, null, "Bahamas"), BT(null, null, "Bhutan"), BU("1989-12-05", "MM", "Burma"), BV(null, null, "Bouvet Island"), BW(null, null, "Botswana"), BY(null, null, "Belarus"), BZ(null, null, "Belize"), CA(null, null, "Canada"), CC(null, null, "Cocos (Keeling) Islands"), CD(null, null, "Congo, The Democratic Republic of the"), CF(null, null, "Central African Republic"), CG(null, null, "Congo"), CH( null, null, "Switzerland"), CI(null, null, "C&#xF4;te d'Ivoire"), CK(null, null, "Cook Islands"), CL(null, null, "Chile"), CM(null, null, "Cameroon"), CN(null, null, "China"), CO(null, null, "Colombia"), CR(null, null, "Costa Rica"), CS("2006-10-05", null, "Serbia and Montenegro"), CU(null, null, "Cuba"), CV(null, null, "Cape Verde"), CX(null, null, "Christmas Island"), CY(null, null, "Cyprus"), CZ(null, null, "Czech Republic"), DD( "1990-10-30", "DE", "German Democratic Republic"), DE(null, null, "Germany"), DJ(null, null, "Djibouti"), DK( null, null, "Denmark"), DM(null, null, "Dominica"), DO(null, null, "Dominican Republic"), DZ(null, null, "Algeria"), EC(null, null, "Ecuador"), EE(null, null, "Estonia"), EG(null, null, "Egypt"), EH(null, null, "Western Sahara"), ER(null, null, "Eritrea"), ES(null, null, "Spain"), ET(null, null, "Ethiopia"), FI(null, null, "Finland"), FJ(null, null, "Fiji"), FK(null, null, "Falkland Islands (Malvinas)"), FM(null, null, "Micronesia, Federated States of"), FO(null, null, "Faroe Islands"), FR(null, null, "France"), FX("1997-07-14", "FR", "Metropolitan France"), GA(null, null, "Gabon"), GB(null, null, "United Kingdom"), GD(null, null, "Grenada"), GE(null, null, "Georgia"), GF(null, null, "French Guiana"), GG(null, null, "Guernsey"), GH(null, null, "Ghana"), GI(null, null, "Gibraltar"), GL(null, null, "Greenland"), GM(null, null, "Gambia"), GN(null, null, "Guinea"), GP(null, null, "Guadeloupe"), GQ(null, null, "Equatorial Guinea"), GR(null, null, "Greece"), GS( null, null, "South Georgia and the South Sandwich Islands"), GT(null, null, "Guatemala"), GU(null, null, "Guam"), GW( null, null, "Guinea-Bissau"), GY(null, null, "Guyana"), HK(null, null, "Hong Kong"), HM(null, null, "Heard Island and McDonald Islands"), HN(null, null, "Honduras"), HR(null, null, "Croatia"), HT(null, null, "Haiti"), HU(null, null, "Hungary"), ID(null, null, "Indonesia"), IE(null, null, "Ireland"), IL(null, null, "Israel"), IM(null, null, "Isle of Man"), IN(null, null, "India"), IO(null, null, "British Indian Ocean Territory"), IQ(null, null, "Iraq"), IR(null, null, "Iran, Islamic Republic of"), IS( null, null, "Iceland"), IT(null, null, "Italy"), JE(null, null, "Jersey"), JM(null, null, "Jamaica"), JO(null, null, "Jordan"), JP(null, null, "Japan"), KE(null, null, "Kenya"), KG(null, null, "Kyrgyzstan"), KH(null, null, "Cambodia"), KI(null, null, "Kiribati"), KM(null, null, "Comoros"), KN(null, null, "Saint Kitts and Nevis"), KP( null, null, "Korea, Democratic People's Republic of"), KR(null, null, "Korea, Republic of"), KW(null, null, "Kuwait"), KY(null, null, "Cayman Islands"), KZ(null, null, "Kazakhstan"), LA(null, null, "Lao People's Democratic Republic"), LB(null, null, "Lebanon"), LC(null, null, "Saint Lucia"), LI(null, null, "Liechtenstein"), LK(null, null, "Sri Lanka"), LR(null, null, "Liberia"), LS(null, null, "Lesotho"), LT(null, null, "Lithuania"), LU(null, null, "Luxembourg"), LV(null, null, "Latvia"), LY(null, null, "Libyan Arab Jamahiriya"), MA(null, null, "Morocco"), MC(null, null, "Monaco"), MD(null, null, "Moldova, Republic of"), ME(null, null, "Montenegro"), MF(null, null, "Saint Martin"), MG(null, null, "Madagascar"), MH(null, null, "Marshall Islands"), MK(null, null, "Macedonia, The Former Yugoslav Republic of"), ML( null, null, "Mali"), MM(null, null, "Myanmar"), MN(null, null, "Mongolia"), MO(null, null, "Macao"), MP(null, null, "Northern Mariana Islands"), MQ(null, null, "Martinique"), MR(null, null, "Mauritania"), MS(null, null, "Montserrat"), MT(null, null, "Malta"), MU(null, null, "Mauritius"), MV(null, null, "Maldives"), MW(null, null, "Malawi"), MX(null, null, "Mexico"), MY(null, null, "Malaysia"), MZ(null, null, "Mozambique"), NA(null, null, "Namibia"), NC(null, null, "New Caledonia"), NE(null, null, "Niger"), NF(null, null, "Norfolk Island"), NG( null, null, "Nigeria"), NI(null, null, "Nicaragua"), NL(null, null, "Netherlands"), NO(null, null, "Norway"), NP( null, null, "Nepal"), NR(null, null, "Nauru"), NT("1993-07-12", null, "Neutral Zone"), NU(null, null, "Niue"), NZ( null, null, "New Zealand"), OM(null, null, "Oman"), PA(null, null, "Panama"), PE(null, null, "Peru"), PF(null, null, "French Polynesia"), PG(null, null, "Papua New Guinea"), PH(null, null, "Philippines"), PK(null, null, "Pakistan"), PL(null, null, "Poland"), PM(null, null, "Saint Pierre and Miquelon"), PN(null, null, "Pitcairn"), PR( null, null, "Puerto Rico"), PS(null, null, "Palestinian Territory, Occupied"), PT(null, null, "Portugal"), PW( null, null, "Palau"), PY(null, null, "Paraguay"), QA(null, null, "Qatar"), QM(null, null, "PRIVATE USE"), QN( null, null, "PRIVATE USE"), QO(null, null, "PRIVATE USE"), QP(null, null, "PRIVATE USE"), QQ(null, null, "PRIVATE USE"), QR(null, null, "PRIVATE USE"), QS(null, null, "PRIVATE USE"), QT(null, null, "PRIVATE USE"), QU( null, null, "PRIVATE USE"), QV(null, null, "PRIVATE USE"), QW(null, null, "PRIVATE USE"), QX(null, null, "PRIVATE USE"), QY(null, null, "PRIVATE USE"), QZ(null, null, "PRIVATE USE"), RE(null, null, "R&#xE9;union"), RO( null, null, "Romania"), RS(null, null, "Serbia"), RU(null, null, "Russian Federation"), RW(null, null, "Rwanda"), SA( null, null, "Saudi Arabia"), SB(null, null, "Solomon Islands"), SC(null, null, "Seychelles"), SD(null, null, "Sudan"), SE(null, null, "Sweden"), SG(null, null, "Singapore"), SH(null, null, "Saint Helena"), SI(null, null, "Slovenia"), SJ(null, null, "Svalbard and Jan Mayen"), SK(null, null, "Slovakia"), SL(null, null, "Sierra Leone"), SM(null, null, "San Marino"), SN(null, null, "Senegal"), SO(null, null, "Somalia"), SR(null, null, "Suriname"), ST(null, null, "Sao Tome and Principe"), SU("1992-08-30", null, "Union of Soviet Socialist Republics"), SV(null, null, "El Salvador"), SY(null, null, "Syrian Arab Republic"), SZ( null, null, "Swaziland"), TC(null, null, "Turks and Caicos Islands"), TD(null, null, "Chad"), TF(null, null, "French Southern Territories"), TG(null, null, "Togo"), TH(null, null, "Thailand"), TJ(null, null, "Tajikistan"), TK( null, null, "Tokelau"), TL(null, null, "Timor-Leste"), TM(null, null, "Turkmenistan"), TN(null, null, "Tunisia"), TO( null, null, "Tonga"), TP("2002-11-15", "TL", "East Timor"), TR(null, null, "Turkey"), TT(null, null, "Trinidad and Tobago"), TV(null, null, "Tuvalu"), TW(null, null, "Taiwan, Province of China"), TZ(null, null, "Tanzania, United Republic of"), UA(null, null, "Ukraine"), UG(null, null, "Uganda"), UM(null, null, "United States Minor Outlying Islands"), US(null, null, "United States"), UY(null, null, "Uruguay"), UZ(null, null, "Uzbekistan"), VA(null, null, "Holy See (Vatican City State)"), VC(null, null, "Saint Vincent and the Grenadines"), VE(null, null, "Venezuela"), VG(null, null, "Virgin Islands, British"), VI( null, null, "Virgin Islands, U.S."), VN(null, null, "Viet Nam"), VU(null, null, "Vanuatu"), WF(null, null, "Wallis and Futuna"), WS(null, null, "Samoa"), XA(null, null, "PRIVATE USE"), XB(null, null, "PRIVATE USE"), XC( null, null, "PRIVATE USE"), XD(null, null, "PRIVATE USE"), XE(null, null, "PRIVATE USE"), XF(null, null, "PRIVATE USE"), XG(null, null, "PRIVATE USE"), XH(null, null, "PRIVATE USE"), XI(null, null, "PRIVATE USE"), XJ( null, null, "PRIVATE USE"), XK(null, null, "PRIVATE USE"), XL(null, null, "PRIVATE USE"), XM(null, null, "PRIVATE USE"), XN(null, null, "PRIVATE USE"), XO(null, null, "PRIVATE USE"), XP(null, null, "PRIVATE USE"), XQ( null, null, "PRIVATE USE"), XR(null, null, "PRIVATE USE"), XS(null, null, "PRIVATE USE"), XT(null, null, "PRIVATE USE"), XU(null, null, "PRIVATE USE"), XV(null, null, "PRIVATE USE"), XW(null, null, "PRIVATE USE"), XX( null, null, "PRIVATE USE"), XY(null, null, "PRIVATE USE"), XZ(null, null, "PRIVATE USE"), YD("1990-08-14", "YE", "Yemen, Democratic"), YE(null, null, "Yemen"), YT(null, null, "Mayotte"), YU("2003-07-23", "CS", "Yugoslavia"), ZA(null, null, "South Africa"), ZM(null, null, "Zambia"), ZR("1997-07-14", "CD", "Zaire"), ZW( null, null, "Zimbabwe"), ZZ(null, null, "PRIVATE USE"), UN001(null, null, "World"), UN002(null, null, "Africa"), UN005( null, null, "South America"), UN009(null, null, "Oceania"), UN011(null, null, "Western Africa"), UN013(null, null, "Central America"), UN014(null, null, "Eastern Africa"), UN015(null, null, "Northern Africa"), UN017( null, null, "Middle Africa"), UN018(null, null, "Southern Africa"), UN019(null, null, "Americas"), UN021(null, null, "Northern America"), UN029(null, null, "Caribbean"), UN030(null, null, "Eastern Asia"), UN034(null, null, "Southern Asia"), UN035(null, null, "South-Eastern Asia"), UN039(null, null, "Southern Europe"), UN053(null, null, "Australia and New Zealand"), UN054(null, null, "Melanesia"), UN057(null, null, "Micronesia"), UN061( null, null, "Polynesia"), UN142(null, null, "Asia"), UN143(null, null, "Central Asia"), UN145(null, null, "Western Asia"), UN150(null, null, "Europe"), UN151(null, null, "Eastern Europe"), UN154(null, null, "Northern Europe"), UN155(null, null, "Western Europe"), UN419(null, null, "Latin America and the Caribbean"); private final String deprecated; private final String preferred; private final String[] descriptions; private Region(String dep, String pref, String... desc) { this.deprecated = dep; this.preferred = pref; this.descriptions = desc; } public String getDeprecated() { return deprecated; } public boolean isDeprecated() { return deprecated != null; } public Region getPreferred() { return preferred != null ? valueOf(preferred.toUpperCase(Locale.US)) : this; } public String getPreferredValue() { return preferred; } public String getDescription() { return descriptions.length > 0 ? descriptions[0] : null; } public String[] getDescriptions() { return descriptions; } public Subtag newSubtag() { return new Subtag(this); } public static Region valueOf(Subtag subtag) { if (subtag == null) return null; if (subtag.getType() == Subtag.Type.REGION) { String name = subtag.getName(); if (name.length() == 3) name = "UN" + name; else name = name.toUpperCase(Locale.US); return valueOf(name); } else throw new IllegalArgumentException("Wrong subtag type"); } }
7,286
0
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/rfc4646
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/rfc4646/enums/Singleton.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.rfc4646.enums; import java.util.Locale; import org.apache.abdera.i18n.rfc4646.Subtag; /** * Enum constants used to validate language tags */ public enum Singleton { A("Undefined", -1, null, null), B("Undefined", -1, null, null), C("Undefined", -1, null, null), D("Undefined", -1, null, null), E("Undefined", -1, null, null), F("Undefined", -1, null, null), G("Undefined", -1, null, null), H( "Undefined", -1, null, null), I("Undefined", -1, null, null), J("Undefined", -1, null, null), K("Undefined", -1, null, null), L("Undefined", -1, null, null), M("Undefined", -1, null, null), N("Undefined", -1, null, null), O( "Undefined", -1, null, null), P("Undefined", -1, null, null), Q("Undefined", -1, null, null), R("Undefined", -1, null, null), S("Undefined", -1, null, null), T("Undefined", -1, null, null), U("Undefined", -1, null, null), V( "Undefined", -1, null, null), W("Undefined", -1, null, null), X("Private Use", 4646, null, null), Y( "Undefined", -1, null, null), Z("Undefined", -1, null, null); private final String description; private final int rfc; private final String deprecated; private final String preferred; private Singleton(String description, int rfc, String deprecated, String preferred) { this.description = description; this.rfc = rfc; this.deprecated = deprecated; this.preferred = preferred; } public String getDescription() { return description; } public int getRFC() { return rfc; } public Subtag newSubtag() { return new Subtag(this); } public String getDeprecated() { return deprecated; } public boolean isDeprecated() { return deprecated != null; } public String getPreferredValue() { return preferred; } public Singleton getPreferred() { return preferred != null ? valueOf(preferred.toUpperCase(Locale.US)) : this; } public static Singleton valueOf(Subtag subtag) { if (subtag == null) return null; if (subtag.getType() == Subtag.Type.SINGLETON) return valueOf(subtag.getName().toUpperCase(Locale.US)); else throw new IllegalArgumentException("Wrong subtag type"); } }
7,287
0
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/rfc4646
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/rfc4646/enums/Extlang.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.rfc4646.enums; import java.util.Locale; import org.apache.abdera.i18n.rfc4646.Subtag; /** * Enum constants used to validate language tags */ public enum Extlang { // none registered yet ; private final String deprecated; private final String preferred; private final String prefix; private final String[] descriptions; private Extlang(String dep, String pref, String prefix, String... desc) { this.deprecated = dep; this.preferred = pref; this.prefix = prefix; this.descriptions = desc; } public String getDeprecated() { return deprecated; } public boolean isDeprecated() { return deprecated != null; } public String getPreferredValue() { return preferred; } public Extlang getPreferred() { return preferred != null ? valueOf(preferred.toUpperCase(Locale.US)) : this; } public String getPrefix() { return prefix; } public String getDescription() { return descriptions.length > 0 ? descriptions[0] : null; } public String[] getDescriptions() { return descriptions; } public Subtag newSubtag() { return new Subtag(this); } public static Extlang valueOf(Subtag subtag) { if (subtag == null) return null; if (subtag.getType() == Subtag.Type.PRIMARY) return valueOf(subtag.getName().toUpperCase(Locale.US)); else throw new IllegalArgumentException("Wrong subtag type"); } }
7,288
0
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/rfc4646
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/rfc4646/enums/Language.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.rfc4646.enums; import java.util.Locale; import org.apache.abdera.i18n.rfc4646.Subtag; /** * Enum constants used to validate language tags */ public enum Language { // ISO 639-1 AA(null, null, "Afar"), AB(null, null, "Abkhazian"), AE(null, null, "Avestan"), AF(null, null, "Afrikaans"), AK( null, null, "Akan"), AM(null, null, "Amharic"), AN(null, null, "Aragonese"), AR(null, null, "Arabic"), AS(null, null, "Assamese"), AV(null, null, "Avaric"), AY(null, null, "Aymara"), AZ(null, null, "Azerbaijani"), BA(null, null, "Bashkir"), BE(null, null, "Belarusian"), BG(null, null, "Bulgarian"), BH(null, null, "Bihari"), BI(null, null, "Bislama"), BM(null, null, "Bambara"), BN(null, null, "Bengali"), BO(null, null, "Tibetan"), BR(null, null, "Breton"), BS(null, null, "Bosnian"), CA(null, null, "Catalan", "Valencian"), CE(null, null, "Chechen"), CH( null, null, "Chamorro"), CO(null, null, "Corsican"), CR(null, null, "Cree"), CS(null, null, "Czech"), CU(null, null, "Church Slavic", "Old Slavonic", "Church Slavonic", "Old Bulgarian", "Old Church Slavonic"), CV(null, null, "Chuvash"), CY(null, null, "Welsh"), DA(null, null, "Danish"), DE(null, null, "German"), DV(null, null, "Divehi", "Dhivehi", "Maldivian"), DZ(null, null, "Dzongkha"), EE(null, null, "Ewe"), EL(null, null, "Greek, Modern (1453-)"), EN(null, null, "English"), EO(null, null, "Esperanto"), ES(null, null, "Spanish", "Castilian"), ET(null, null, "Estonian"), EU(null, null, "Basque"), FA(null, null, "Persian"), FF(null, null, "Fulah"), FI(null, null, "Finnish"), FJ(null, null, "Fijian"), FO(null, null, "Faroese"), FR(null, null, "French"), FY(null, null, "Western Frisian"), GA(null, null, "Irish"), GD(null, null, "Gaelic", "Scottish Gaelic"), GL(null, null, "Galician"), GN(null, null, "Guarani"), GU(null, null, "Gujarati"), GV(null, null, "Manx"), HA(null, null, "Hausa"), HE(null, null, "Hebrew"), HI(null, null, "Hindi"), HO(null, null, "Hiri Motu"), HR(null, null, "Croatian"), HT(null, null, "Haitian", "Haitian Creole"), HU(null, null, "Hungarian"), HY(null, null, "Armenian"), HZ(null, null, "Herero"), IA(null, null, "Interlingua (International Auxiliary Language Association)"), ID(null, null, "Indonesian"), IE(null, null, "Interlingue", "Occidental"), IG(null, null, "Igbo"), II(null, null, "Sichuan Yi", "Nuosu"), IK(null, null, "Inupiaq"), IN("1989-01-01", "id", "Indonesian"), IO(null, null, "Ido"), IS(null, null, "Icelandic"), IT(null, null, "Italian"), IU(null, null, "Inuktitut"), IW("1989-01-01", "he", null, "Hebrew"), JA(null, null, "Japanese"), JI("1989-01-01", "yi", "Yiddish"), JV(null, null, "Javanese"), JW("2001-08-13", "jv", "Javanese"), KA( null, null, "Georgian"), KG(null, null, "Kongo"), KI(null, null, "Kikuyu", "Gikuyu"), KJ(null, null, "Kuanyama", "Kwanyama"), KK(null, null, "Kazakh"), KL(null, null, "Kalaallisut", "Greenlandic"), KM(null, null, "Central Khmer"), KN(null, null, "Kannada"), KO(null, null, "Korean"), KR(null, null, "Kanuri"), KS(null, null, "Kashmiri"), KU(null, null, "Kurdish"), KV(null, null, "Komi"), KW(null, null, "Cornish"), KY(null, null, "Kyrgyz", "Kirghiz"), LA(null, null, "Latin"), LB(null, null, "Luxembourgish", "Letzeburgesch"), LG(null, null, "Ganda"), LI(null, null, "Limburgan", "Limburger", "Limburgish"), LN(null, null, "Lingala"), LO(null, null, "Lao"), LT(null, null, "Lithuanian"), LU(null, null, "Luba-Katanga"), LV(null, null, "Latvian"), MG(null, null, "Malagasy"), MH(null, null, "Marshallese"), MI(null, null, "Maori"), MK(null, null, "Macedonian"), ML(null, null, "Malayalam"), MN(null, null, "Mongolian"), MO("2008-11-03", null, null, "Moldavian"), MR(null, null, "Marathi"), MS(null, null, "Malay"), MT(null, null, "Maltese"), MY(null, null, "Burmese"), NA(null, null, "Nauru"), NB(null, null, "Norwegian Bokm&#xE5;l"), ND(null, null, "Ndebele, North", "North Ndebele"), NE(null, null, "Nepali"), NG(null, null, "Ndonga"), NL(null, null, "Dutch", "Flemish"), NN(null, null, "Norwegian Nynorsk"), NO(null, null, "Norwegian"), NR(null, null, "Ndebele, South", "South Ndebele"), NV(null, null, "Navajo", "Navaho"), NY(null, null, "Chichewa", "Chewa", "Nyanja"), OC(null, null, "Occitan (post 1500)", "Proven&#xE7;al"), OJ(null, null, "Ojibwa"), OM(null, null, "Oromo"), OR(null, null, "Oriya"), OS(null, null, "Ossetian", "Ossetic"), PA(null, null, "Panjabi", "Punjabi"), PI(null, null, "Pali"), PL(null, null, "Polish"), PS( null, null, "Pushto"), PT(null, null, "Portuguese"), QU(null, null, "Quechua"), RM(null, null, "Romansh"), RN( null, null, "Rundi"), RO(null, null, "Romanian"), RU(null, null, "Russian"), RW(null, null, "Kinyarwanda"), SA( null, null, "Sanskrit"), SC(null, null, "Sardinian"), SD(null, null, "Sindhi"), SE(null, null, "Northern Sami"), SG( null, null, "Sango"), SH("2000-02-18", null, null, "Serbo-Croatian"), SI(null, null, "Sinhala", "Sinhalese"), SK( null, null, "Slovak"), SL(null, null, "Slovenian"), SM(null, null, "Samoan"), SN(null, null, "Shona"), SO(null, null, "Somali"), SQ(null, null, "Albanian"), SR(null, null, "Serbian"), SS(null, null, "Swati"), ST(null, null, "Sotho, Southern"), SU(null, null, "Sundanese"), SV(null, null, "Swedish"), SW(null, null, "Swahili"), TA(null, null, "Tamil"), TE(null, null, "Telugu"), TG(null, null, "Tajik"), TH(null, null, "Thai"), TI(null, null, "Tigrinya"), TK(null, null, "Turkmen"), TL(null, null, "Tagalog"), TN(null, null, "Tswana"), TO(null, null, "Tonga (Tonga Islands)"), TR(null, null, "Turkish"), TS(null, null, "Tsonga"), TT(null, null, "Tatar"), TW( null, null, "Twi"), TY(null, null, "Tahitian"), UG(null, null, "Uighur", "Uyghur"), UK(null, null, "Ukrainian"), UR( null, null, "Urdu"), UZ(null, null, "Uzbek"), VE(null, null, "Venda"), VI(null, null, "Vietnamese"), VO(null, null, "Volap&#xFC;k"), WA(null, null, "Walloon"), WO(null, null, "Wolof"), XH(null, null, "Xhosa"), YI(null, null, "Yiddish"), YO(null, null, "Yoruba"), ZA(null, null, "Zhuang", "Chuang"), ZH(null, null, "Chinese"), ZU( null, null, "Zulu"), // ISO 639-2 // A AAR(null, null, "Afar"), ABK(null, null, "Abkhazian"), ACE(null, null, "Achinese"), AFR(null, null, "Afrikaans"), ANP( null, null, "Angika"), ACH(null, null, "Acoli"), ADA(null, null, "Adangme"), ADY(null, null, "Adyghe", "Adygei"), AFA( null, null, "Afro-Asiatic (Other)"), AFH(null, null, "Afrihili"), AIN(null, null, "Ainu"), AKA(null, null, "Akan"), AKK(null, null, "Akkadian"), ALB(null, null, "Albanian"), ALE(null, null, "Aleut"), ALG(null, null, "Algonquian languages"), ALT(null, null, "Southern Altai"), AMH(null, null, "Amharic"), ANG(null, null, "English, Old (ca. 450-1100)"), APA(null, null, "Apache languages"), ARA(null, null, "Arabic"), ARC(null, null, "Official Aramaic (700-300 BCE)", "Imperial Aramaic (700-300 BCE)"), ARG(null, null, "Aragonese"), ARM(null, null, "Armenian"), ARN(null, null, "Mapudungun", "Mapuche"), ARP(null, null, "Arapaho"), ART(null, null, "Artificial (Other)"), ARW(null, null, "Arawak"), ASM(null, null, "Assamese"), AST(null, null, "Asturian", "Bable", "Leonese", "Asturleonese"), ATH(null, null, "Athapascan languages"), AUS(null, null, "Australian languages"), AVA(null, null, "Avaric"), AVE(null, null, "Avestan"), AWA(null, null, "Awadhi"), AYM( null, null, "Aymara"), AZE(null, null, "Azerbaijani"), // B BAD(null, null, "Banda languages"), BAI(null, null, "Bamileke languages"), BAK(null, null, "Bashkir"), BAL(null, null, "Baluchi"), BAM(null, null, "Bambara"), BAN(null, null, "Balinese"), BAQ(null, null, "Basque"), BAS(null, null, "Basa"), BAT(null, null, "Baltic (Other)"), BEJ(null, null, "Beja", "Bedawiyet"), BEM(null, null, "Bemba"), BEN( null, null, "Bengali"), BER(null, null, "Berber (Other)"), BHO(null, null, "Bhojpuri"), BIH(null, null, "Bihari languages"), BIK(null, null, "Bikol"), BIN(null, null, "Bini", "Edo"), BIS(null, null, "Bislama"), BLA( null, null, "Siksika"), BNT(null, null, "Bantu (Other)"), BOD(null, null, "Tibetan"), BOS(null, null, "Bosnian"), BRA( null, null, "Braj"), BRE(null, null, "Breton"), BTK(null, null, "Batak languages"), BUA(null, null, "Buriat"), BUG( null, null, "Buginese"), BUL(null, null, "Bulgarian"), BUR(null, null, "Burmese"), BYN(null, null, "Blin", "Bilin"), // C CAD(null, null, "Caddo"), CAI(null, null, "Central American Indian (Other)"), CAR(null, null, "Galibi Carib"), CAT( null, null, "Catalan", "Valencian"), CAU(null, null, "Caucasian (Other)"), CEB(null, null, "Cebuano"), CEL( null, null, "Celtic (Other)"), CES(null, null, "Czech"), CHA(null, null, "Chamorro"), CHB(null, null, "Chibcha"), CHE( null, null, "Chechen"), CHG(null, null, "Chagatai"), CHI(null, null, "Chinese"), CHK(null, null, "Chuukese"), CHM( null, null, "Mari"), CHN(null, null, "Chinook jargon"), CHO(null, null, "Choctaw"), CHP(null, null, "Chipewyan", "Dene Suline"), CHR(null, null, "Cherokee"), CHU(null, null, "Church Slavic", "Old Slavonic", "Church Slavonic", "Old Bulgarian", "Old Church Slavonic"), CHV(null, null, "Chuvash"), CHY(null, null, "Cheyenne"), CMC(null, null, "Chamic languages"), COP(null, null, "Coptic"), COR(null, null, "Cornish"), COS( null, null, "Corsican"), CPE(null, null, "Creoles and pidgins, English-based (Other)"), CPF(null, null, "Creoles and pidgins, French-based (Other)"), CPP(null, null, "Creoles and pidgins, Portuguese-based (Other)"), CRH( null, null, "Crimean Tatar", "Crimean Turkish"), CRE(null, null, "Cree"), CRP(null, null, "Creoles and pidgins (Other)"), CSB(null, null, "Kashubian"), CUS(null, null, "Cushitic (Other)"), CYM(null, null, "Welsh"), CZE(null, null, "Czech"), // D DAK(null, null, "Dakota"), DAN(null, null, "Danish"), DAR(null, null, "Dargwa"), DAY(null, null, "Land Dayak languages"), DEL(null, null, "Delaware"), DEN(null, null, "Slave (Athapascan)"), DEU(null, null, "German"), DGR(null, null, "Dogrib"), DIN(null, null, "Dinka"), DIV(null, null, "Divehi", "Dhivehi", "Maldivian"), DOI(null, null, "Dogri"), DRA(null, null, "Dravidian (Other)"), DSB(null, null, "Lower Sorbian"), DUA( null, null, "Duala"), DUM(null, null, "Dutch, Middle (ca. 1050-1350)"), DUT(null, null, "Dutch", "Flemish"), DYU( null, null, "Dyula"), DZO(null, null, "Dzongkha"), // E EFI(null, null, "Efik"), EGY(null, null, "Egyptian (Ancient)"), EKA(null, null, "Ekajuk"), ELL(null, null, "Greek, Modern (1453-)"), ELX(null, null, "Elamite"), ENG(null, null, "English"), ENM(null, null, "English, Middle (1100-1500)"), EPO(null, null, "Esperanto"), EST(null, null, "Estonian"), EUS(null, null, "Basque"), EWE(null, null, "Ewe"), EWO(null, null, "Ewondo"), // F FAN(null, null, "Fang"), FAO(null, null, "Faroese"), FAS(null, null, "Persian"), FAT(null, null, "Fanti"), FIJ( null, null, "Fijian"), FIL(null, null, "Filipino", "Pilipino"), FIN(null, null, "Finnish"), FIU(null, null, "Finno-Ugrian (Other)"), FON(null, null, "Fon"), FRA(null, null, "French"), FRE(null, null, "French"), FRM( null, null, "French, Middle (ca. 1400-1600)"), FRO(null, null, "French, Old (842-ca. 1400)"), FRR(null, null, "Northern Frisian"), FRS(null, null, "Eastern Frisian"), FRY(null, null, "Western Frisian"), FUL(null, null, "Fulah"), FUR(null, null, "Friulian"), // G GAA(null, null, "Ga"), GAY(null, null, "Gayo"), GBA(null, null, "Gbaya"), GEM(null, null, "Germanic (Other)"), GEO( null, null, "Georgian"), GER(null, null, "German"), GEZ(null, null, "Geez"), GIL(null, null, "Gilbertese"), GLA( null, null, "Gaelic", "Scottish Gaelic"), GLE(null, null, "Irish"), GLG(null, null, "Galician"), GLV(null, null, "Manx"), GMH(null, null, "German, Middle High (ca. 1050-1500)"), GOH(null, null, "German, Old High (ca. 750-1050)"), GON(null, null, "Gondi"), GOR(null, null, "Gorontalo"), GOT(null, null, "Gothic"), GRB(null, null, "Grebo"), GRC(null, null, "Greek, Ancient (to 1453)"), GRE(null, null, "Greek, Modern (1453-)"), GRN(null, null, "Guarani"), GSW(null, null, "Swiss German", "Alemannic"), GUJ(null, null, "Gujarati"), GWI(null, null, "Gwich&#xB4;in"), // H HAI(null, null, "Haida"), HAU(null, null, "Hausa"), HAW(null, null, "Hawaiian"), HAT(null, null, "Haitian", "Haitian Creole"), HEB(null, null, "Hebrew"), HER(null, null, "Herero"), HIL(null, null, "Hiligaynon"), HIM( null, null, "Himachali"), HIN(null, null, "Hindi"), HIT(null, null, "Hittite"), HMN(null, null, "Hmong"), HMO( null, null, "Hiri Motu"), HRV(null, null, "Croatian"), HSB(null, null, "Upper Sorbian"), HUN(null, null, "Hungarian"), HUP(null, null, "Hupa"), HYE(null, null, "Armenian"), // I IBA(null, null, "Iban"), IBO(null, null, "Igbo"), III(null, null, "Sichuan Yi", "Nuosu"), IJO(null, null, "Ijo languages"), ILE(null, null, "Interlingue", "Occidental"), ILO(null, null, "Iloko"), INC(null, null, "Indic (Other)"), INE(null, null, "Indo-European (Other)"), INH(null, null, "Ingush"), IRA(null, null, "Iranian (Other)"), IRO(null, null, "Iroquoian languages"), ITA(null, null, "Italian"), // J JAV(null, null, "Javanese"), JBO(null, null, "Lojban"), JPN(null, null, "Japanese"), JPR(null, null, "Judeo-Persian"), JRB(null, null, "Judeo-Arabic"), // K KAA(null, null, "Kara-Kalpak"), KAB(null, null, "Kabyle"), KAC(null, null, "Kachin", "Jingpho"), KAL(null, null, "Kalaallisut", "Greenlandic"), KAM(null, null, "Kamba"), KAR(null, null, "Karen languages"), KAW(null, null, "Kawi"), KBD(null, null, "Kabardian"), KHA(null, null, "Khasi"), KHI(null, null, "Khoisan (Other)"), KHO(null, null, "Khotanese"), KIK(null, null, "Kikuyu", "Gikuyu"), KIR(null, null, "Kirghiz", "Kyrgyz"), KMB(null, null, "Kimbundu"), KOK(null, null, "Konkani"), KOS(null, null, "Kosraean"), KPE(null, null, "Kpelle"), KRC(null, null, "Karachay-Balkar"), KRL(null, null, "Karelian"), KRO(null, null, "Kru languages"), KRU(null, null, "Kurukh"), KUA(null, null, "Kuanyama", "Kwanyama"), KUM(null, null, "Kumyk"), KUT(null, null, "Kutenai"), // L LAD(null, null, "Ladino"), LAH(null, null, "Lahnda"), LAM(null, null, "Lamba"), LEZ(null, null, "Lezghian"), LIM( null, null, "Limburgan", "Limburger", "Limburgish"), LOL(null, null, "Mongo"), LOZ(null, null, "Lozi"), LUA( null, null, "Luba-Lulua"), LUI(null, null, "Luiseno"), LUN(null, null, "Lunda"), LUO(null, null, "Luo (Kenya and Tanzania)"), LUS(null, null, "Lushai"), // M MAD(null, null, "Madurese"), MAG(null, null, "Magahi"), MAI(null, null, "Maithili"), MAK(null, null, "Makasar"), MAN( null, null, "Mandingo"), MAP(null, null, "Austronesian (Other)"), MAS(null, null, "Masai"), MDF(null, null, "Moksha"), MDR(null, null, "Mandar"), MEN(null, null, "Mende"), MGA(null, null, "Irish, Middle (900-1200)"), MIC( null, null, "Mi'kmaq", "Micmac"), MIN(null, null, "Minangkabau"), MIS(null, null, "Uncoded languages"), MKH( null, null, "Mon-Khmer (Other)"), MNC(null, null, "Manchu"), MNI(null, null, "Manipuri"), MNO(null, null, "Manobo languages"), MOH(null, null, "Mohawk"), MOS(null, null, "Mossi"), MUL(null, null, "Multiple languages"), MUN( null, null, "Munda languages"), MUS(null, null, "Creek"), MWL(null, null, "Mirandese"), MWR(null, null, "Marwari"), MYN(null, null, "Mayan languages"), MYV(null, null, "Erzya"), // N NAH(null, null, "Nahuatl languages"), NAI(null, null, "North American Indian"), NAP(null, null, "Neapolitan"), NAU( null, null, "Nauru"), NAV(null, null, "Navajo", "Navaho"), NBL(null, null, "Ndebele, South", "South Ndebele"), NDE( null, null, "Ndebele, North", "North Ndebele"), NDS(null, null, "Low German", "Low Saxon", "German, Low", "Saxon, Low"), NEW(null, null, "Nepal Bhasa", "Newari"), NIA(null, null, "Nias"), NIC(null, null, "Niger-Kordofanian (Other)"), NIU(null, null, "Niuean"), NNO(null, null, "Norwegian Nynorsk", "Nynorsk, Norwegian"), NOG(null, null, "Nogai"), NON(null, null, "Norse, Old"), NQO(null, null, "N&#x2019;Ko"), NSO( null, null, "Northern Sotho", "Pedi", "Sepedi"), NUB(null, null, "Nubian languages"), NWC(null, null, "Classical Newari", "Old Newari", "Classical Nepal Bhasa"), NYA(null, null, "Chichewa", "Chewa", "Nyanja"), NYM( null, null, "Nyamwezi"), NYN(null, null, "Nyankole"), NYO(null, null, "Nyoro"), NZI(null, null, "Nzima"), // O OCI(null, null, "Occitan"), OJI(null, null, "Ojibwa"), ORI(null, null, "Oriya"), ORM(null, null, "Oromo"), OSA( null, null, "Osage"), OSS(null, null, "Ossetian", "Ossetic"), OTA(null, null, "Turkish, Ottoman (1500-1928)"), OTO( null, null, "Otomian languages"), // P PAA(null, null, "Papuan (Other)"), PAG(null, null, "Pangasinan"), PAL(null, null, "Pahlavi"), PAM(null, null, "Pampanga", "Kapampangan"), PAN(null, null, "Panjabi", "Punjabi"), PAP(null, null, "Papiamento"), PAU(null, null, "Palauan"), PEO(null, null, "Persian, Old (ca. 600-400 B.C.)"), PHI(null, null, "Philippine (Other)"), PHN( null, null, "Phoenician"), PON(null, null, "Pohnpeian"), POR(null, null, "Portuguese"), PRA(null, null, "Prakrit languages"), PRO(null, null, "Proven&#xE7;al, Old (to 1500)"), PUS(null, null, "Pushto", "Pashto"), // Q QAA(null, null, "PRIVATE USE"), QAB(null, null, "PRIVATE USE"), QAC(null, null, "PRIVATE USE"), QAD(null, null, "PRIVATE USE"), QAE(null, null, "PRIVATE USE"), QAF(null, null, "PRIVATE USE"), QAG(null, null, "PRIVATE USE"), QAH( null, null, "PRIVATE USE"), QAI(null, null, "PRIVATE USE"), QAJ(null, null, "PRIVATE USE"), QAK(null, null, "PRIVATE USE"), QAL(null, null, "PRIVATE USE"), QAM(null, null, "PRIVATE USE"), QAN(null, null, "PRIVATE USE"), QAO( null, null, "PRIVATE USE"), QAP(null, null, "PRIVATE USE"), QAQ(null, null, "PRIVATE USE"), QAR(null, null, "PRIVATE USE"), QAS(null, null, "PRIVATE USE"), QAT(null, null, "PRIVATE USE"), QAU(null, null, "PRIVATE USE"), QAV( null, null, "PRIVATE USE"), QAW(null, null, "PRIVATE USE"), QAX(null, null, "PRIVATE USE"), QAY(null, null, "PRIVATE USE"), QAZ(null, null, "PRIVATE USE"), QBA(null, null, "PRIVATE USE"), QBB(null, null, "PRIVATE USE"), QBC( null, null, "PRIVATE USE"), QBD(null, null, "PRIVATE USE"), QBE(null, null, "PRIVATE USE"), QBF(null, null, "PRIVATE USE"), QBG(null, null, "PRIVATE USE"), QBH(null, null, "PRIVATE USE"), QBI(null, null, "PRIVATE USE"), QBJ( null, null, "PRIVATE USE"), QBK(null, null, "PRIVATE USE"), QBL(null, null, "PRIVATE USE"), QBM(null, null, "PRIVATE USE"), QBN(null, null, "PRIVATE USE"), QBO(null, null, "PRIVATE USE"), QBP(null, null, "PRIVATE USE"), QBQ( null, null, "PRIVATE USE"), QBR(null, null, "PRIVATE USE"), QBS(null, null, "PRIVATE USE"), QBT(null, null, "PRIVATE USE"), QBU(null, null, "PRIVATE USE"), QBV(null, null, "PRIVATE USE"), QBW(null, null, "PRIVATE USE"), QBX( null, null, "PRIVATE USE"), QBY(null, null, "PRIVATE USE"), QBZ(null, null, "PRIVATE USE"), QCA(null, null, "PRIVATE USE"), QCB(null, null, "PRIVATE USE"), QCC(null, null, "PRIVATE USE"), QCD(null, null, "PRIVATE USE"), QCE( null, null, "PRIVATE USE"), QCF(null, null, "PRIVATE USE"), QCG(null, null, "PRIVATE USE"), QCH(null, null, "PRIVATE USE"), QCI(null, null, "PRIVATE USE"), QCJ(null, null, "PRIVATE USE"), QCK(null, null, "PRIVATE USE"), QCL( null, null, "PRIVATE USE"), QCM(null, null, "PRIVATE USE"), QCN(null, null, "PRIVATE USE"), QCO(null, null, "PRIVATE USE"), QCP(null, null, "PRIVATE USE"), QCQ(null, null, "PRIVATE USE"), QCR(null, null, "PRIVATE USE"), QCS( null, null, "PRIVATE USE"), QCT(null, null, "PRIVATE USE"), QCU(null, null, "PRIVATE USE"), QCV(null, null, "PRIVATE USE"), QCW(null, null, "PRIVATE USE"), QCX(null, null, "PRIVATE USE"), QCY(null, null, "PRIVATE USE"), QCZ( null, null, "PRIVATE USE"), QDA(null, null, "PRIVATE USE"), QDB(null, null, "PRIVATE USE"), QDC(null, null, "PRIVATE USE"), QDD(null, null, "PRIVATE USE"), QDE(null, null, "PRIVATE USE"), QDF(null, null, "PRIVATE USE"), QDG( null, null, "PRIVATE USE"), QDH(null, null, "PRIVATE USE"), QDI(null, null, "PRIVATE USE"), QDJ(null, null, "PRIVATE USE"), QDK(null, null, "PRIVATE USE"), QDL(null, null, "PRIVATE USE"), QDM(null, null, "PRIVATE USE"), QDN( null, null, "PRIVATE USE"), QDO(null, null, "PRIVATE USE"), QDP(null, null, "PRIVATE USE"), QDQ(null, null, "PRIVATE USE"), QDR(null, null, "PRIVATE USE"), QDS(null, null, "PRIVATE USE"), QDT(null, null, "PRIVATE USE"), QDU( null, null, "PRIVATE USE"), QDV(null, null, "PRIVATE USE"), QDW(null, null, "PRIVATE USE"), QDX(null, null, "PRIVATE USE"), QDY(null, null, "PRIVATE USE"), QDZ(null, null, "PRIVATE USE"), QEA(null, null, "PRIVATE USE"), QEB( null, null, "PRIVATE USE"), QEC(null, null, "PRIVATE USE"), QED(null, null, "PRIVATE USE"), QEE(null, null, "PRIVATE USE"), QEF(null, null, "PRIVATE USE"), QEG(null, null, "PRIVATE USE"), QEH(null, null, "PRIVATE USE"), QEI( null, null, "PRIVATE USE"), QEJ(null, null, "PRIVATE USE"), QEK(null, null, "PRIVATE USE"), QEL(null, null, "PRIVATE USE"), QEM(null, null, "PRIVATE USE"), QEN(null, null, "PRIVATE USE"), QEO(null, null, "PRIVATE USE"), QEP( null, null, "PRIVATE USE"), QEQ(null, null, "PRIVATE USE"), QER(null, null, "PRIVATE USE"), QES(null, null, "PRIVATE USE"), QET(null, null, "PRIVATE USE"), QEU(null, null, "PRIVATE USE"), QEV(null, null, "PRIVATE USE"), QEW( null, null, "PRIVATE USE"), QEX(null, null, "PRIVATE USE"), QEY(null, null, "PRIVATE USE"), QEZ(null, null, "PRIVATE USE"), QFA(null, null, "PRIVATE USE"), QFB(null, null, "PRIVATE USE"), QFC(null, null, "PRIVATE USE"), QFD( null, null, "PRIVATE USE"), QFE(null, null, "PRIVATE USE"), QFF(null, null, "PRIVATE USE"), QFG(null, null, "PRIVATE USE"), QFH(null, null, "PRIVATE USE"), QFI(null, null, "PRIVATE USE"), QFJ(null, null, "PRIVATE USE"), QFK( null, null, "PRIVATE USE"), QFL(null, null, "PRIVATE USE"), QFM(null, null, "PRIVATE USE"), QFN(null, null, "PRIVATE USE"), QFO(null, null, "PRIVATE USE"), QFP(null, null, "PRIVATE USE"), QFQ(null, null, "PRIVATE USE"), QFR( null, null, "PRIVATE USE"), QFS(null, null, "PRIVATE USE"), QFT(null, null, "PRIVATE USE"), QFU(null, null, "PRIVATE USE"), QFV(null, null, "PRIVATE USE"), QFW(null, null, "PRIVATE USE"), QFX(null, null, "PRIVATE USE"), QFY( null, null, "PRIVATE USE"), QFZ(null, null, "PRIVATE USE"), QGA(null, null, "PRIVATE USE"), QGB(null, null, "PRIVATE USE"), QGC(null, null, "PRIVATE USE"), QGD(null, null, "PRIVATE USE"), QGE(null, null, "PRIVATE USE"), QGF( null, null, "PRIVATE USE"), QGG(null, null, "PRIVATE USE"), QGH(null, null, "PRIVATE USE"), QGI(null, null, "PRIVATE USE"), QGJ(null, null, "PRIVATE USE"), QGK(null, null, "PRIVATE USE"), QGL(null, null, "PRIVATE USE"), QGM( null, null, "PRIVATE USE"), QGN(null, null, "PRIVATE USE"), QGO(null, null, "PRIVATE USE"), QGP(null, null, "PRIVATE USE"), QGQ(null, null, "PRIVATE USE"), QGR(null, null, "PRIVATE USE"), QGS(null, null, "PRIVATE USE"), QGT( null, null, "PRIVATE USE"), QGU(null, null, "PRIVATE USE"), QGV(null, null, "PRIVATE USE"), QGW(null, null, "PRIVATE USE"), QGX(null, null, "PRIVATE USE"), QGY(null, null, "PRIVATE USE"), QGZ(null, null, "PRIVATE USE"), QHA( null, null, "PRIVATE USE"), QHB(null, null, "PRIVATE USE"), QHC(null, null, "PRIVATE USE"), QHD(null, null, "PRIVATE USE"), QHE(null, null, "PRIVATE USE"), QHF(null, null, "PRIVATE USE"), QHG(null, null, "PRIVATE USE"), QHH( null, null, "PRIVATE USE"), QHI(null, null, "PRIVATE USE"), QHJ(null, null, "PRIVATE USE"), QHK(null, null, "PRIVATE USE"), QHL(null, null, "PRIVATE USE"), QHM(null, null, "PRIVATE USE"), QHN(null, null, "PRIVATE USE"), QHO( null, null, "PRIVATE USE"), QHP(null, null, "PRIVATE USE"), QHQ(null, null, "PRIVATE USE"), QHR(null, null, "PRIVATE USE"), QHS(null, null, "PRIVATE USE"), QHT(null, null, "PRIVATE USE"), QHU(null, null, "PRIVATE USE"), QHV( null, null, "PRIVATE USE"), QHW(null, null, "PRIVATE USE"), QHX(null, null, "PRIVATE USE"), QHY(null, null, "PRIVATE USE"), QHZ(null, null, "PRIVATE USE"), QIA(null, null, "PRIVATE USE"), QIB(null, null, "PRIVATE USE"), QIC( null, null, "PRIVATE USE"), QID(null, null, "PRIVATE USE"), QIE(null, null, "PRIVATE USE"), QIF(null, null, "PRIVATE USE"), QIG(null, null, "PRIVATE USE"), QIH(null, null, "PRIVATE USE"), QII(null, null, "PRIVATE USE"), QIJ( null, null, "PRIVATE USE"), QIK(null, null, "PRIVATE USE"), QIL(null, null, "PRIVATE USE"), QIM(null, null, "PRIVATE USE"), QIN(null, null, "PRIVATE USE"), QIO(null, null, "PRIVATE USE"), QIP(null, null, "PRIVATE USE"), QIQ( null, null, "PRIVATE USE"), QIR(null, null, "PRIVATE USE"), QIS(null, null, "PRIVATE USE"), QIT(null, null, "PRIVATE USE"), QIU(null, null, "PRIVATE USE"), QIV(null, null, "PRIVATE USE"), QIW(null, null, "PRIVATE USE"), QIX( null, null, "PRIVATE USE"), QIY(null, null, "PRIVATE USE"), QIZ(null, null, "PRIVATE USE"), QJA(null, null, "PRIVATE USE"), QJB(null, null, "PRIVATE USE"), QJC(null, null, "PRIVATE USE"), QJD(null, null, "PRIVATE USE"), QJE( null, null, "PRIVATE USE"), QJF(null, null, "PRIVATE USE"), QJG(null, null, "PRIVATE USE"), QJH(null, null, "PRIVATE USE"), QJI(null, null, "PRIVATE USE"), QJJ(null, null, "PRIVATE USE"), QJK(null, null, "PRIVATE USE"), QJL( null, null, "PRIVATE USE"), QJM(null, null, "PRIVATE USE"), QJN(null, null, "PRIVATE USE"), QJO(null, null, "PRIVATE USE"), QJP(null, null, "PRIVATE USE"), QJQ(null, null, "PRIVATE USE"), QJR(null, null, "PRIVATE USE"), QJS( null, null, "PRIVATE USE"), QJT(null, null, "PRIVATE USE"), QJU(null, null, "PRIVATE USE"), QJV(null, null, "PRIVATE USE"), QJW(null, null, "PRIVATE USE"), QJX(null, null, "PRIVATE USE"), QJY(null, null, "PRIVATE USE"), QJZ( null, null, "PRIVATE USE"), QKA(null, null, "PRIVATE USE"), QKB(null, null, "PRIVATE USE"), QKC(null, null, "PRIVATE USE"), QKD(null, null, "PRIVATE USE"), QKE(null, null, "PRIVATE USE"), QKF(null, null, "PRIVATE USE"), QKG( null, null, "PRIVATE USE"), QKH(null, null, "PRIVATE USE"), QKI(null, null, "PRIVATE USE"), QKJ(null, null, "PRIVATE USE"), QKK(null, null, "PRIVATE USE"), QKL(null, null, "PRIVATE USE"), QKM(null, null, "PRIVATE USE"), QKN( null, null, "PRIVATE USE"), QKO(null, null, "PRIVATE USE"), QKP(null, null, "PRIVATE USE"), QKQ(null, null, "PRIVATE USE"), QKR(null, null, "PRIVATE USE"), QKS(null, null, "PRIVATE USE"), QKT(null, null, "PRIVATE USE"), QKU( null, null, "PRIVATE USE"), QKV(null, null, "PRIVATE USE"), QKW(null, null, "PRIVATE USE"), QKX(null, null, "PRIVATE USE"), QKY(null, null, "PRIVATE USE"), QKZ(null, null, "PRIVATE USE"), QLA(null, null, "PRIVATE USE"), QLB( null, null, "PRIVATE USE"), QLC(null, null, "PRIVATE USE"), QLD(null, null, "PRIVATE USE"), QLE(null, null, "PRIVATE USE"), QLF(null, null, "PRIVATE USE"), QLG(null, null, "PRIVATE USE"), QLH(null, null, "PRIVATE USE"), QLI( null, null, "PRIVATE USE"), QLJ(null, null, "PRIVATE USE"), QLK(null, null, "PRIVATE USE"), QLL(null, null, "PRIVATE USE"), QLM(null, null, "PRIVATE USE"), QLN(null, null, "PRIVATE USE"), QLO(null, null, "PRIVATE USE"), QLP( null, null, "PRIVATE USE"), QLQ(null, null, "PRIVATE USE"), QLR(null, null, "PRIVATE USE"), QLS(null, null, "PRIVATE USE"), QLT(null, null, "PRIVATE USE"), QLU(null, null, "PRIVATE USE"), QLV(null, null, "PRIVATE USE"), QLW( null, null, "PRIVATE USE"), QLX(null, null, "PRIVATE USE"), QLY(null, null, "PRIVATE USE"), QLZ(null, null, "PRIVATE USE"), QMA(null, null, "PRIVATE USE"), QMB(null, null, "PRIVATE USE"), QMC(null, null, "PRIVATE USE"), QMD( null, null, "PRIVATE USE"), QME(null, null, "PRIVATE USE"), QMF(null, null, "PRIVATE USE"), QMG(null, null, "PRIVATE USE"), QMH(null, null, "PRIVATE USE"), QMI(null, null, "PRIVATE USE"), QMJ(null, null, "PRIVATE USE"), QMK( null, null, "PRIVATE USE"), QML(null, null, "PRIVATE USE"), QMM(null, null, "PRIVATE USE"), QMN(null, null, "PRIVATE USE"), QMO(null, null, "PRIVATE USE"), QMP(null, null, "PRIVATE USE"), QMQ(null, null, "PRIVATE USE"), QMR( null, null, "PRIVATE USE"), QMS(null, null, "PRIVATE USE"), QMT(null, null, "PRIVATE USE"), QMU(null, null, "PRIVATE USE"), QMV(null, null, "PRIVATE USE"), QMW(null, null, "PRIVATE USE"), QMX(null, null, "PRIVATE USE"), QMY( null, null, "PRIVATE USE"), QMZ(null, null, "PRIVATE USE"), QNA(null, null, "PRIVATE USE"), QNB(null, null, "PRIVATE USE"), QNC(null, null, "PRIVATE USE"), QND(null, null, "PRIVATE USE"), QNE(null, null, "PRIVATE USE"), QNF( null, null, "PRIVATE USE"), QNG(null, null, "PRIVATE USE"), QNH(null, null, "PRIVATE USE"), QNI(null, null, "PRIVATE USE"), QNJ(null, null, "PRIVATE USE"), QNK(null, null, "PRIVATE USE"), QNL(null, null, "PRIVATE USE"), QNM( null, null, "PRIVATE USE"), QNN(null, null, "PRIVATE USE"), QNO(null, null, "PRIVATE USE"), QNP(null, null, "PRIVATE USE"), QNQ(null, null, "PRIVATE USE"), QNR(null, null, "PRIVATE USE"), QNS(null, null, "PRIVATE USE"), QNT( null, null, "PRIVATE USE"), QNU(null, null, "PRIVATE USE"), QNV(null, null, "PRIVATE USE"), QNW(null, null, "PRIVATE USE"), QNX(null, null, "PRIVATE USE"), QNY(null, null, "PRIVATE USE"), QNZ(null, null, "PRIVATE USE"), QOA( null, null, "PRIVATE USE"), QOB(null, null, "PRIVATE USE"), QOC(null, null, "PRIVATE USE"), QOD(null, null, "PRIVATE USE"), QOE(null, null, "PRIVATE USE"), QOF(null, null, "PRIVATE USE"), QOG(null, null, "PRIVATE USE"), QOH( null, null, "PRIVATE USE"), QOI(null, null, "PRIVATE USE"), QOJ(null, null, "PRIVATE USE"), QOK(null, null, "PRIVATE USE"), QOL(null, null, "PRIVATE USE"), QOM(null, null, "PRIVATE USE"), QON(null, null, "PRIVATE USE"), QOO( null, null, "PRIVATE USE"), QOP(null, null, "PRIVATE USE"), QOQ(null, null, "PRIVATE USE"), QOR(null, null, "PRIVATE USE"), QOS(null, null, "PRIVATE USE"), QOT(null, null, "PRIVATE USE"), QOU(null, null, "PRIVATE USE"), QOV( null, null, "PRIVATE USE"), QOW(null, null, "PRIVATE USE"), QOX(null, null, "PRIVATE USE"), QOY(null, null, "PRIVATE USE"), QOZ(null, null, "PRIVATE USE"), QPA(null, null, "PRIVATE USE"), QPB(null, null, "PRIVATE USE"), QPC( null, null, "PRIVATE USE"), QPD(null, null, "PRIVATE USE"), QPE(null, null, "PRIVATE USE"), QPF(null, null, "PRIVATE USE"), QPG(null, null, "PRIVATE USE"), QPH(null, null, "PRIVATE USE"), QPI(null, null, "PRIVATE USE"), QPJ( null, null, "PRIVATE USE"), QPK(null, null, "PRIVATE USE"), QPL(null, null, "PRIVATE USE"), QPM(null, null, "PRIVATE USE"), QPN(null, null, "PRIVATE USE"), QPO(null, null, "PRIVATE USE"), QPP(null, null, "PRIVATE USE"), QPQ( null, null, "PRIVATE USE"), QPR(null, null, "PRIVATE USE"), QPS(null, null, "PRIVATE USE"), QPT(null, null, "PRIVATE USE"), QPU(null, null, "PRIVATE USE"), QPV(null, null, "PRIVATE USE"), QPW(null, null, "PRIVATE USE"), QPX( null, null, "PRIVATE USE"), QPY(null, null, "PRIVATE USE"), QPZ(null, null, "PRIVATE USE"), QQA(null, null, "PRIVATE USE"), QQB(null, null, "PRIVATE USE"), QQC(null, null, "PRIVATE USE"), QQD(null, null, "PRIVATE USE"), QQE( null, null, "PRIVATE USE"), QQF(null, null, "PRIVATE USE"), QQG(null, null, "PRIVATE USE"), QQH(null, null, "PRIVATE USE"), QQI(null, null, "PRIVATE USE"), QQJ(null, null, "PRIVATE USE"), QQK(null, null, "PRIVATE USE"), QQL( null, null, "PRIVATE USE"), QQM(null, null, "PRIVATE USE"), QQN(null, null, "PRIVATE USE"), QQO(null, null, "PRIVATE USE"), QQP(null, null, "PRIVATE USE"), QQQ(null, null, "PRIVATE USE"), QQR(null, null, "PRIVATE USE"), QQS( null, null, "PRIVATE USE"), QQT(null, null, "PRIVATE USE"), QQU(null, null, "PRIVATE USE"), QQV(null, null, "PRIVATE USE"), QQW(null, null, "PRIVATE USE"), QQX(null, null, "PRIVATE USE"), QQY(null, null, "PRIVATE USE"), QQZ( null, null, "PRIVATE USE"), QRA(null, null, "PRIVATE USE"), QRB(null, null, "PRIVATE USE"), QRC(null, null, "PRIVATE USE"), QRD(null, null, "PRIVATE USE"), QRE(null, null, "PRIVATE USE"), QRF(null, null, "PRIVATE USE"), QRG( null, null, "PRIVATE USE"), QRH(null, null, "PRIVATE USE"), QRI(null, null, "PRIVATE USE"), QRJ(null, null, "PRIVATE USE"), QRK(null, null, "PRIVATE USE"), QRL(null, null, "PRIVATE USE"), QRM(null, null, "PRIVATE USE"), QRN( null, null, "PRIVATE USE"), QRO(null, null, "PRIVATE USE"), QRP(null, null, "PRIVATE USE"), QRQ(null, null, "PRIVATE USE"), QRR(null, null, "PRIVATE USE"), QRS(null, null, "PRIVATE USE"), QRT(null, null, "PRIVATE USE"), QRU( null, null, "PRIVATE USE"), QRV(null, null, "PRIVATE USE"), QRW(null, null, "PRIVATE USE"), QRX(null, null, "PRIVATE USE"), QRY(null, null, "PRIVATE USE"), QRZ(null, null, "PRIVATE USE"), QSA(null, null, "PRIVATE USE"), QSB( null, null, "PRIVATE USE"), QSC(null, null, "PRIVATE USE"), QSD(null, null, "PRIVATE USE"), QSE(null, null, "PRIVATE USE"), QSF(null, null, "PRIVATE USE"), QSG(null, null, "PRIVATE USE"), QSH(null, null, "PRIVATE USE"), QSI( null, null, "PRIVATE USE"), QSJ(null, null, "PRIVATE USE"), QSK(null, null, "PRIVATE USE"), QSL(null, null, "PRIVATE USE"), QSM(null, null, "PRIVATE USE"), QSN(null, null, "PRIVATE USE"), QSO(null, null, "PRIVATE USE"), QSP( null, null, "PRIVATE USE"), QSQ(null, null, "PRIVATE USE"), QSR(null, null, "PRIVATE USE"), QSS(null, null, "PRIVATE USE"), QST(null, null, "PRIVATE USE"), QSU(null, null, "PRIVATE USE"), QSV(null, null, "PRIVATE USE"), QSW( null, null, "PRIVATE USE"), QSX(null, null, "PRIVATE USE"), QSY(null, null, "PRIVATE USE"), QSZ(null, null, "PRIVATE USE"), QTA(null, null, "PRIVATE USE"), QTB(null, null, "PRIVATE USE"), QTC(null, null, "PRIVATE USE"), QTD( null, null, "PRIVATE USE"), QTE(null, null, "PRIVATE USE"), QTF(null, null, "PRIVATE USE"), QTG(null, null, "PRIVATE USE"), QTH(null, null, "PRIVATE USE"), QTI(null, null, "PRIVATE USE"), QTJ(null, null, "PRIVATE USE"), QTK( null, null, "PRIVATE USE"), QTL(null, null, "PRIVATE USE"), QTM(null, null, "PRIVATE USE"), QTN(null, null, "PRIVATE USE"), QTO(null, null, "PRIVATE USE"), QTP(null, null, "PRIVATE USE"), QTQ(null, null, "PRIVATE USE"), QTR( null, null, "PRIVATE USE"), QTS(null, null, "PRIVATE USE"), QTT(null, null, "PRIVATE USE"), QTU(null, null, "PRIVATE USE"), QTV(null, null, "PRIVATE USE"), QTW(null, null, "PRIVATE USE"), QTX(null, null, "PRIVATE USE"), QTY( null, null, "PRIVATE USE"), QTZ(null, null, "PRIVATE USE"), // R RAJ(null, null, "Rajasthani"), RAP(null, null, "Rapanui"), RAR(null, null, "Rarotongan", "Cook Islands Maori"), ROA( null, null, "Romance (Other)"), ROH(null, null, "Romansh"), ROM(null, null, "Romany"), RON(null, null, "Romanian", "Moldavian", "Moldovan"), RUM(null, null, "Romanian", "Moldavian", "Moldovan"), RUN(null, null, "Rundi"), RUP(null, null, "Aromanian", "Arumanian", "Macedo-Romanian"), RUS(null, null, "Russian"), // S SAD(null, null, "Sandawe"), SAH(null, null, "Yakut"), SAI(null, null, "South American Indian (Other)"), SAL(null, null, "Salishan languages"), SAM(null, null, "Samaritan Aramaic"), SAS(null, null, "Sasak"), SAT(null, null, "Santali"), SCN(null, null, "Sicilian"), SCO(null, null, "Scots"), SEL(null, null, "Selkup"), SEM(null, null, "Semitic (Other)"), SGA(null, null, "Irish, Old (to 900)"), SGN(null, null, "Sign Languages"), SHN(null, null, "Shan"), SID(null, null, "Sidamo"), SIN(null, null, "Sinhala", "Sinhalese"), SIO(null, null, "Siouan languages"), SIT( null, null, "Sino-Tibetan (Other)"), SLA(null, null, "Slavic (Other)"), SMA(null, null, "Southern Sami"), SMI( null, null, "Sami languages (Other)"), SMJ(null, null, "Lule Sami"), SMN(null, null, "Inari Sami"), SMS(null, null, "Skolt Sami"), SNK(null, null, "Soninke"), SOG(null, null, "Sogdian"), SON(null, null, "Songhai languages"), SPA(null, null, "Spanish", "Castilian"), SRN(null, null, "Sranan Tongo"), SRR(null, null, "Serer"), SSA(null, null, "Nilo-Saharan (Other)"), SUK(null, null, "Sukuma"), SUS(null, null, "Susu"), SUX( null, null, "Sumerian"), SYC(null, null, "Classical Syriac"), SYR(null, null, "Syriac"), // T TAH(null, null, "Tahitian"), TAI(null, null, "Tai (Other)"), TAM(null, null, "Tamil"), TAT(null, null, "Tatar"), TEM( null, null, "Timne"), TER(null, null, "Tereno"), TET(null, null, "Tetum"), TIG(null, null, "Tigre"), TIV(null, null, "Tiv"), TKL(null, null, "Tokelau"), TLH(null, null, "Klingon", "tlhIngan-Hol"), TLI(null, null, "Tlingit"), TMH( null, null, "Tamashek"), TOG(null, null, "Tonga (Nyasa)"), TPI(null, null, "Tok Pisin"), TSI(null, null, "Tsimshian"), TUK(null, null, "Turkmen"), TUM(null, null, "Tumbuka"), TUP(null, null, "Tupi languages"), TUR( null, null, "Turkish"), TSO(null, null, "Tsonga"), TUT(null, null, "Altaic (Other)"), TVL(null, null, "Tuvalu"), TWI( null, null, "Twi"), TYV(null, null, "Tuvinian"), // U UDM(null, null, "Udmurt"), UGA(null, null, "Ugaritic"), UIG(null, null, "Uighur", "Uyghur"), UKR(null, null, "Ukrainian"), UMB(null, null, "Umbundu"), UND(null, null, "Undetermined"), URD(null, null, "Urdu"), UZB(null, null, "Uzbek"), // V VAI(null, null, "Vai"), VEN(null, null, "Venda"), VIE(null, null, "Vietnamese"), VOT(null, null, "Votic"), // W WAK(null, null, "Wakashan languages"), WAL(null, null, "Walamo"), WAR(null, null, "Waray"), WAS(null, null, "Washo"), WEL( null, null, "Welsh"), WEN(null, null, "Sorbian languages"), WLN(null, null, "Walloon"), WOL(null, null, "Wolof"), // X XAL(null, null, "Kalmyk", "Oirat"), XHO(null, null, "Xhosa"), // Y YAO(null, null, "Yao"), YAP(null, null, "Yapese"), YID(null, null, "Yiddish"), YOR(null, null, "Yoruba"), YPK(null, null, "Yupik languages"), // Z ZAP(null, null, "Zapotec"), ZBL(null, null, "Blissymbols", "Blissymbolics", "Bliss"), ZEN(null, null, "Zenaga"), ZHA( null, null, "Zhuang", "Chuang"), ZHO(null, null, "Chinese"), ZND(null, null, "Zande languages"), ZUL(null, null, "Zulu"), ZUN(null, null, "Zuni"), ZXX(null, null, "No linguistic content"), ZZA(null, null, "Zaza", "Dimili", "Dimli", "Kirdki", "Kirmanjki", "Zazaki"); private final String deprecated; private final String preferred; private final String[] descriptions; private Language(String dep, String pref, String... desc) { this.deprecated = dep; this.preferred = pref; this.descriptions = desc; } public String getDeprecated() { return deprecated; } public boolean isDeprecated() { return deprecated != null; } public String getPreferredValue() { return preferred; } public Language getPreferred() { return preferred != null ? valueOf(preferred.toUpperCase(Locale.US)) : this; } public String getSuppressScript() { return null; } public String getDescription() { return descriptions.length > 0 ? descriptions[0] : null; } public String[] getDescriptions() { return descriptions; } public Subtag newSubtag() { return new Subtag(this); } public static Language valueOf(Subtag subtag) { if (subtag == null) return null; if (subtag.getType() == Subtag.Type.PRIMARY) return valueOf(subtag.getName().toUpperCase(Locale.US)); else throw new IllegalArgumentException("Wrong subtag type"); } }
7,289
0
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/rfc4646
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/rfc4646/enums/Script.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.rfc4646.enums; import java.util.Locale; import org.apache.abdera.i18n.rfc4646.Subtag; /** * Enum constants used to validate language tags */ public enum Script { ARAB(null, null, "Arabic"), ARMI(null, null, "Imperial Aramaic"), ARMN(null, null, "Armenian"), AVST(null, null, "Avestan"), BALI(null, null, "Balinese"), BATK(null, null, "Batak"), BENG(null, null, "Bengali"), BLIS(null, null, "Blissymbols"), BOPO(null, null, "Bopomofo"), BRAH(null, null, "Brahmi"), BRAI(null, null, "Braille"), BUGI( null, null, "Buginese"), BUHD(null, null, "Buhid"), CAKM(null, null, "Chakma"), CANS(null, null, "Unified Canadian Aboriginal Syllabics"), CARI(null, null, "Carian"), CHAM(null, null, "Cham"), CHER(null, null, "Cherokee"), CIRT(null, null, "Cirth"), COPT(null, null, "Coptic"), CPRT(null, null, "Cypriot"), CYRL( null, null, "Cyrillic"), CYRS(null, null, "Cyrillic (Old Church Slavonic variant)"), DEVA(null, null, "Devanagari (Nagari)"), DSRT(null, null, "Deseret (Mormon)"), EGYD(null, null, "Egyptian demotic"), EGYH(null, null, "Egyptian hieratic"), EGYP(null, null, "Egyptian hieroglyphs"), ETHI(null, null, "Ethiopic (Ge&#x2BB;ez)", "Ethiopic (Ge'ez)"), GEOK(null, null, "Khutsuri (Asomtavruli and Nuskhuri)"), GEOR( null, null, "Georgian (Mkhedruli)"), GLAG(null, null, "Glagolitic"), GOTH(null, null, "Gothic"), GREK(null, null, "Greek"), GUJR(null, null, "Gujarati"), GURU(null, null, "Gurmukhi"), HANG(null, null, "Hangul (Hang&#x16D;l, Hangeul)"), HANI(null, null, "Han (Hanzi, Kanji, Hanja)"), HANO(null, null, "Hanunoo (Hanun&#xF3;o)"), HANS(null, null, "Han (Simplified variant)"), HANT(null, null, "Han (Traditional variant)"), HEBR(null, null, "Hebrew"), HIRA(null, null, "Hiragana"), HMNG(null, null, "Pahawh Hmong"), HRKT(null, null, "(alias for Hiragana + Katakana)"), HUNG(null, null, "Old Hungarian"), INDS( null, null, "Indus (Harappan)"), ITAL(null, null, "Old Italic (Etruscan, Oscan, etc.)"), JAVA(null, null, "Javanese"), JPAN(null, null, "Japanese (alias for Han + Hiragana + Katakana)"), KALI(null, null, "Kayah Li"), KANA( null, null, "Katakana"), KHAR(null, null, "Kharoshthi"), KHMR(null, null, "Khmer"), KNDA(null, null, "Kannada"), KORE( null, null, "Korean (alias for Hangul + Han)"), KTHI(null, null, "Kaithi"), LANA(null, null, "Lanna", "Tai Tham"), LAOO(null, null, "Lao"), LATF(null, null, "Latin (Fraktur variant)"), LATG(null, null, "Latin (Gaelic variant)"), LATN(null, null, "Latin"), LEPC(null, null, "Lepcha (R&#xF3;ng)"), LIMB(null, null, "Limbu"), LINA(null, null, "Linear A"), LINB(null, null, "Linear B"), LYCI(null, null, "Lycian"), LYDI(null, null, "Lydian"), MAND(null, null, "Mandaic", "Mandaean"), MANI(null, null, "Manichaean"), MAYA(null, null, "Mayan hieroglyphs"), MERO(null, null, "Meroitic"), MLYM(null, null, "Malayalam"), MONG(null, null, "Mongolian"), MOON( null, null, "Moon", "Moon code", "Moon script", "Moon type"), MTEI(null, null, "Meitei Mayek", "Meithei", "Meetei"), MYMR(null, null, "Myanmar (Burmese)"), NKOO(null, null, "N&#x2019;Ko"), OGAM(null, null, "Ogham"), OLCK( null, null, "Ol Chiki (Ol Cemet', Ol, Santali)"), ORKH(null, null, "Orkhon"), ORYA(null, null, "Oriya"), OSMA( null, null, "Osmanya"), PERM(null, null, "Old Permic"), PHAG(null, null, "Phags-pa"), PHLI(null, null, "Inscriptional Pahlavi"), PHLP(null, null, "Psalter Pahlavi"), PHLV(null, null, "Book Pahlavi"), PHNX(null, null, "Phoenician"), PLRD(null, null, "Pollard Phonetic"), PRTI(null, null, "Inscriptional Parthian"), QAAA( null, null, "PRIVATE USE"), QAAB(null, null, "PRIVATE USE"), QAAC(null, null, "PRIVATE USE"), QAAD(null, null, "PRIVATE USE"), QAAE(null, null, "PRIVATE USE"), QAAF(null, null, "PRIVATE USE"), QAAG(null, null, "PRIVATE USE"), QAAH(null, null, "PRIVATE USE"), QAAI(null, null, "PRIVATE USE"), QAAJ(null, null, "PRIVATE USE"), QAAK(null, null, "PRIVATE USE"), QAAL(null, null, "PRIVATE USE"), QAAM(null, null, "PRIVATE USE"), QAAN(null, null, "PRIVATE USE"), QAAO(null, null, "PRIVATE USE"), QAAP(null, null, "PRIVATE USE"), QAAQ(null, null, "PRIVATE USE"), QAAR(null, null, "PRIVATE USE"), QAAS(null, null, "PRIVATE USE"), QAAT(null, null, "PRIVATE USE"), QAAU(null, null, "PRIVATE USE"), QAAV(null, null, "PRIVATE USE"), QAAW(null, null, "PRIVATE USE"), QAAX(null, null, "PRIVATE USE"), QABA(null, null, "PRIVATE USE"), QABB(null, null, "PRIVATE USE"), QABC(null, null, "PRIVATE USE"), QABD(null, null, "PRIVATE USE"), QABE(null, null, "PRIVATE USE"), QABF(null, null, "PRIVATE USE"), QABG(null, null, "PRIVATE USE"), QABH(null, null, "PRIVATE USE"), QABI(null, null, "PRIVATE USE"), QABJ(null, null, "PRIVATE USE"), QABK(null, null, "PRIVATE USE"), QABL(null, null, "PRIVATE USE"), QABM(null, null, "PRIVATE USE"), QABN(null, null, "PRIVATE USE"), QABO(null, null, "PRIVATE USE"), QABP(null, null, "PRIVATE USE"), QABQ(null, null, "PRIVATE USE"), QABR(null, null, "PRIVATE USE"), QABS(null, null, "PRIVATE USE"), QABT(null, null, "PRIVATE USE"), QABU(null, null, "PRIVATE USE"), QABV(null, null, "PRIVATE USE"), QABW(null, null, "PRIVATE USE"), QABX(null, null, "PRIVATE USE"), RJNG(null, null, "Rejang", "Redjang", "Kaganga"), RORO(null, null, "Rongorongo"), RUNR(null, null, "Runic"), SAMR(null, null, "Samaritan"), SARA( null, null, "Sarati"), SAUR(null, null, "Saurashtra"), SGNW(null, null, "SignWriting"), SHAW(null, null, "Shavian (Shaw)"), SINH(null, null, "Sinhala"), SUND(null, null, "Sundanese"), SYLO(null, null, "Syloti Nagri"), SYRC( null, null, "Syriac"), SYRE(null, null, "Syriac (Estrangelo variant)"), SYRJ(null, null, "Syriac (Western variant)"), SYRN(null, null, "Syriac (Eastern variant)"), TAGB(null, null, "Tagbanwa"), TALE( null, null, "Tai Le"), TALU(null, null, "New Tai Lue"), TAML(null, null, "Tamil"), TAVT(null, null, "Tai Viet"), TELU( null, null, "Telugu"), TENG(null, null, "Tengwar"), TFNG(null, null, "Tifinagh (Berber)"), TGLG(null, null, "Tagalog"), THAA(null, null, "Thaana"), THAI(null, null, "Thai"), TIBT(null, null, "Tibetan"), UGAR(null, null, "Ugaritic"), VAII(null, null, "Vai"), VISP(null, null, "Visible Speech"), XPEO(null, null, "Old Persian"), XSUX( null, null, "Cuneiform, Sumero-Akkadian"), YIII(null, null, "Yi"), ZMTH(null, null, "Mathematical notation"), ZSYM( null, null, "Symbols"), ZXXX(null, null, "Code for unwritten documents"), ZYYY(null, null, "Code for undetermined script"), ZZZZ(null, null, "Code for uncoded script"); private final String deprecated; private final String preferred; private final String[] descriptions; private Script(String dep, String pref, String... desc) { this.deprecated = dep; this.preferred = pref; this.descriptions = desc; } public String getDeprecated() { return deprecated; } public boolean isDeprecated() { return deprecated != null; } public String getPreferredValue() { return preferred; } public Script getPreferred() { return preferred != null ? valueOf(preferred.toUpperCase(Locale.US)) : this; } public String getDescription() { return descriptions.length > 0 ? descriptions[0] : null; } public String[] getDescriptions() { return descriptions; } public Subtag newSubtag() { return new Subtag(this); } public static Script valueOf(Subtag subtag) { if (subtag == null) return null; if (subtag.getType() == Subtag.Type.SCRIPT) return valueOf(subtag.getName().toUpperCase(Locale.US)); else throw new IllegalArgumentException("Wrong subtag type"); } }
7,290
0
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/lang/Lang.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.lang; import java.io.Serializable; import java.util.Iterator; import java.util.Locale; import org.apache.abdera.i18n.text.CharUtils; import org.apache.abdera.i18n.text.InvalidCharacterException; import org.apache.abdera.i18n.text.CharUtils.Profile; /** * rfc3066 implementation. This has been deprecated. Use org.apache.abdera.i18n.rfc4646.Lang instead * * @deprecated * @see org.apache.abdera.i18n.rfc4646.Lang */ public class Lang implements Iterable<String>, Serializable, Cloneable { public static final Lang ANY = new Lang(); private static final long serialVersionUID = -4620499451615533855L; protected final String[] tags; protected final Locale locale; private Lang() { tags = new String[] {"*"}; locale = null; } public Lang(Locale locale) { this.tags = locale.toString().replace("\u005F", "\u002D").split("\u002D"); this.locale = locale; } public Lang(String tag) { this(parse(tag)); } public Lang(String... tags) { verify(tags); this.tags = tags; this.locale = initLocale(); } private Locale initLocale() { Locale locale = null; switch (tags.length) { case 0: break; case 1: locale = new Locale(tags[0]); break; case 2: locale = new Locale(tags[0], tags[1]); break; default: locale = new Locale(tags[0], tags[1], tags[2]); break; } return locale; } public String getPrimary() { return tags[0]; } public String getSubtag(int n) { if (n + 1 > tags.length) throw new ArrayIndexOutOfBoundsException(n); return tags[n + 1]; } public int getSubtagCount() { return tags.length - 1; } public Locale getLocale() { return locale; } public String toString() { StringBuilder buf = new StringBuilder(); for (String s : tags) { if (buf.length() > 0) buf.append('\u002D'); buf.append(s); } return buf.toString(); } public static boolean matches(Lang lang, String range) { if (range.equals("*")) return true; return matches(lang, new Lang(range)); } public static boolean matches(Lang lang, Lang range) { if (range.equals("*")) return true; if (lang.equals(range)) return true; if (lang.tags.length <= range.tags.length) return false; for (int n = 0; n < range.tags.length; n++) { if (!lang.tags[n].equalsIgnoreCase(range.tags[n])) return false; } return true; } public boolean matches(String range) { return matches(this, range); } public boolean matches(Lang range) { return matches(this, range); } @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((locale == null) ? 0 : locale.hashCode()); for (String tag : tags) { result = PRIME * result + tag.hashCode(); } return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof String) { String s = (String)obj; if (s.equals("*")) obj = ANY; else { try { obj = new Lang(s); } catch (Exception e) { } } } if (getClass() != obj.getClass()) return false; final Lang other = (Lang)obj; if (tags.length != other.tags.length) return false; for (int n = 0; n < tags.length; n++) { if (!tags[n].equalsIgnoreCase(other.tags[n])) return false; } return true; } private static void verify(String[] tags) { if (tags.length == 0) throw new InvalidLangTagSyntax(); String primary = tags[0]; try { CharUtils.verify(primary, Profile.ALPHA); } catch (InvalidCharacterException e) { throw new InvalidLangTagSyntax(); } for (int n = 1; n < tags.length; n++) { try { CharUtils.verify(tags[n], Profile.ALPHANUM); } catch (InvalidCharacterException e) { throw new InvalidLangTagSyntax(); } } } private static String[] parse(String tag) { String[] tags = tag.split("\u002D"); verify(tags); return tags; } public Iterator<String> iterator() { return java.util.Arrays.asList(tags).iterator(); } }
7,291
0
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/lang/InvalidLangTagSyntax.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.lang; /** * @deprecated **/ public class InvalidLangTagSyntax extends RuntimeException { private static final long serialVersionUID = -2653819135178550519L; public InvalidLangTagSyntax() { super(); } public InvalidLangTagSyntax(String message, Throwable cause) { super(message, cause); } public InvalidLangTagSyntax(String message) { super(message); } public InvalidLangTagSyntax(Throwable cause) { super(cause); } }
7,292
0
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/templates/DelegatingContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.templates; import java.util.Iterator; @SuppressWarnings("unchecked") public abstract class DelegatingContext extends CachingContext { protected final Context subcontext; protected DelegatingContext(Context subcontext) { this.subcontext = subcontext; } protected <T> T resolveActual(String var) { return (T)this.subcontext.resolve(var); } public Iterator<String> iterator() { return this.subcontext.iterator(); } }
7,293
0
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/templates/HashMapContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.templates; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * Context implementation based on a HashMap */ @SuppressWarnings("unchecked") public final class HashMapContext extends HashMap<String, Object> implements Context { private static final long serialVersionUID = 2206000974505975049L; private boolean isiri = false; private boolean normalizing = false; public HashMapContext() { } public HashMapContext(Map<String, Object> map) { super(map); } public HashMapContext(Map<String, Object> map, boolean isiri) { super(map); this.isiri = isiri; } public <T> T resolve(String var) { return (T)get(var); } public boolean isIri() { return isiri; } public void setIri(boolean isiri) { this.isiri = isiri; } public Iterator<String> iterator() { return keySet().iterator(); } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (isiri ? 1231 : 1237); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; final HashMapContext other = (HashMapContext)obj; if (isiri != other.isiri) return false; return true; } public boolean isNormalizing() { return normalizing; } public void setNormalizing(boolean normalizing) { this.normalizing = normalizing; } }
7,294
0
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/templates/Operation.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.templates; import java.io.IOException; import java.io.InputStream; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.abdera.i18n.text.CharUtils; import org.apache.abdera.i18n.text.Normalizer; import org.apache.abdera.i18n.text.UrlEncoding; @SuppressWarnings("unchecked") public abstract class Operation implements Serializable { protected final String name; protected final boolean multivar; protected Operation(String name) { this(name, false); } protected Operation(String name, boolean multivar) { this.name = name; this.multivar = multivar; } public final String name() { return name; } public abstract String evaluate(String var, String arg, Context context); public abstract void explain(String var, String arg, Appendable buf) throws IOException; public String[] getVariables(String var) { List<String> list = new ArrayList<String>(); if (!multivar) { String name = tokenName(var); if (!list.contains(name)) list.add(name); } else { String[] vardefs = var.split("\\+?\\s*,\\s*"); for (int n = 0; n < vardefs.length; n++) { String vardef = vardefs[n]; String name = vardef.split("=", 2)[0]; if (!list.contains(name)) list.add(name); } } return list.toArray(new String[list.size()]); } private static Map<String, Operation> operations = getOperations(); private static Map<String, Operation> getOperations() { Map<String, Operation> ops = new HashMap<String, Operation>(); ops.put("", new DefaultOperation()); ops.put("prefix", new PrefixOperation()); ops.put("suffix", new AppendOperation()); ops.put("join", new JoinOperation()); ops.put("list", new ListJoinOperation()); ops.put("opt", new OptOperation()); ops.put("neg", new NegOperation()); ops.put("append", ops.get("suffix")); // for backwards compatibility ops.put("listjoin", ops.get("list")); // for backwards compatibility return ops; } public static void register(Operation operation) { operations.put(operation.name(), operation); } public static Operation get(String name) { if (name == null) name = ""; Operation op = operations.get(name); if (op != null) return op; throw new UnsupportedOperationException(name); } private static String tokenName(String token) { String[] vardef = token.split("=", 2); return vardef[0]; } private static String evallist(String token, Context context, String sep) { StringBuilder buf = new StringBuilder(); Object value = context.resolve(token); if (value != null) { if (value instanceof String) { String val = toString(value, context); if (val != null) buf.append(val); } else if (value.getClass().isArray()) { Object[] values = (Object[])value; for (Object obj : values) { String val = toString(obj, context); if (val != null) { if (buf.length() > 0) buf.append(sep); buf.append(val); } } } else if (value instanceof Iterable) { Iterable iterable = (Iterable)value; for (Object obj : iterable) { String val = toString(obj, context); if (val != null) { if (buf.length() > 0) buf.append(sep); buf.append(val); } } } } else return null; return buf.toString(); } protected static String eval(String token, Context context) { String[] vardef = token.split("=", 2); String var = vardef[0]; String def = vardef.length > 1 ? vardef[1] : null; Object rep = context.resolve(var); String val = toString(rep, context); return val != null ? val : def != null ? def : null; } private static String toString(Object val, Context context) { if (val == null) return null; if (val.getClass().isArray()) { if (val instanceof byte[]) { return UrlEncoding.encode((byte[])val); } else if (val instanceof char[]) { String chars = new String((char[])val); return UrlEncoding.encode(Normalizer.normalize(chars, Normalizer.Form.KC).toString(), context.isIri() ? CharUtils.Profile.IUNRESERVED.filter() : CharUtils.Profile.UNRESERVED.filter()); } else if (val instanceof short[]) { StringBuilder buf = new StringBuilder(); short[] array = (short[])val; for (short obj : array) { if (buf.length() > 0) buf.append("%2C"); buf.append(String.valueOf(obj)); } return buf.toString(); } else if (val instanceof int[]) { StringBuilder buf = new StringBuilder(); int[] array = (int[])val; for (int obj : array) { if (buf.length() > 0) buf.append("%2C"); buf.append(String.valueOf(obj)); } return buf.toString(); } else if (val instanceof long[]) { StringBuilder buf = new StringBuilder(); long[] array = (long[])val; for (long obj : array) { if (buf.length() > 0) buf.append("%2C"); buf.append(String.valueOf(obj)); } return buf.toString(); } else if (val instanceof double[]) { StringBuilder buf = new StringBuilder(); double[] array = (double[])val; for (double obj : array) { if (buf.length() > 0) buf.append("%2C"); buf.append(String.valueOf(obj)); } return buf.toString(); } else if (val instanceof float[]) { StringBuilder buf = new StringBuilder(); float[] array = (float[])val; for (float obj : array) { if (buf.length() > 0) buf.append("%2C"); buf.append(String.valueOf(obj)); } return buf.toString(); } else if (val instanceof boolean[]) { StringBuilder buf = new StringBuilder(); boolean[] array = (boolean[])val; for (boolean obj : array) { if (buf.length() > 0) buf.append("%2C"); buf.append(String.valueOf(obj)); } return buf.toString(); } else { StringBuilder buf = new StringBuilder(); Object[] array = (Object[])val; for (Object obj : array) buf.append(toString(obj, context)); return buf.toString(); } } else if (val instanceof Template) { return toString(((Template)val).getPattern(), context); } else if (val instanceof InputStream) { try { return UrlEncoding.encode((InputStream)val); } catch (IOException e) { throw new RuntimeException(e); } } else if (val instanceof Readable) { try { return UrlEncoding.encode((Readable)val, "UTF-8", context.isIri() ? CharUtils.Profile.IUNRESERVED .filter() : CharUtils.Profile.UNRESERVED.filter()); } catch (IOException e) { throw new RuntimeException(e); } } else if (val instanceof CharSequence) { return encode((CharSequence)val, context.isIri()); } else if (val instanceof Byte) { return UrlEncoding.encode(((Byte)val).byteValue()); } else if (val instanceof Iterable) { StringBuilder buf = new StringBuilder(); Iterable i = (Iterable)val; for (Object obj : i) buf.append(toString(obj, context)); return buf.toString(); } else { return encode(val != null ? val.toString() : null, context.isIri()); } } protected static String eval(String token, String arg, Context context) { String[] vardef = token.split("=", 2); String var = vardef[0]; String def = vardef.length > 1 ? vardef[1] : null; Object rep = context.resolve(var); if (rep != null) { StringBuilder buf = new StringBuilder(); if (rep.getClass().isArray()) { if (rep instanceof byte[]) { String val = toString(rep, context); if (val != null) { buf.append(var); buf.append("="); buf.append(val); } } else if (rep instanceof char[]) { String val = toString(rep, context); if (val != null) { buf.append(var); buf.append("="); buf.append(val); } } else if (rep instanceof short[]) { String val = toString(rep, context); if (val != null) { buf.append(var); buf.append("="); buf.append(val); } } else if (rep instanceof int[]) { String val = toString(rep, context); if (val != null) { buf.append(var); buf.append("="); buf.append(val); } } else if (rep instanceof long[]) { String val = toString(rep, context); if (val != null) { buf.append(var); buf.append("="); buf.append(val); } } else if (rep instanceof double[]) { String val = toString(rep, context); if (val != null) { buf.append(var); buf.append("="); buf.append(val); } } else if (rep instanceof float[]) { String val = toString(rep, context); if (val != null) { buf.append(var); buf.append("="); buf.append(val); } } else if (rep instanceof boolean[]) { String val = toString(rep, context); if (val != null) { buf.append(var); buf.append("="); buf.append(val); } } else { Object[] array = (Object[])rep; for (Object obj : array) { String val = toString(obj, context); if (val != null) { if (buf.length() > 0) buf.append(arg); buf.append(var); buf.append("="); buf.append(val); } } } } else if (rep instanceof Iterable) { Iterable list = (Iterable)rep; for (Object obj : list) { String val = toString(obj, context); if (val != null) { if (buf.length() > 0) buf.append(arg); buf.append(var); buf.append("="); buf.append(val); } } } else { String val = toString(rep, context); if (val != null) { buf.append(var); buf.append("="); buf.append(val); } } return buf.toString(); } else if (def != null && def.length() > 0) { StringBuilder buf = new StringBuilder(); buf.append(var); buf.append("="); buf.append(def); return buf.toString(); } else return null; } protected static boolean isdefined(String token, Context context) { String[] vardef = token.split("=", 2); String var = vardef[0]; String def = vardef.length > 1 ? vardef[1] : null; Object rep = context.resolve(var); if (rep == null) rep = def; if (rep == null) return false; if (rep.getClass().isArray()) { if (rep instanceof byte[]) return ((byte[])rep).length > 0; else if (rep instanceof short[]) return ((short[])rep).length > 0; else if (rep instanceof char[]) return ((char[])rep).length > 0; else if (rep instanceof int[]) return ((int[])rep).length > 0; else if (rep instanceof long[]) return ((long[])rep).length > 0; else if (rep instanceof double[]) return ((double[])rep).length > 0; else if (rep instanceof float[]) return ((float[])rep).length > 0; else if (rep instanceof boolean[]) return ((boolean[])rep).length > 0; else if (rep instanceof Object[]) return ((Object[])rep).length > 0; } return true; } private static String encode(CharSequence val, boolean isiri) { return UrlEncoding.encode(Normalizer.normalize(val, Normalizer.Form.KC).toString(), isiri ? CharUtils.Profile.IUNRESERVED.filter() : CharUtils.Profile.UNRESERVED.filter()); } private static final class DefaultOperation extends Operation { private static final long serialVersionUID = -1279818778391836528L; public DefaultOperation() { super(""); } public String evaluate(String var, String arg, Context context) { return eval(var, context); } public void explain(String var, String arg, Appendable buf) throws IOException { buf.append("Replaced with the value of '").append(var).append("'"); } } private static final class PrefixOperation extends Operation { private static final long serialVersionUID = 2738115969196268525L; public PrefixOperation() { super("prefix"); } public String evaluate(String var, String arg, Context context) { String value = evallist(var, context, arg); return value == null || value.length() == 0 ? "" : arg != null ? arg + value : value; } public void explain(String var, String arg, Appendable buf) throws IOException { buf.append("If '").append(var).append("' is defined then prefix the value of '").append(var) .append("' with '").append(arg).append("'"); } } private static final class AppendOperation extends Operation { private static final long serialVersionUID = -2742793539643289075L; public AppendOperation() { super("suffix"); } public String evaluate(String var, String arg, Context context) { String value = evallist(var, context, arg); return value == null || value.length() == 0 ? "" : arg != null ? value + arg : value; } public void explain(String var, String arg, Appendable buf) throws IOException { buf.append("If '").append(var).append("' is defined then append '").append(arg) .append("' to the value of '").append(var).append("'"); } } private static final class JoinOperation extends Operation { private static final long serialVersionUID = -4102440981071994082L; public JoinOperation() { super("join", true); } public String evaluate(String var, String arg, Context context) { StringBuilder buf = new StringBuilder(); String[] vardefs = var.split("\\+?\\s*,\\s*"); String val = null; for (int n = 0; n < vardefs.length; n++) { String vardef = vardefs[n]; val = eval(vardef, arg, context); if (val != null) { if (buf.length() > 0) buf.append(arg); buf.append(val); } } String value = buf.toString(); return value; } public void explain(String var, String arg, Appendable buf) throws IOException { buf.append("Join 'var=value' with '" + arg + "' for each variable in ["); String[] vars = getVariables(var); boolean b = false; for (String v : vars) { if (b) buf.append(','); else b = true; buf.append("'").append(v).append("'"); } buf.append("]"); } } private static final class ListJoinOperation extends Operation { private static final long serialVersionUID = -8314383556644740425L; public ListJoinOperation() { super("list"); } public String evaluate(String var, String arg, Context context) { return evallist(var, context, arg); } public void explain(String var, String arg, Appendable buf) throws IOException { buf.append("Join the members of the list '").append(var).append("' together with '").append(arg) .append("'"); } } private static final class OptOperation extends Operation { private static final long serialVersionUID = 7808433764609641180L; public OptOperation() { super("opt", true); } public String evaluate(String var, String arg, Context context) { String[] vardefs = var.split("\\s*,\\s*"); for (String v : vardefs) { if (isdefined(v, context)) return arg; } return null; } public void explain(String var, String arg, Appendable buf) throws IOException { buf.append("If ["); String[] vars = getVariables(var); boolean b = false; for (String v : vars) { if (b) buf.append(','); else b = true; buf.append("'").append(v).append("'"); } buf.append("] is defined and a string, or a list with one or more members, then insert '").append(arg) .append("'"); } } private static final class NegOperation extends Operation { private static final long serialVersionUID = 1936380358902743528L; public NegOperation() { super("neg", true); } public String evaluate(String var, String arg, Context context) { String[] vardefs = var.split("\\s*,\\s*"); for (String v : vardefs) { if (isdefined(v, context)) return null; } return arg; } public void explain(String var, String arg, Appendable buf) throws IOException { buf.append("If ["); String[] vars = getVariables(var); boolean b = false; for (String v : vars) { if (b) buf.append(','); else b = true; buf.append("'").append(v).append("'"); } buf.append("] is undefined, or a zero length list, then insert '").append(arg).append("'"); } } }
7,295
0
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/templates/ObjectContext.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.templates; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.Iterator; import java.util.Map; @SuppressWarnings("unchecked") public final class ObjectContext extends CachingContext { private static final long serialVersionUID = -1387599933658718221L; private final Object target; private final Map<String, AccessibleObject> accessors = new HashMap<String, AccessibleObject>(); public ObjectContext(Object object) { this(object, false); } public ObjectContext(Object object, boolean isiri) { if (object == null) throw new IllegalArgumentException(); this.target = object; setIri(isiri); initMethods(); } private void initMethods() { Class _class = target.getClass(); if (_class.isAnnotation() || _class.isArray() || _class.isEnum() || _class.isPrimitive()) throw new IllegalArgumentException(); if (!_class.isInterface()) { Field[] fields = _class.getFields(); for (Field field : fields) { if (!Modifier.isPrivate(field.getModifiers())) { accessors.put(getName(field), field); } } } Method[] methods = _class.getMethods(); for (Method method : methods) { String name = method.getName(); if (!Modifier.isPrivate(method.getModifiers()) && method.getParameterTypes().length == 0 && !method.getReturnType().equals(Void.class) && !isReserved(name)) { accessors.put(getName(method), method); } } } private String getName(AccessibleObject object) { String name = null; VarName varName = object.getAnnotation(VarName.class); if (varName != null) return varName.value(); if (object instanceof Field) { name = ((Field)object).getName().toLowerCase(); } else if (object instanceof Method) { name = ((Method)object).getName().toLowerCase(); if (name.startsWith("get")) name = name.substring(3); else if (name.startsWith("is")) name = name.substring(2); } return name; } private boolean isReserved(String name) { return (name.equals("toString") || name.equals("hashCode") || name.equals("notify") || name.equals("notifyAll") || name.equals("getClass") || name.equals("wait")); } @Override protected <T> T resolveActual(String var) { try { var = var.toLowerCase(); AccessibleObject accessor = accessors.get(var); if (accessor == null) return null; if (accessor instanceof Method) { Method method = (Method)accessor; return (T)method.invoke(target); } else if (accessor instanceof Field) { Field field = (Field)accessor; return (T)field.get(target); } else return null; } catch (InvocationTargetException e) { throw new IllegalArgumentException("Accessor: " + var, e); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Accessor: " + var, e); } } public Iterator<String> iterator() { return accessors.keySet().iterator(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((target == null) ? 0 : target.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final ObjectContext other = (ObjectContext)obj; if (target == null) { if (other.target != null) return false; } else if (!target.equals(other.target)) return false; return true; } }
7,296
0
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/templates/Context.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.templates; import java.io.Serializable; /** * Used to resolve values for template variables */ public interface Context extends Cloneable, Serializable, Iterable<String> { /** * Resolve a value for the specified variable. The method can return either a String, an Array or a Collection. */ <T> T resolve(String var); /** * True if IRI expansion is enabled */ boolean isIri(); /** * True if IRI expansion is to be enabled */ void setIri(boolean isiri); /** * Clear this context */ void clear(); }
7,297
0
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/templates/Route.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.templates; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.abdera.i18n.text.CharUtils; /** * A type of URI Template loosely based on Ruby on Rails style Routes. Example: Route feed_route = new * Route("feed",":feed/:entry"); */ @SuppressWarnings("unchecked") public class Route implements Iterable<String>, Cloneable, Serializable { private static final long serialVersionUID = -8979172281494208841L; private static final Evaluator EVALUATOR = new Evaluator(); private static final Pattern VARIABLE = Pattern.compile("[\\*\\:](?:\\()?[0-9a-zA-Z]+(?:\\))?"); private static final String VARIABLE_CONTENT_MATCH = "([^:/\\?#\\[\\]@!\\$&'\\(\\)\\*\\+,;\\=]+)"; private static final String VARIABLE_CONTENT_PARSE = "([^:/\\?#\\[\\]@!\\$&'\\(\\)\\*\\+,;\\=]*)"; private final String name; private final String pattern; private final String[] tokens; private final String[] variables; private final Pattern regexMatch; private final Pattern regexParse; private Map<String, String> requirements; private Map<String, String> defaultValues; public Route(String name, String pattern) { this(name, pattern, null, null); } public Route(String name, String pattern, Map<String, String> defaultValues, Map<String, String> requirements) { this.name = name; this.pattern = CharUtils.stripBidiInternal(pattern); this.tokens = initTokens(); this.variables = initVariables(); this.defaultValues = defaultValues; this.requirements = requirements; this.regexMatch = initRegexMatch(); this.regexParse = initRegexParse(); } private String[] initTokens() { Matcher matcher = VARIABLE.matcher(pattern); List<String> tokens = new ArrayList<String>(); while (matcher.find()) { String token = matcher.group(); if (!tokens.contains(token)) tokens.add(token); } return tokens.toArray(new String[tokens.size()]); } private String[] initVariables() { List<String> list = new ArrayList<String>(); for (String token : this) { String var = var(token); if (!list.contains(var)) list.add(var); } String[] vars = list.toArray(new String[list.size()]); Arrays.sort(vars); return vars; } private Pattern initRegexMatch() { StringBuffer match = new StringBuffer(); int cnt = 0; for (String part : VARIABLE.split(pattern)) { match.append(Pattern.quote(part)); if (cnt++ < tokens.length) { match.append(VARIABLE_CONTENT_MATCH); } } return Pattern.compile(match.toString()); } private Pattern initRegexParse() { StringBuffer parse = new StringBuffer(); int cnt = 0; for (String part : VARIABLE.split(pattern)) { parse.append(Pattern.quote(part)); if (cnt++ < tokens.length) { parse.append(VARIABLE_CONTENT_PARSE); } } return Pattern.compile(parse.toString()); } /** * Returns true if the given uri matches the route pattern */ public boolean match(String uri) { return regexMatch.matcher(uri).matches() && matchRequirements(uri); } /** * Parses the given uri using the route pattern */ public Map<String, String> parse(String uri) { HashMap<String, String> vars = new HashMap<String, String>(); Matcher matcher = regexParse.matcher(uri); if (matcher.matches()) { for (int i = 0; i < matcher.groupCount(); i++) { vars.put(var(tokens[i]), matcher.group(i + 1).length() > 0 ? matcher.group(i + 1) : null); } } return vars; } /** * Expand the route pattern given the specified context */ public String expand(Context context) { String pattern = this.pattern; for (String token : this) { String var = var(token); pattern = replace(pattern, token, EVALUATOR.evaluate(var, getDefaultValue(var), context)); } StringBuffer buf = new StringBuffer(pattern); boolean qs = false; for (String var : context) { if (Arrays.binarySearch(variables, var) < 0) { if (!qs) { buf.append("?"); qs = true; } else { buf.append("&"); } buf.append(var).append("=").append(EVALUATOR.evaluate(var, context)); } } return buf.toString(); } public String getDefaultValue(String var) { if (defaultValues == null) return null; return defaultValues.get(var); } public String getRequirement(String var) { if (requirements == null) return null; return requirements.get(var); } private String var(String token) { token = token.substring(1); if (token.startsWith("(")) token = token.substring(1); if (token.endsWith(")")) token = token.substring(0, token.length() - 1); return token; } /** * Expand the route pattern given the specified context object **/ public String expand(Object object) { return expand(object, false); } /** * Expand the route pattern using IRI escaping rules */ public String expand(Object object, boolean isiri) { return expand(object instanceof Context ? (Context)object : object instanceof Map ? new HashMapContext((Map)object, isiri) : new ObjectContext(object, isiri)); } private String replace(String pattern, String token, String value) { return pattern.replace(token, value); } public String getName() { return name; } public String getPattern() { return pattern; } public Iterator<String> iterator() { return Arrays.asList(tokens).iterator(); } public String[] getVariables() { return variables; } public Map<String, String> getDefaultValues() { return defaultValues; } public Map<String, String> getRequirements() { return requirements; } public Route clone() { try { return (Route)super.clone(); } catch (Throwable e) { return new Route(name, pattern); // not going to happen, but just in case } } public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((pattern == null) ? 0 : pattern.hashCode()); return result; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; final Route other = (Route)obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (pattern == null) { if (other.pattern != null) return false; } else if (!pattern.equals(other.pattern)) return false; return true; } public String toString() { return pattern; } public static String expand(String pattern, Context context) { if (context == null || pattern == null) throw new IllegalArgumentException(); Route route = new Route(null, pattern); return route.expand(context); } public static String expand(String pattern, Object object) { return expand(pattern, object, false); } public static String expand(String pattern, Object object, boolean isiri) { if (object == null || pattern == null) throw new IllegalArgumentException(); Route route = new Route(null, pattern); return route.expand(object, isiri); } public static String expandAnnotated(Object object) { if (object == null) throw new IllegalArgumentException(); Class _class = object.getClass(); URIRoute uriroute = (URIRoute)_class.getAnnotation(URIRoute.class); if (uriroute != null) { return expand(uriroute.value(), object, uriroute.isiri()); } else { throw new IllegalArgumentException("No Route provided"); } } private boolean matchRequirements(String uri) { if (requirements != null && !requirements.isEmpty()) { Map<String, String> parsedUri = parse(uri); for (Map.Entry<String, String> requirement : requirements.entrySet()) { Pattern patt = Pattern.compile(requirement.getValue()); if (parsedUri.containsKey(requirement.getKey()) && !patt.matcher(parsedUri.get(requirement.getKey())) .matches()) { return false; } } } return true; } }
7,298
0
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n
Create_ds/abdera/dependencies/i18n/src/main/java/org/apache/abdera/i18n/templates/VarName.java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. The ASF licenses this file to You * 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. For additional information regarding * copyright in this work, please see the NOTICE file in the top level * directory of this distribution. */ package org.apache.abdera.i18n.templates; import static java.lang.annotation.ElementType.FIELD; import static java.lang.annotation.ElementType.METHOD; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Used to specify an alternative URI Template varname for a field or method */ @Retention(RUNTIME) @Target( {FIELD, METHOD}) public @interface VarName { String value(); }
7,299