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/server/src/main/java/org/apache/abdera/protocol/server
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/context/MediaResponseContext.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.protocol.server.context; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Writer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.util.Date; import org.apache.abdera.util.EntityTag; /** * ResponseContext implementation for arbitrary media resources */ public class MediaResponseContext extends SimpleResponseContext { private InputStream in; public MediaResponseContext(InputStream in, EntityTag etag, int status) { this.in = in; this.status = status; setEntityTag(etag); } public MediaResponseContext(InputStream in, int status) { this.in = in; this.status = status; } public MediaResponseContext(InputStream in, Date lastmodified, int status) { this.in = in; this.status = status; setLastModified(lastmodified); } public MediaResponseContext(byte[] bytes, int status) { this(new ByteArrayInputStream(bytes), status); } public MediaResponseContext(byte[] bytes, Date lastmodified, int status) { this(new ByteArrayInputStream(bytes), lastmodified, status); } public MediaResponseContext(byte[] bytes, EntityTag etag, int status) { this(new ByteArrayInputStream(bytes), etag, status); } public MediaResponseContext(ReadableByteChannel channel, int status) { this(Channels.newInputStream(channel), status); } public MediaResponseContext(ReadableByteChannel channel, Date lastmodified, int status) { this(Channels.newInputStream(channel), lastmodified, status); } public MediaResponseContext(ReadableByteChannel channel, EntityTag etag, int status) { this(Channels.newInputStream(channel), etag, status); } public boolean hasEntity() { return in != null; } public void writeTo(OutputStream out) throws IOException { if (hasEntity()) { if (in != null) { byte[] buf = new byte[500]; int r = -1; while ((r = in.read(buf)) != -1) { out.write(buf, 0, r); buf = new byte[100]; } } } } protected void writeEntity(Writer out) throws IOException { if (in != null) { InputStreamReader rdr = new InputStreamReader(in); char[] buf = new char[500]; int r = -1; while ((r = rdr.read(buf)) != -1) { out.write(buf, 0, r); buf = new char[100]; } } } }
7,400
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/context/ResponseContextException.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.protocol.server.context; import org.apache.abdera.protocol.server.ResponseContext; public class ResponseContextException extends Exception { private static final long serialVersionUID = -3031651143835987024L; private ResponseContext responseContext; public ResponseContextException(ResponseContext responseContext, Throwable t) { super(t); this.responseContext = responseContext; } public ResponseContextException(ResponseContext responseContext) { super(); this.responseContext = responseContext; } public ResponseContextException(int responseCode) { this(new EmptyResponseContext(responseCode)); } public ResponseContextException(int responseCode, Throwable t) { this(new EmptyResponseContext(responseCode), t); } public ResponseContextException(String msg, int responseCode) { this.responseContext = new EmptyResponseContext(responseCode); this.responseContext.setStatusText(msg); } public ResponseContext getResponseContext() { return responseContext; } @Override public String getMessage() { return responseContext.getStatusText(); } public int getStatusCode() { return responseContext.getStatus(); } }
7,401
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/context/StreamWriterResponseContext.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.protocol.server.context; import java.io.IOException; import java.io.Writer; import org.apache.abdera.Abdera; import org.apache.abdera.writer.StreamWriter; /** * Abstract base class for creating ResponseContext implementations that use the StreamWriter interface. Using the * StreamWriter to write out documents is significantly faster than using the object model but requires developers to * know more about proper Atom syntax. */ public abstract class StreamWriterResponseContext extends SimpleResponseContext { private final Abdera abdera; private final String sw; private boolean autoindent; /** * Create a new StreamWriterResponseContext * * @param abdera The Abdera instance */ protected StreamWriterResponseContext(Abdera abdera) { this(abdera, null, null); } /** * Create a new StreamWriterResponseContext * * @param abdera The Abdera instance * @param encoding The charset encoding */ protected StreamWriterResponseContext(Abdera abdera, String encoding) { this(abdera, encoding, null); } /** * Create a new StreamWriterResponseContext * * @param abdera The Abdera instance * @param encoding The charset encoding * @param sw The name of the Named StreamWriter to use */ protected StreamWriterResponseContext(Abdera abdera, String encoding, String sw) { super(encoding); this.abdera = abdera; this.sw = sw; } /** * Get the Abdera instance */ protected final Abdera getAbdera() { return abdera; } /** * Create a new StreamWriter instance. If the sw property was set, the specified Named StreamWriter will be returned */ protected StreamWriter newStreamWriter() { return sw == null ? abdera.newStreamWriter() : abdera.getWriterFactory().newStreamWriter(sw); } protected void writeEntity(Writer writer) throws IOException { writeTo(newStreamWriter().setWriter(writer).setAutoIndent(autoindent)); } /** * Write to the specified StreamWriter. Subclasses of this class must implement this method. */ protected abstract void writeTo(StreamWriter sw) throws IOException; /** * True to enable automatic indenting on the StreamWriter */ public StreamWriterResponseContext setAutoIndent(boolean autoindent) { this.autoindent = autoindent; return this; } /** * True if automatic indenting is enabled on the StreamWriter */ public boolean getAutoIndent() { return this.autoindent; } public boolean hasEntity() { return true; } }
7,402
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/context/AbstractResponseContext.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.protocol.server.context; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.activation.MimeType; import org.apache.abdera.i18n.text.Localizer; import org.apache.abdera.i18n.text.Rfc2047Helper; import org.apache.abdera.i18n.text.UrlEncoding; import org.apache.abdera.i18n.text.CharUtils.Profile; import org.apache.abdera.protocol.server.ResponseContext; import org.apache.abdera.protocol.util.AbstractResponse; import org.apache.abdera.util.EntityTag; import org.apache.abdera.writer.Writer; public abstract class AbstractResponseContext extends AbstractResponse implements ResponseContext { protected static final String[] EMPTY = new String[0]; protected int status = 0; protected String status_text = null; protected Writer writer = null; protected boolean binary = false; protected Map<String, Object[]> headers = null; public ResponseContext setBinary(boolean binary) { this.binary = binary; return this; } public boolean isBinary() { return binary; } public ResponseContext removeHeader(String name) { Map<String, Object[]> headers = getHeaders(); headers.remove(name); return this; } public ResponseContext setEncodedHeader(String name, String charset, String value) { return setHeader(name, Rfc2047Helper.encode(value, charset)); } public ResponseContext setEncodedHeader(String name, String charset, String... vals) { Object[] evals = new Object[vals.length]; for (int n = 0; n < vals.length; n++) { evals[n] = Rfc2047Helper.encode(vals[n], charset); } return setHeader(name, evals); } public ResponseContext setEscapedHeader(String name, Profile profile, String value) { return setHeader(name, UrlEncoding.encode(value, profile.filter())); } public ResponseContext setHeader(String name, Object value) { return setHeader(name, new Object[] {value}); } public ResponseContext setHeader(String name, Object... vals) { Map<String, Object[]> headers = getHeaders(); List<Object> values = new ArrayList<Object>(); for (Object value : vals) { values.add(value); } headers.put(name, values.toArray(new Object[values.size()])); return this; } public ResponseContext addEncodedHeader(String name, String charset, String value) { return addHeader(name, Rfc2047Helper.encode(value, charset)); } public ResponseContext addEncodedHeaders(String name, String charset, String... vals) { for (String value : vals) { addHeader(name, Rfc2047Helper.encode(value, charset)); } return this; } public ResponseContext addHeader(String name, Object value) { return addHeaders(name, new Object[] {value}); } public ResponseContext addHeaders(String name, Object... vals) { Map<String, Object[]> headers = getHeaders(); Object[] values = headers.get(name); List<Object> l = null; if (values == null) { l = new ArrayList<Object>(); } else { l = Arrays.asList(values); } for (Object value : vals) { l.add(value); } headers.put(name, l.toArray(new Object[l.size()])); return this; } public Map<String, Object[]> getHeaders() { if (headers == null) headers = new HashMap<String, Object[]>(); return headers; } public Date getDateHeader(String name) { Map<String, Object[]> headers = getHeaders(); Object[] values = headers.get(name); if (values != null) { for (Object value : values) { if (value instanceof Date) return (Date)value; } } return null; } public String getHeader(String name) { Map<String, Object[]> headers = getHeaders(); Object[] values = headers.get(name); if (values != null && values.length > 0) return values[0].toString(); return null; } public Object[] getHeaders(String name) { Map<String, Object[]> headers = getHeaders(); return headers.get(name); } public String[] getHeaderNames() { Map<String, Object[]> headers = getHeaders(); return headers.keySet().toArray(new String[headers.size()]); } private void append(StringBuilder buf, String value) { if (buf.length() > 0) buf.append(", "); buf.append(value); } public String getCacheControl() { StringBuilder buf = new StringBuilder(); if (isPublic()) append(buf, "public"); if (isPrivate()) append(buf, "private"); if (private_headers != null && private_headers.length > 0) { buf.append("=\""); for (String header : private_headers) { append(buf, header); } buf.append("\""); } if (isNoCache()) append(buf, "no-cache"); if (nocache_headers != null && nocache_headers.length > 0) { buf.append("=\""); for (String header : nocache_headers) { append(buf, header); } buf.append("\""); } if (isNoStore()) append(buf, "no-store"); if (isMustRevalidate()) append(buf, "must-revalidate"); if (isNoTransform()) append(buf, "no-transform"); if (getMaxAge() != -1) append(buf, "max-age=" + getMaxAge()); if (getSMaxAge() != -1) append(buf, "smax-age=" + getMaxAge()); return buf.toString(); } public ResponseContext setAge(long age) { return age == -1 ? removeHeader("Age") : setHeader("Age", String.valueOf(age)); } public ResponseContext setContentLanguage(String language) { return language == null ? removeHeader("Content-Language") : setHeader("Content-Language", language); } public ResponseContext setContentLength(long length) { return length == -1 ? removeHeader("Content-Length") : setHeader("Content-Length", String.valueOf(length)); } public ResponseContext setContentLocation(String uri) { return uri == null ? removeHeader("Content-Location") : setHeader("Content-Location", uri); } public ResponseContext setSlug(String slug) { if (slug == null) { return removeHeader("Slug"); } if (slug.indexOf((char)10) > -1 || slug.indexOf((char)13) > -1) throw new IllegalArgumentException(Localizer.get("SLUG.BAD.CHARACTERS")); return setEscapedHeader("Slug", Profile.ASCIISANSCRLF, slug); } public ResponseContext setContentType(String type) { return setContentType(type, null); } public ResponseContext setContentType(String type, String charset) { if (type == null) { return removeHeader("Content-Type"); } try { MimeType mimeType = new MimeType(type); if (charset != null) mimeType.setParameter("charset", charset); return setHeader("Content-Type", mimeType.toString()); } catch (Exception e) { throw new RuntimeException(e); } } public ResponseContext setEntityTag(String etag) { return etag != null ? setEntityTag(new EntityTag(etag)) : removeHeader("ETag"); } public ResponseContext setEntityTag(EntityTag etag) { return etag == null ? removeHeader("ETag") : setHeader("ETag", etag.toString()); } public ResponseContext setExpires(Date date) { return date == null ? removeHeader("Expires") : setHeader("Expires", date); } public ResponseContext setLastModified(Date date) { return date == null ? removeHeader("Last-Modified") : setHeader("Last-Modified", date); } public ResponseContext setLocation(String uri) { return uri == null ? removeHeader("Location") : setHeader("Location", uri); } public int getStatus() { return status; } public ResponseContext setStatus(int status) { this.status = status; return this; } public String getStatusText() { return status_text; } public ResponseContext setStatusText(String text) { this.status_text = text; return this; } public ResponseContext setAllow(String method) { return setHeader("Allow", method); } public ResponseContext setAllow(String... methods) { StringBuilder buf = new StringBuilder(); for (String method : methods) { if (buf.length() > 0) buf.append(", "); buf.append(method); } return setAllow(buf.toString()); } public ResponseContext setWriter(Writer writer) { this.writer = writer; return this; } }
7,403
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/context/EmptyResponseContext.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.protocol.server.context; import java.io.IOException; public final class EmptyResponseContext extends SimpleResponseContext { public EmptyResponseContext(int status) { setStatus(status); } public EmptyResponseContext(int status, String text) { setStatus(status); setStatusText(text); } protected void writeEntity(java.io.Writer writer) throws IOException { } public boolean hasEntity() { return false; } }
7,404
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/context/AbstractRequestContext.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.protocol.server.context; import java.io.IOException; import java.security.Principal; import javax.security.auth.Subject; import org.apache.abdera.Abdera; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.text.Localizer; 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.Provider; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.Target; import org.apache.abdera.protocol.server.TargetType; import org.apache.abdera.protocol.server.impl.SimpleTarget; import org.apache.abdera.protocol.util.AbstractRequest; import org.apache.abdera.util.MimeTypeHelper; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; public abstract class AbstractRequestContext extends AbstractRequest implements RequestContext { private final static Log log = LogFactory.getLog(AbstractRequestContext.class); protected final Provider provider; protected Subject subject; protected Principal principal; protected Target target; protected final String method; protected final IRI requestUri; protected final IRI baseUri; protected Document<?> document; protected AbstractRequestContext(Provider provider, String method, IRI requestUri, IRI baseUri) { this.provider = provider; this.method = method; this.baseUri = baseUri; this.requestUri = requestUri; } protected Target initTarget() { try { Target target = provider.resolveTarget(this); return target != null ? target : new SimpleTarget(TargetType.TYPE_NOT_FOUND, this); } catch (Exception e) { throw new RuntimeException(e); } } public Abdera getAbdera() { return provider.getAbdera(); } @SuppressWarnings("unchecked") public synchronized <T extends Element> Document<T> getDocument() throws ParseException, IOException { log.debug(Localizer.get("PARSING.REQUEST.DOCUMENT")); if (document == null) document = getDocument(getAbdera().getParser()); return (Document<T>)document; } @SuppressWarnings("unchecked") public synchronized <T extends Element> Document<T> getDocument(Parser parser) throws ParseException, IOException { log.debug(Localizer.get("PARSING.REQUEST.DOCUMENT")); if (parser == null) parser = getAbdera().getParser(); if (parser == null) throw new IllegalArgumentException("No Parser implementation was provided"); if (document == null) document = getDocument(parser, parser.getDefaultParserOptions()); return (Document<T>)document; } @SuppressWarnings("unchecked") public synchronized <T extends Element> Document<T> getDocument(ParserOptions options) throws ParseException, IOException { log.debug(Localizer.get("PARSING.REQUEST.DOCUMENT")); if (document == null) document = getDocument(getAbdera().getParser(), options); return (Document<T>)document; } @SuppressWarnings("unchecked") public synchronized <T extends Element> Document<T> getDocument(Parser parser, ParserOptions options) throws ParseException, IOException { log.debug(Localizer.get("PARSING.REQUEST.DOCUMENT")); if (parser == null) parser = getAbdera().getParser(); if (parser == null) throw new IllegalArgumentException("No Parser implementation was provided"); if (document == null) { document = parser.parse(getInputStream(), getResolvedUri().toString(), options); } return (Document<T>)document; } public IRI getBaseUri() { return baseUri; } public IRI getResolvedUri() { return baseUri.resolve(getUri()); } public String getMethod() { return method; } public IRI getUri() { return requestUri; } public Subject getSubject() { return subject; } public Principal getPrincipal() { return principal; } public Target getTarget() { return target; } public Provider getProvider() { return provider; } public String getTargetPath() { String uri = getUri().toString(); String cpath = getContextPath(); return cpath == null ? uri : uri.substring(cpath.length()); } public RequestContext setAttribute(String name, Object value) { return setAttribute(Scope.REQUEST, name, value); } public String urlFor(Object key, Object param) { return provider.urlFor(this, key, param); } public String absoluteUrlFor(Object key, Object param) { return getResolvedUri().resolve(urlFor(key, param)).toString(); } public boolean isAtom() { try { return MimeTypeHelper.isAtom(getContentType().toString()); } catch (Exception e) { return false; } } }
7,405
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/context/EntityProviderResponseContext.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.protocol.server.context; import java.io.IOException; import org.apache.abdera.Abdera; import org.apache.abdera.protocol.EntityProvider; import org.apache.abdera.writer.StreamWriter; /** * StreamWriterResponseContext implementation based on the EntityProvider interface */ public class EntityProviderResponseContext extends StreamWriterResponseContext { private final EntityProvider provider; public EntityProviderResponseContext(EntityProvider provider, Abdera abdera, String encoding, String sw) { super(abdera, encoding, sw); this.provider = provider; init(); } public EntityProviderResponseContext(EntityProvider provider, Abdera abdera, String encoding) { super(abdera, encoding); this.provider = provider; init(); } public EntityProviderResponseContext(EntityProvider provider, Abdera abdera) { super(abdera); this.provider = provider; init(); } private void init() { setContentType(provider.getContentType()); setEntityTag(provider.getEntityTag()); setLastModified(provider.getLastModified()); } @Override protected void writeTo(StreamWriter sw) throws IOException { provider.writeTo(sw); } }
7,406
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider/managed/BasicServerConfiguration.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.protocol.server.provider.managed; import org.apache.abdera.protocol.server.RequestContext; import static org.apache.abdera.util.Version.*; public class BasicServerConfiguration extends AbstractServerConfiguration { public BasicServerConfiguration(RequestContext request) { super(request); } @Override public String getFeedNamespace() { return URI + "/" + VERSION + "/"; } @Override public String getFeedNamespacePrefix() { return "a"; } }
7,407
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider/managed/FeedConfiguration.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.protocol.server.provider.managed; import java.util.Map; import java.util.Properties; import org.apache.abdera.model.Collection; import org.apache.abdera.protocol.server.CategoriesInfo; import org.apache.abdera.protocol.server.CollectionInfo; import org.apache.abdera.protocol.server.RequestContext; public class FeedConfiguration extends Configuration implements CollectionInfo { public static final String PROP_NAME_ADAPTER_CLASS = "adapterClassName"; public static final String PROP_SUB_URI_NAME = "subUri"; public static final String PROP_AUTHOR_NAME = "author"; public static final String PROP_TITLE_NAME = "title"; public static final String PROP_ACCEPTS = "accepts"; public static final String PROP_ENTRY_TITLE_NAME = "entryTitle"; public static final String PROP_FEED_CONFIG_LOCATION_NAME = "configFile"; public static final String ENTRY_ELEM_NAME_ID = "id"; public static final String ENTRY_ELEM_NAME_TITLE = "title"; public static final String ENTRY_ELEM_NAME_CONTENT = "content"; public static final String ENTRY_ELEM_NAME_AUTHOR = "author"; public static final String ENTRY_ELEM_NAME_UPDATED = "updated"; public static final String ENTRY_ELEM_NAME_LINK = "link"; private final String feedId; private final String subUri; private final String adapterClassName; private final String feedConfigLocation; private final ServerConfiguration serverConfiguration; private String feedTitle = "unknown"; private String feedAuthor = "unknown"; private Map<Object, Object> optionalProperties; private final CollectionAdapterConfiguration adapterConfiguration; public FeedConfiguration(String feedId, String subUri, String adapterClassName, String feedConfigLocation, ServerConfiguration serverConfiguration) { this.feedId = feedId; this.subUri = subUri; this.adapterClassName = adapterClassName; this.feedConfigLocation = feedConfigLocation; this.adapterConfiguration = new CollectionAdapterConfiguration(serverConfiguration, feedConfigLocation); this.serverConfiguration = serverConfiguration; } public static FeedConfiguration getFeedConfiguration(String feedId, Properties properties, ServerConfiguration serverConfiguration) { FeedConfiguration feedConfiguration = new FeedConfiguration(feedId, Configuration.getProperty(properties, PROP_SUB_URI_NAME), Configuration .getProperty(properties, PROP_NAME_ADAPTER_CLASS), Configuration .getProperty(properties, PROP_FEED_CONFIG_LOCATION_NAME), serverConfiguration); if (properties.containsKey(PROP_AUTHOR_NAME)) { feedConfiguration.setFeedAuthor(Configuration.getProperty(properties, PROP_AUTHOR_NAME)); } if (properties.containsKey(PROP_TITLE_NAME)) { feedConfiguration.setFeedTitle(Configuration.getProperty(properties, PROP_TITLE_NAME)); } feedConfiguration.optionalProperties = properties; return feedConfiguration; } public String getAdapterClassName() { return adapterClassName; } public String getFeedAuthor() { return feedAuthor; } public String getFeedConfigLocation() { return feedConfigLocation; } public String getFeedId() { return feedId; } public String getFeedTitle() { return feedTitle; } public String getSubUri() { return subUri; } public void setFeedAuthor(String feedAuthor) { this.feedAuthor = feedAuthor; } public void setFeedTitle(String feedTitle) { this.feedTitle = feedTitle; } public String getFeedUri() { return serverConfiguration.getServerUri() + "/" + getSubUri(); } public boolean hasProperty(String key) { return optionalProperties.containsKey(key); } public Object getProperty(String key) { return optionalProperties.get(key); } public CollectionAdapterConfiguration getAdapterConfiguration() { return adapterConfiguration; } public Collection asCollectionElement(RequestContext request) { Collection collection = request.getAbdera().getFactory().newCollection(); collection.setHref(getHref(request)); collection.setTitle(getTitle(request)); collection.setAccept(getAccepts(request)); for (CategoriesInfo catsinfo : getCategoriesInfo(request)) { collection.addCategories(catsinfo.asCategoriesElement(request)); } return collection; } public String[] getAccepts(RequestContext request) { Object accepts = optionalProperties.get(PROP_ACCEPTS); if (accepts == null || !(accepts instanceof String)) return new String[] {"application/atom+xml;type=entry"}; return ((String)accepts).split("\\s*,\\s*"); } public CategoriesInfo[] getCategoriesInfo(RequestContext request) { return new CategoriesInfo[0]; } public String getHref(RequestContext request) { return getFeedUri(); } public String getTitle(RequestContext request) { return getFeedTitle(); } public ServerConfiguration getServerConfiguration() { return adapterConfiguration.getServerConfiguration(); } }
7,408
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider/managed/ManagedWorkspace.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.protocol.server.provider.managed; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.abdera.model.Workspace; import org.apache.abdera.protocol.server.CollectionInfo; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.WorkspaceInfo; public class ManagedWorkspace implements WorkspaceInfo { private final ManagedProvider provider; private String title = "Abdera"; public ManagedWorkspace(ManagedProvider provider) { this.provider = provider; } public Collection<CollectionInfo> getCollections(RequestContext request) { CollectionAdapterManager cam = provider.getCollectionAdapterManager(request); List<CollectionInfo> collections = new ArrayList<CollectionInfo>(); try { Map<String, FeedConfiguration> map = cam.listAdapters(); for (FeedConfiguration config : map.values()) collections.add(config); } catch (Exception e) { throw new RuntimeException(e); } return collections; } public String getTitle(RequestContext request) { return title; } public void setTitle(String title) { this.title = title; } public Workspace asWorkspaceElement(RequestContext request) { Workspace workspace = request.getAbdera().getFactory().newWorkspace(); workspace.setTitle(getTitle(null)); for (CollectionInfo collection : getCollections(request)) workspace.addCollection(collection.asCollectionElement(request)); return workspace; } }
7,409
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider/managed/Configuration.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.protocol.server.provider.managed; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public abstract class Configuration { static Properties loadFileAsProperties(String fileLocation) throws IOException { Properties props = new Properties(); props.load(new FileInputStream(fileLocation)); return props; } static InputStream loadFileAsInputStream(String fileLocation) throws IOException { return Thread.currentThread().getContextClassLoader().getResourceAsStream(fileLocation); } static String getProperty(Properties prop, String key) { String val = prop.getProperty(key); if (val == null) throw new RuntimeException(); return val; } protected Configuration() { } }
7,410
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider/managed/ServerConfiguration.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.protocol.server.provider.managed; public abstract class ServerConfiguration extends Configuration { public abstract int getPort(); public abstract String getServerUri(); public abstract String getFeedNamespace(); public abstract String getFeedNamespacePrefix(); public abstract String getFeedConfigLocation(); public abstract String getFeedConfigSuffix(); public abstract String getAdapterConfigLocation(); public abstract FeedConfiguration loadFeedConfiguration(String feedId) throws Exception; }
7,411
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider/managed/CollectionAdapterConfiguration.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.protocol.server.provider.managed; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; public class CollectionAdapterConfiguration extends Configuration { private final String fileLocation; private final ServerConfiguration serverConfiguration; public CollectionAdapterConfiguration(ServerConfiguration serverConfiguration, String fileLocation) { this.fileLocation = fileLocation; this.serverConfiguration = serverConfiguration; } public InputStream getConfigAsFileInputStream() throws IOException { String filePath = serverConfiguration.getAdapterConfigLocation() + fileLocation; return Configuration.loadFileAsInputStream(filePath); } public Reader getAdapterConfigAsReader() throws IOException { return new InputStreamReader(getConfigAsFileInputStream()); } public ServerConfiguration getServerConfiguration() { return serverConfiguration; } }
7,412
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider/managed/CollectionAdapterManager.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.protocol.server.provider.managed; import java.io.File; import java.io.FileFilter; import java.lang.reflect.Constructor; import java.net.URL; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import java.util.logging.Logger; import org.apache.abdera.Abdera; import org.apache.abdera.protocol.server.CollectionAdapter; public class CollectionAdapterManager { public static Logger logger = Logger.getLogger(CollectionAdapterManager.class.getName()); // maps a feed id to an adapter instance protected static Map<String, CollectionAdapter> adapterInstanceMap = new HashMap<String, CollectionAdapter>(); protected final Abdera abdera; protected final ServerConfiguration config; public CollectionAdapterManager(Abdera abdera, ServerConfiguration config) { this.abdera = abdera; this.config = config; } public CollectionAdapter getAdapter(String feedId) throws Exception { FeedConfiguration feedConfiguration = config.loadFeedConfiguration(feedId); return createAdapterInstance(feedConfiguration, abdera); } public Map<String, FeedConfiguration> listAdapters() throws Exception { Map<String, FeedConfiguration> results = new HashMap<String, FeedConfiguration>(); Enumeration<URL> e = Thread.currentThread().getContextClassLoader().getResources(config.getFeedConfigLocation()); while (e.hasMoreElements()) { URL url = e.nextElement(); File file = new File(url.toURI()); if (!file.exists()) { throw new RuntimeException("Could not convert properties path to a File! \"" + file.getAbsolutePath() + "\" does not exist."); } File[] files = file.listFiles(new FileFilter() { public boolean accept(File file) { return !file.isDirectory(); } }); if (files != null) { for (File _file : files) { String name = _file.getName(); int i = name.indexOf(config.getFeedConfigSuffix()); String id = i > -1 ? name.substring(0, i) : null; if (id != null) { FeedConfiguration feedConfiguration = loadFeedInfo(id); if (null != feedConfiguration) results.put(id, feedConfiguration); } } } } return results; } protected FeedConfiguration loadFeedInfo(String feedId) throws Exception { return config.loadFeedConfiguration(feedId); } protected static synchronized CollectionAdapter createAdapterInstance(FeedConfiguration config, Abdera abdera) throws Exception { CollectionAdapter basicAdapter = adapterInstanceMap.get(config.getFeedId()); if (basicAdapter != null) { return basicAdapter; } ClassLoader cl = Thread.currentThread().getContextClassLoader(); Class<?> adapterClass = cl.loadClass(config.getAdapterClassName()); Constructor<?>[] ctors = adapterClass.getConstructors(); for (Constructor<?> element : ctors) { logger.finest("Public constructor found: " + element.toString()); } Constructor<?> c = adapterClass.getConstructor(new Class[] {Abdera.class, FeedConfiguration.class}); c.setAccessible(true); CollectionAdapter adapterInstance = (CollectionAdapter)c.newInstance(abdera, config); // put this adapter instance in adapterInstanceMap adapterInstanceMap.put(config.getFeedId(), adapterInstance); return adapterInstance; } }
7,413
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider/managed/AbstractServerConfiguration.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.protocol.server.provider.managed; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import org.apache.abdera.protocol.server.RequestContext; public abstract class AbstractServerConfiguration extends ServerConfiguration { private final String host; private final int port; private final boolean secure; protected AbstractServerConfiguration(RequestContext request) { Object ohost = request.getProperty(RequestContext.Property.SERVERNAME); Object oport = request.getProperty(RequestContext.Property.SERVERPORT); Object osec = request.getProperty(RequestContext.Property.SECURE); host = ohost != null ? (String)ohost : "localhost"; port = oport != null ? ((Integer)oport).intValue() : 9002; secure = osec != null ? ((Boolean)osec).booleanValue() : false; } @Override public String getAdapterConfigLocation() { return "abdera/adapter/config/"; } @Override public String getFeedConfigLocation() { return "abdera/adapter/"; } @Override public String getFeedConfigSuffix() { return ".properties"; } @Override public int getPort() { return port; } @Override public String getServerUri() { StringBuilder buf = new StringBuilder(); buf.append(secure ? "https://" : "http://"); buf.append(host); if (port != 80) { buf.append(":"); buf.append(port); } return buf.toString(); } @Override public FeedConfiguration loadFeedConfiguration(String feedId) throws IOException { String fileName = getFeedConfigLocation() + feedId + getFeedConfigSuffix(); InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); if (in == null) throw new FileNotFoundException(); Properties props = new Properties(); props.load(in); in.close(); return FeedConfiguration.getFeedConfiguration(feedId, props, this); } }
7,414
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider/managed/ManagedProvider.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.protocol.server.provider.managed; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.impl.AbstractWorkspaceProvider; /** * The ManagedProvider uses *.properties files discovered in the webapp classpath to configure CollectionAdapter * instances. The ManagedWorkspace implementation will automatically discover the *.properties files and will use those * to create the appropriate CollectionAdapter objects. Properties files must be located in the classpath at * /abdera/adapter/*.properties. Refer to the Abdera Server Implementation Guide for additional details */ public abstract class ManagedProvider extends AbstractWorkspaceProvider { protected abstract ServerConfiguration getServerConfiguration(RequestContext request); protected ManagedProvider() { addWorkspace(new ManagedWorkspace(this)); } public CollectionAdapterManager getCollectionAdapterManager(RequestContext request) { return new CollectionAdapterManager(abdera, getServerConfiguration(request)); } }
7,415
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider/managed/ManagedCollectionAdapter.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.protocol.server.provider.managed; import org.apache.abdera.Abdera; import org.apache.abdera.protocol.server.CollectionAdapter; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.context.ResponseContextException; import org.apache.abdera.protocol.server.impl.AbstractCollectionAdapter; public abstract class ManagedCollectionAdapter extends AbstractCollectionAdapter implements CollectionAdapter { protected final FeedConfiguration config; protected final Abdera abdera; protected ManagedCollectionAdapter(Abdera abdera, FeedConfiguration config) { this.config = config; this.abdera = abdera; } public Abdera getAbdera() { return this.abdera; } public FeedConfiguration getConfiguration() { return this.config; } public String getAuthor(RequestContext request) throws ResponseContextException { return config.getFeedAuthor(); } public String getId(RequestContext request) { return config.getFeedId(); } public String getTitle(RequestContext request) { return config.getFeedTitle(); } }
7,416
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider/basic/BasicProvider.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.protocol.server.provider.basic; 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.RouteManager; import org.apache.abdera.protocol.server.provider.managed.BasicServerConfiguration; import org.apache.abdera.protocol.server.provider.managed.ManagedProvider; import org.apache.abdera.protocol.server.provider.managed.ServerConfiguration; /** * Provider implementation intended to be used with BasicAdapter implementations */ public class BasicProvider extends ManagedProvider { public static final String PARAM_FEED = "feed"; public static final String PARAM_ENTRY = "entry"; public BasicProvider() { super(); init(); } private void init() { RouteManager routeManager = new RouteManager().addRoute("service", "/", TargetType.TYPE_SERVICE).addRoute("feed", "/:feed", TargetType.TYPE_COLLECTION) .addRoute("entry", "/:feed/:entry", TargetType.TYPE_ENTRY); setTargetBuilder(routeManager); setTargetResolver(routeManager); } public CollectionAdapter getCollectionAdapter(RequestContext request) { try { return getCollectionAdapterManager(request).getAdapter(request.getTarget().getParameter(PARAM_FEED)); } catch (Exception e) { return null; } } protected ServerConfiguration getServerConfiguration(RequestContext request) { return new BasicServerConfiguration(request); } }
7,417
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/provider/basic/BasicAdapter.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.protocol.server.provider.basic; import java.util.Date; import java.util.logging.Logger; import javax.activation.MimeType; import org.apache.abdera.Abdera; import org.apache.abdera.model.Document; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.parser.Parser; 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.Target; import org.apache.abdera.protocol.server.provider.managed.FeedConfiguration; import org.apache.abdera.protocol.server.provider.managed.ManagedCollectionAdapter; import org.apache.abdera.util.MimeTypeHelper; /** * The BasicAdapter provides a simplistic interface for working with Atompub collections with a restricted set of * options/features. The idea of the basic adapter is to make it easy to provide a minimally capable Atompub server */ public abstract class BasicAdapter extends ManagedCollectionAdapter { public static Logger logger = Logger.getLogger(BasicAdapter.class.getName()); protected BasicAdapter(Abdera abdera, FeedConfiguration config) { super(abdera, config); } public String getProperty(String key) throws Exception { Object val = config.getProperty(key); if (val == null) { logger.warning("Cannot find property " + key + "in Adapter properties file for feed " + config.getFeedId()); throw new RuntimeException(); } if (val instanceof String) return (String)val; throw new RuntimeException(); } protected Feed createFeed() throws Exception { Feed feed = abdera.newFeed(); feed.setId(config.getFeedUri()); feed.setTitle(config.getFeedTitle()); feed.setUpdated(new Date()); feed.addAuthor(config.getFeedAuthor()); return feed; } protected void addEditLinkToEntry(Entry entry) throws Exception { if (ProviderHelper.getEditUriFromEntry(entry) == null) { entry.addLink(entry.getId().toString(), "edit"); } } protected void setEntryIdIfNull(Entry entry) throws Exception { // if there is no id in Entry, assign one. if (entry.getId() != null) { return; } String uuidUri = abdera.getFactory().newUuidUri(); String[] segments = uuidUri.split(":"); String entryId = segments[segments.length - 1]; entry.setId(createEntryIdUri(entryId)); } protected String createEntryIdUri(String entryId) throws Exception { return config.getFeedUri() + "/" + entryId; } private ResponseContext createOrUpdateEntry(RequestContext request, boolean createFlag) { try { MimeType mimeType = request.getContentType(); String contentType = mimeType == null ? null : mimeType.toString(); if (contentType != null && !MimeTypeHelper.isAtom(contentType) && !MimeTypeHelper.isXml(contentType)) return ProviderHelper.notsupported(request); Abdera abdera = request.getAbdera(); Parser parser = abdera.getParser(); Entry inputEntry = (Entry)request.getDocument(parser).getRoot(); Target target = request.getTarget(); String entryId = !createFlag ? target.getParameter(BasicProvider.PARAM_ENTRY) : null; Entry newEntry = createFlag ? createEntry(inputEntry) : updateEntry(entryId, inputEntry); if (newEntry != null) { Document<Entry> newEntryDoc = newEntry.getDocument(); String loc = newEntry.getEditLinkResolvedHref().toString(); return ProviderHelper.returnBase(newEntryDoc, createFlag ? 201 : 200, null).setLocation(loc); } else { return ProviderHelper.notfound(request); } } catch (Exception e) { return ProviderHelper.servererror(request, e.getMessage(), e); } } public ResponseContext postEntry(RequestContext request) { return createOrUpdateEntry(request, true); } public ResponseContext deleteEntry(RequestContext request) { Target target = request.getTarget(); String entryId = target.getParameter(BasicProvider.PARAM_ENTRY); try { return deleteEntry(entryId) ? ProviderHelper.nocontent() : ProviderHelper.notfound(request); } catch (Exception e) { return ProviderHelper.servererror(request, e.getMessage(), e); } } public ResponseContext putEntry(RequestContext request) { return createOrUpdateEntry(request, false); } public ResponseContext getEntry(RequestContext request) { Target target = request.getTarget(); String entryId = target.getParameter(BasicProvider.PARAM_ENTRY); try { Entry entry = getEntry(entryId); return entry != null ? ProviderHelper.returnBase(entry.getDocument(), 200, null) : ProviderHelper .notfound(request); } catch (Exception e) { return ProviderHelper.servererror(request, e.getMessage(), e); } } public ResponseContext getFeed(RequestContext request) { try { Feed feed = getFeed(); return feed != null ? ProviderHelper.returnBase(feed.getDocument(), 200, null) : ProviderHelper .notfound(request); } catch (Exception e) { return ProviderHelper.servererror(request, e.getMessage(), e); } } public ResponseContext extensionRequest(RequestContext request) { return ProviderHelper.notallowed(request, ProviderHelper.getDefaultMethods(request)); } public ResponseContext getCategories(RequestContext request) { return ProviderHelper.notfound(request); } public abstract Feed getFeed() throws Exception; public abstract Entry getEntry(Object entryId) throws Exception; public abstract Entry createEntry(Entry entry) throws Exception; public abstract Entry updateEntry(Object entryId, Entry entry) throws Exception; public abstract boolean deleteEntry(Object entryId) throws Exception; }
7,418
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/processors/CategoriesRequestProcessor.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.protocol.server.processors; import org.apache.abdera.protocol.server.CollectionAdapter; import org.apache.abdera.protocol.server.ProviderHelper; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.RequestProcessor; import org.apache.abdera.protocol.server.ResponseContext; import org.apache.abdera.protocol.server.WorkspaceManager; /** * {@link org.apache.abdera.protocol.server.RequestProcessor} implementation which processes requests for categories * documents. */ public class CategoriesRequestProcessor implements RequestProcessor { public ResponseContext process(RequestContext context, WorkspaceManager workspaceManager, CollectionAdapter collectionAdapter) { if (collectionAdapter == null) { return ProviderHelper.notfound(context); } else { return this.processCategories(context, collectionAdapter); } } protected ResponseContext processCategories(RequestContext context, CollectionAdapter adapter) { return context.getMethod().equalsIgnoreCase("GET") ? adapter.getCategories(context) : null; } }
7,419
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/processors/ServiceRequestProcessor.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.protocol.server.processors; import java.io.IOException; import java.util.Collection; import org.apache.abdera.protocol.server.CategoriesInfo; import org.apache.abdera.protocol.server.CategoryInfo; import org.apache.abdera.protocol.server.CollectionAdapter; import org.apache.abdera.protocol.server.CollectionInfo; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.RequestProcessor; import org.apache.abdera.protocol.server.ResponseContext; import org.apache.abdera.protocol.server.WorkspaceInfo; import org.apache.abdera.protocol.server.WorkspaceManager; import org.apache.abdera.protocol.server.context.StreamWriterResponseContext; import org.apache.abdera.util.Constants; import org.apache.abdera.writer.StreamWriter; /** * {@link org.apache.abdera.protocol.server.RequestProcessor} implementation which processes requests for service * documents. */ public class ServiceRequestProcessor implements RequestProcessor { public ResponseContext process(RequestContext context, WorkspaceManager workspaceManager, CollectionAdapter collectionAdapter) { return this.processService(context, workspaceManager); } private ResponseContext processService(RequestContext context, WorkspaceManager workspaceManager) { String method = context.getMethod(); if (method.equalsIgnoreCase("GET")) { return this.getServiceDocument(context, workspaceManager); } else { return null; } } protected ResponseContext getServiceDocument(final RequestContext request, final WorkspaceManager workspaceManager) { return new StreamWriterResponseContext(request.getAbdera()) { protected void writeTo(StreamWriter sw) throws IOException { sw.startDocument().startService(); for (WorkspaceInfo wi : workspaceManager.getWorkspaces(request)) { sw.startWorkspace().writeTitle(wi.getTitle(request)); Collection<CollectionInfo> collections = wi.getCollections(request); if (collections != null) { for (CollectionInfo ci : collections) { sw.startCollection(ci.getHref(request)).writeTitle(ci.getTitle(request)).writeAccepts(ci .getAccepts(request)); CategoriesInfo[] catinfos = ci.getCategoriesInfo(request); if (catinfos != null) { for (CategoriesInfo catinfo : catinfos) { String cathref = catinfo.getHref(request); if (cathref != null) { sw.startCategories().writeAttribute("href", request.getTargetBasePath() + cathref) .endCategories(); } else { sw.startCategories(catinfo.isFixed(request), catinfo.getScheme(request)); for (CategoryInfo cat : catinfo) { sw.writeCategory(cat.getTerm(request), cat.getScheme(request), cat .getLabel(request)); } sw.endCategories(); } } } sw.endCollection(); } } sw.endWorkspace(); } sw.endService().endDocument(); } }.setStatus(200).setContentType(Constants.APP_MEDIA_TYPE); } }
7,420
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/processors/CollectionRequestProcessor.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.protocol.server.processors; import org.apache.abdera.protocol.server.CollectionAdapter; import org.apache.abdera.protocol.server.MediaCollectionAdapter; import org.apache.abdera.protocol.server.ProviderHelper; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.RequestProcessor; import org.apache.abdera.protocol.server.ResponseContext; import org.apache.abdera.protocol.server.WorkspaceManager; /** * {@link org.apache.abdera.protocol.server.RequestProcessor} implementation which processes requests for collection * documents. */ public class CollectionRequestProcessor implements RequestProcessor { public ResponseContext process(RequestContext context, WorkspaceManager workspaceManager, CollectionAdapter collectionAdapter) { if (collectionAdapter == null) { return ProviderHelper.notfound(context); } else { return this.processCollection(context, collectionAdapter); } } private ResponseContext processCollection(RequestContext context, CollectionAdapter adapter) { String method = context.getMethod(); if (method.equalsIgnoreCase("GET")) { return adapter.getFeed(context); } else if (method.equalsIgnoreCase("POST")) { return ProviderHelper.isAtom(context) ? adapter.postEntry(context) : adapter instanceof MediaCollectionAdapter ? ((MediaCollectionAdapter)adapter).postMedia(context) : ProviderHelper.notallowed(context); } else { return null; } } }
7,421
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/processors/MediaRequestProcessor.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.protocol.server.processors; import org.apache.abdera.protocol.server.CollectionAdapter; import org.apache.abdera.protocol.server.MediaCollectionAdapter; import org.apache.abdera.protocol.server.ProviderHelper; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.RequestProcessor; import org.apache.abdera.protocol.server.ResponseContext; import org.apache.abdera.protocol.server.WorkspaceManager; /** * {@link org.apache.abdera.protocol.server.RequestProcessor} implementation which processes requests for media * documents. */ public class MediaRequestProcessor implements RequestProcessor { public ResponseContext process(RequestContext context, WorkspaceManager workspaceManager, CollectionAdapter collectionAdapter) { if (collectionAdapter == null) { return ProviderHelper.notfound(context); } else { return this.processMedia(context, collectionAdapter); } } protected ResponseContext processMedia(RequestContext context, CollectionAdapter adapter) { String method = context.getMethod(); if (adapter instanceof MediaCollectionAdapter) { MediaCollectionAdapter mcadapter = (MediaCollectionAdapter)adapter; if (method.equalsIgnoreCase("GET")) { return mcadapter.getMedia(context); } else if (method.equalsIgnoreCase("POST")) { return mcadapter.postMedia(context); } else if (method.equalsIgnoreCase("PUT")) { return mcadapter.putMedia(context); } else if (method.equalsIgnoreCase("DELETE")) { return mcadapter.deleteMedia(context); } else if (method.equalsIgnoreCase("HEAD")) { return mcadapter.headMedia(context); } else if (method.equalsIgnoreCase("OPTIONS")) { return mcadapter.optionsMedia(context); } else { return null; } } else { return ProviderHelper.notallowed(context); } } }
7,422
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/processors/MultipartRelatedServiceRequestProcessor.java
package org.apache.abdera.protocol.server.processors; import java.io.IOException; import java.util.Collection; import java.util.Map; import org.apache.abdera.protocol.server.CategoriesInfo; import org.apache.abdera.protocol.server.CategoryInfo; import org.apache.abdera.protocol.server.CollectionInfo; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.ResponseContext; import org.apache.abdera.protocol.server.WorkspaceInfo; import org.apache.abdera.protocol.server.WorkspaceManager; import org.apache.abdera.protocol.server.context.StreamWriterResponseContext; import org.apache.abdera.protocol.server.multipart.MultipartRelatedCollectionInfo; import org.apache.abdera.util.Constants; import org.apache.abdera.writer.StreamWriter; /** * {@link org.apache.abdera.protocol.server.RequestProcessor} implementation which processes requests for service * documents. It writes multipart/related accept attributes when is enabled. */ public class MultipartRelatedServiceRequestProcessor extends ServiceRequestProcessor { @Override protected ResponseContext getServiceDocument(final RequestContext request, final WorkspaceManager workspaceManager) { return new StreamWriterResponseContext(request.getAbdera()) { protected void writeTo(StreamWriter sw) throws IOException { sw.startDocument().startService(); for (WorkspaceInfo wi : workspaceManager.getWorkspaces(request)) { sw.startWorkspace().writeTitle(wi.getTitle(request)); Collection<CollectionInfo> collections = wi.getCollections(request); if (collections != null) { for (CollectionInfo ci : collections) { sw.startCollection(ci.getHref(request)).writeTitle(ci.getTitle(request)); if (ci instanceof MultipartRelatedCollectionInfo) { MultipartRelatedCollectionInfo multipartCi = (MultipartRelatedCollectionInfo)ci; for (Map.Entry<String, String> accept : multipartCi.getAlternateAccepts(request) .entrySet()) { sw.startElement(Constants.ACCEPT); if (accept.getValue() != null && accept.getValue().length() > 0) { sw.writeAttribute(Constants.LN_ALTERNATE, accept.getValue()); } sw.writeElementText(accept.getKey()).endElement(); } } else { sw.writeAccepts(ci.getAccepts(request)); } CategoriesInfo[] catinfos = ci.getCategoriesInfo(request); if (catinfos != null) { for (CategoriesInfo catinfo : catinfos) { String cathref = catinfo.getHref(request); if (cathref != null) { sw.startCategories().writeAttribute("href", request.getTargetBasePath() + cathref) .endCategories(); } else { sw.startCategories(catinfo.isFixed(request), catinfo.getScheme(request)); for (CategoryInfo cat : catinfo) { sw.writeCategory(cat.getTerm(request), cat.getScheme(request), cat .getLabel(request)); } sw.endCategories(); } } } sw.endCollection(); } } sw.endWorkspace(); } sw.endService().endDocument(); } }.setStatus(200).setContentType(Constants.APP_MEDIA_TYPE); } }
7,423
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/processors/EntryRequestProcessor.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.protocol.server.processors; import org.apache.abdera.protocol.server.CollectionAdapter; import org.apache.abdera.protocol.server.ProviderHelper; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.RequestProcessor; import org.apache.abdera.protocol.server.ResponseContext; import org.apache.abdera.protocol.server.WorkspaceManager; /** * {@link org.apache.abdera.protocol.server.RequestProcessor} implementation which processes requests for entry * documents. */ public class EntryRequestProcessor implements RequestProcessor { public ResponseContext process(RequestContext context, WorkspaceManager workspaceManager, CollectionAdapter collectionAdapter) { if (collectionAdapter == null) { return ProviderHelper.notfound(context); } else { return this.processEntry(context, collectionAdapter); } } protected ResponseContext processEntry(RequestContext context, CollectionAdapter adapter) { String method = context.getMethod(); if (method.equalsIgnoreCase("GET")) { return adapter.getEntry(context); } else if (method.equalsIgnoreCase("POST")) { return adapter.postEntry(context); } else if (method.equalsIgnoreCase("PUT")) { return adapter.putEntry(context); } else if (method.equalsIgnoreCase("DELETE")) { return adapter.deleteEntry(context); } else if (method.equalsIgnoreCase("HEAD")) { return adapter.headEntry(context); } else if (method.equalsIgnoreCase("OPTIONS")) { return adapter.optionsEntry(context); } else { return null; } } }
7,424
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/multipart/MultipartRelatedCollectionInfo.java
package org.apache.abdera.protocol.server.multipart; import java.util.Map; import org.apache.abdera.protocol.server.CollectionInfo; import org.apache.abdera.protocol.server.RequestContext; public interface MultipartRelatedCollectionInfo extends CollectionInfo { /** * Returns a map of MIME media types for the app:collection element's app:accept elements. These tell a client which * media types the collection will accept on a POST. The key element is the default media type and the value element * is the alternate type or null if it doesn't accept alternates. */ public Map<String, String> getAlternateAccepts(RequestContext request); }
7,425
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/multipart/MultipartInputStream.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.protocol.server.multipart; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; /** * InputStream that reads a given inputStream and skips the boundary tokens. */ public class MultipartInputStream extends FilterInputStream { private InputStream input; private byte[] boundary; private byte[] storedBuffer; private int storedBufferPosition; private boolean fakeEof; private boolean realEof; private boolean bufferEnd; private int[] lastTable = new int[256]; public MultipartInputStream(InputStream input, byte[] boundary) { super(input); this.input = input; this.boundary = boundary; computeLastTable(); } public void skipBoundary() throws IOException { byte[] buffer = new byte[256]; while (read(buffer) != -1) { } } @Override public int read() throws IOException { byte[] b = new byte[1]; if (read(b) == -1) { return -1; } return b[0] & 0xff; } @Override public int read(byte[] bytes) throws IOException { return read(bytes, 0, bytes.length); } @Override public int read(byte[] buffer, int offset, int length) throws IOException { if (length == 0) { return 0; } int bytesReaded = -1; if (!checkEndOfFile()) { int bufferLength = Math.max(boundary.length * 3/* number of tokens into the stream */, length + boundary.length); byte[] newBuffer = new byte[bufferLength]; int position = cleanStoredBuffer(newBuffer, 0, bufferLength); if (bufferLength >= position) { position += readBuffer(newBuffer, position, bufferLength - position); } if (realEof && position == 0) { return -1; } bytesReaded = getBytesReaded(buffer, newBuffer, offset, position, length); } return bytesReaded != 0 ? bytesReaded : -1; } private int readBuffer(byte[] buffer, int offset, int length) throws IOException { int count = 0; int read = 0; do { read = input.read(buffer, offset + count, length - count); if (read > 0) { count += read; } } while (read > 0 && count < length); if (read < 0) { realEof = true; } return count; } private boolean checkEndOfFile() { if (fakeEof) { fakeEof = false; return true; } if (realEof && storedBuffer == null) { return true; } if (realEof && !bufferEnd) { bufferEnd = true; } return false; } private int getBytesReaded(byte[] buffer, byte[] newBuffer, int offSet, int position, int length) { int boundaryPosition = locateBoundary(newBuffer, boundary.length - 1, position); int bytesReaded; if (length < boundaryPosition || boundaryPosition == -1) {// boundary not found bytesReaded = Math.min(length, position); createStoredBuffer(newBuffer, bytesReaded, position); } else { bytesReaded = boundaryPosition; createStoredBuffer(newBuffer, bytesReaded + boundary.length, position); if (bytesReaded == 0) { return -1; } fakeEof = true; } System.arraycopy(newBuffer, 0, buffer, offSet, bytesReaded); return bytesReaded; } private void createStoredBuffer(byte[] buffer, int start, int end) { int length = end - start; if (length > 0) { if (bufferEnd && storedBuffer != null) { storedBufferPosition -= length; } else { int bufferLength = (storedBuffer == null ? 0 : storedBuffer.length - storedBufferPosition); byte[] newBuffer = new byte[length + bufferLength]; System.arraycopy(buffer, start, newBuffer, 0, length); if (storedBuffer != null) { System.arraycopy(storedBuffer, storedBufferPosition, newBuffer, length, bufferLength); } storedBuffer = newBuffer; storedBufferPosition = 0; } } } private int cleanStoredBuffer(byte[] buffer, int offset, int length) { int i = 0; if (storedBuffer != null) { for (i = 0; i < length && storedBufferPosition < storedBuffer.length; i++) { buffer[offset + i] = storedBuffer[storedBufferPosition++]; } if (storedBufferPosition >= storedBuffer.length) { storedBuffer = null; storedBufferPosition = 0; } } return i; } /* computation of the last table */ private void computeLastTable() { Arrays.fill(lastTable, boundary.length); for (int i = 0; i < boundary.length - 1; i++) { lastTable[boundary[i] & 0xff] = boundary.length - i - 1; } } /* simplified boyer-moore algorithm */ private int locateBoundary(byte[] bytes, int start, int end) { int position = -1; if (end > boundary.length) { int j = 0; int k = 0; for (int i = start; i < end; i += lastTable[bytes[i] & 0xff]) { for (k = i, j = boundary.length - 1; j >= 0 && boundary[j] == bytes[k]; j--) { k--; } if (j == -1) { position = k + 1; } } } return position; } }
7,426
0
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server
Create_ds/abdera/server/src/main/java/org/apache/abdera/protocol/server/multipart/AbstractMultipartCollectionAdapter.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.protocol.server.multipart; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; import java.util.Collection; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.mail.Header; import javax.mail.MessagingException; import javax.mail.internet.InternetHeaders; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.model.Entry; import org.apache.abdera.parser.ParseException; import org.apache.abdera.parser.Parser; import org.apache.abdera.protocol.server.RequestContext; import org.apache.abdera.protocol.server.impl.AbstractCollectionAdapter; import org.apache.abdera.util.Constants; import org.apache.abdera.util.MimeTypeHelper; import org.apache.commons.codec.binary.Base64; @SuppressWarnings("unchecked") public abstract class AbstractMultipartCollectionAdapter extends AbstractCollectionAdapter implements MultipartRelatedCollectionInfo { private static final String CONTENT_TYPE_HEADER = "content-type"; private static final String CONTENT_ID_HEADER = "content-id"; private static final String START_PARAM = "start"; private static final String TYPE_PARAM = "type"; private static final String BOUNDARY_PARAM = "boundary"; protected Map<String, String> accepts; public String[] getAccepts(RequestContext request) { Collection<String> acceptKeys = getAlternateAccepts(request).keySet(); return acceptKeys.toArray(new String[acceptKeys.size()]); } protected MultipartRelatedPost getMultipartRelatedData(RequestContext request) throws IOException, ParseException, MessagingException { MultipartInputStream multipart = getMultipartStream(request); multipart.skipBoundary(); String start = request.getContentType().getParameter(START_PARAM); Document<Entry> entry = null; Map<String, String> entryHeaders = new HashMap<String, String>(); InputStream data = null; Map<String, String> dataHeaders = new HashMap<String, String>(); Map<String, String> headers = getHeaders(multipart); // check if the first boundary is the media link entry if (start == null || start.length() == 0 || (headers.containsKey(CONTENT_ID_HEADER) && start.equals(headers.get(CONTENT_ID_HEADER))) || (headers.containsKey(CONTENT_TYPE_HEADER) && MimeTypeHelper.isAtom(headers.get(CONTENT_TYPE_HEADER)))) { entry = getEntry(multipart, request); entryHeaders.putAll(headers); } else { data = getDataInputStream(multipart); dataHeaders.putAll(headers); } multipart.skipBoundary(); headers = getHeaders(multipart); if (start != null && (headers.containsKey(CONTENT_ID_HEADER) && start.equals(headers.get(CONTENT_ID_HEADER))) && (headers.containsKey(CONTENT_TYPE_HEADER) && MimeTypeHelper.isAtom(headers.get(CONTENT_TYPE_HEADER)))) { entry = getEntry(multipart, request); entryHeaders.putAll(headers); } else { data = getDataInputStream(multipart); dataHeaders.putAll(headers); } checkMultipartContent(entry, dataHeaders, request); return new MultipartRelatedPost(entry, data, entryHeaders, dataHeaders); } private MultipartInputStream getMultipartStream(RequestContext request) throws IOException, ParseException, IllegalArgumentException { String boundary = request.getContentType().getParameter(BOUNDARY_PARAM); if (boundary == null) { throw new IllegalArgumentException("multipart/related stream invalid, boundary parameter is missing."); } boundary = "--" + boundary; String type = request.getContentType().getParameter(TYPE_PARAM); if (!(type != null && MimeTypeHelper.isAtom(type))) { throw new ParseException( "multipart/related stream invalid, type parameter should be " + Constants.ATOM_MEDIA_TYPE); } PushbackInputStream pushBackInput = new PushbackInputStream(request.getInputStream(), 2); pushBackInput.unread("\r\n".getBytes()); return new MultipartInputStream(pushBackInput, boundary.getBytes()); } private void checkMultipartContent(Document<Entry> entry, Map<String, String> dataHeaders, RequestContext request) throws ParseException { if (entry == null) { throw new ParseException("multipart/related stream invalid, media link entry is missing"); } if (!dataHeaders.containsKey(CONTENT_TYPE_HEADER)) { throw new ParseException("multipart/related stream invalid, data content-type is missing"); } if (!isContentTypeAccepted(dataHeaders.get(CONTENT_TYPE_HEADER), request)) { throw new ParseException("multipart/related stream invalid, content-type " + dataHeaders .get(CONTENT_TYPE_HEADER) + " not accepted into this multipart file"); } } private Map<String, String> getHeaders(MultipartInputStream multipart) throws IOException, MessagingException { Map<String, String> mapHeaders = new HashMap<String, String>(); moveToHeaders(multipart); InternetHeaders headers = new InternetHeaders(multipart); Enumeration<Header> allHeaders = headers.getAllHeaders(); if (allHeaders != null) { while (allHeaders.hasMoreElements()) { Header header = allHeaders.nextElement(); mapHeaders.put(header.getName().toLowerCase(), header.getValue()); } } return mapHeaders; } private boolean moveToHeaders(InputStream stream) throws IOException { boolean dash = false; boolean cr = false; int byteReaded; while ((byteReaded = stream.read()) != -1) { switch (byteReaded) { case '\r': cr = true; dash = false; break; case '\n': if (cr == true) return true; dash = false; break; case '-': if (dash == true) { // two dashes stream.close(); return false; } dash = true; cr = false; break; default: dash = false; cr = false; } } return false; } private InputStream getDataInputStream(InputStream stream) throws IOException { Base64 base64 = new Base64(); ByteArrayOutputStream bo = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; while (stream.read(buffer) != -1) { bo.write(buffer); } return new ByteArrayInputStream(base64.decode(bo.toByteArray())); } private <T extends Element> Document<T> getEntry(InputStream stream, RequestContext request) throws ParseException, IOException { Parser parser = request.getAbdera().getParser(); if (parser == null) throw new IllegalArgumentException("No Parser implementation was provided"); Document<?> document = parser.parse(stream, request.getResolvedUri().toString(), parser.getDefaultParserOptions()); return (Document<T>)document; } private boolean isContentTypeAccepted(String contentType, RequestContext request) { if (getAlternateAccepts(request) == null) { return false; } for (Map.Entry<String, String> accept : getAlternateAccepts(request).entrySet()) { if (accept.getKey().equalsIgnoreCase(contentType) && accept.getValue() != null && accept.getValue().equalsIgnoreCase(Constants.LN_ALTERNATE_MULTIPART_RELATED)) { return true; } } return false; } protected class MultipartRelatedPost { private final Document<Entry> entry; private final InputStream data; private final Map<String, String> entryHeaders; private final Map<String, String> dataHeaders; public MultipartRelatedPost(Document<Entry> entry, InputStream data, Map<String, String> entryHeaders, Map<String, String> dataHeaders) { this.entry = entry; this.data = data; this.entryHeaders = entryHeaders; this.dataHeaders = dataHeaders; } public Document<Entry> getEntry() { return entry; } public InputStream getData() { return data; } public Map<String, String> getEntryHeaders() { return entryHeaders; } public Map<String, String> getDataHeaders() { return dataHeaders; } } }
7,427
0
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser/EncodingTest.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.parser; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.OutputStream; import java.io.StringReader; import java.util.Date; import org.apache.abdera.Abdera; import org.apache.abdera.i18n.text.io.CompressionUtil; import org.apache.abdera.i18n.text.io.CompressionUtil.CompressionCodec; import org.apache.abdera.model.Content; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.model.Entry; import org.apache.abdera.parser.Parser; import org.apache.abdera.parser.ParserOptions; import org.apache.abdera.writer.WriterOptions; import org.junit.Test; public class EncodingTest { @Test public void testContentEncoding() throws Exception { Abdera abdera = new Abdera(); Entry entry = abdera.newEntry(); entry.setId("http://example.com/entry/1"); entry.setTitle("Whatever"); entry.setUpdated(new Date()); Content content = entry.getFactory().newContent(Content.Type.XML); String s = "<x>" + new Character((char)224) + "</x>"; content.setValue(s); content.setMimeType("application/xml+whatever"); entry.setContentElement(content); assertNotNull(entry.getContent()); assertEquals(s, entry.getContent()); } /** * Passes if the test does not throw a parse exception */ @Test public void testCompressionCodec() throws Exception { Abdera abdera = new Abdera(); Entry entry = abdera.newEntry(); ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStream cout = CompressionUtil.getEncodedOutputStream(out, CompressionCodec.GZIP); entry.writeTo(cout); cout.close(); byte[] bytes = out.toByteArray(); ByteArrayInputStream in = new ByteArrayInputStream(bytes); Parser parser = abdera.getParser(); ParserOptions options = parser.getDefaultParserOptions(); options.setCompressionCodecs(CompressionCodec.GZIP); Document<Entry> doc = abdera.getParser().parse(in, null, options); entry = doc.getRoot(); } /** * Passes if the test does not throw a parse exception */ @Test public void testXMLRestrictedChar() throws Exception { String s = "<?xml version='1.1'?><t t='\u007f' />"; Abdera abdera = new Abdera(); Parser parser = abdera.getParser(); ParserOptions options = parser.getDefaultParserOptions(); options.setFilterRestrictedCharacters(true); Document<Element> doc = parser.parse(new StringReader(s), null, options); doc.getRoot().toString(); } /** * Passes if the test does not throw a parse exception */ @Test public void testXMLRestrictedChar2() throws Exception { String s = "<?xml version='1.0'?><t t='\u0002' />"; Abdera abdera = new Abdera(); Parser parser = abdera.getParser(); ParserOptions options = parser.getDefaultParserOptions(); options.setFilterRestrictedCharacters(true); options.setCharset("UTF-8"); Document<Element> doc = parser.parse(new ByteArrayInputStream(s.getBytes("UTF-8")), null, options); doc.getRoot().toString(); } /** * Passes if the test does not throw any exceptions */ @Test public void testWriterOptions() throws Exception { Abdera abdera = new Abdera(); Entry entry = abdera.newEntry(); entry.setTitle("1"); ByteArrayOutputStream out = new ByteArrayOutputStream(); WriterOptions writeoptions = entry.getDefaultWriterOptions(); writeoptions.setCompressionCodecs(CompressionCodec.DEFLATE); writeoptions.setCharset("UTF-16"); writeoptions.setAutoClose(true); entry.getDocument().writeTo(out, writeoptions); out.close(); byte[] bytes = out.toByteArray(); ByteArrayInputStream in = new ByteArrayInputStream(bytes); Parser parser = abdera.getParser(); ParserOptions options = parser.getDefaultParserOptions(); options.setCompressionCodecs(CompressionCodec.DEFLATE); Document<Entry> doc = abdera.getParser().parse(in, null, options); doc.getRoot().toString(); } }
7,428
0
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser/ServiceDocumentTest.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.parser; import static org.junit.Assert.assertTrue; import java.io.StringWriter; import org.apache.abdera.Abdera; import org.apache.abdera.factory.Factory; import org.apache.abdera.model.Collection; import org.apache.abdera.model.Service; import org.apache.abdera.model.Workspace; import org.apache.abdera.parser.stax.FOMMultipartCollection; import org.junit.Test; public class ServiceDocumentTest { /** * Test whether the Service Document includes <accept> for collections. */ @Test public void testCollectionAccepts() throws Exception { Abdera abdera = new Abdera(); Factory factory = abdera.getFactory(); Service svc = factory.newService(); Workspace ws = svc.addWorkspace("test-ws"); Collection coll = ws.addCollection("test-coll", ws.getTitle() + "/test-coll"); coll.setAcceptsEntry(); assertTrue("Collection does not accept entries.", coll.acceptsEntry()); coll.addAccepts("application/apples"); assertTrue("Collection does not accept apples.", coll.accepts("application/apples")); StringWriter sw = new StringWriter(); svc.writeTo(sw); // System.out.println(sw); String s = sw.toString(); assertTrue("Service document does not specify acceptance of entries.", s .contains("application/atom+xml; type=entry")); assertTrue("Service document does not specify acceptance of apples.", s.contains("application/apples")); } /** * Test whether the <accept> element includes the multipart attribute. */ @Test public void testCollectionAcceptsMultipart() throws Exception { Abdera abdera = new Abdera(); Factory factory = abdera.getFactory(); Service svc = factory.newService(); Workspace ws = svc.addWorkspace("test-ws"); FOMMultipartCollection coll = (FOMMultipartCollection)ws.addMultipartCollection("test multipart coll", "/test-coll"); coll.setAcceptsEntry(); coll.addAccepts("image/*", "multipart-related"); assertTrue("Collection does not accept entries.", coll.acceptsEntry()); assertTrue("Collection does not accept multipart related images", coll.acceptsMultipart("image/*")); StringWriter sw = new StringWriter(); svc.writeTo(sw); String s = sw.toString(); assertTrue("Service document does not specify acceptance of entries.", s .contains("application/atom+xml; type=entry")); assertTrue("Service document does not specify acceptance of apples.", s.contains("image/*")); } }
7,429
0
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser/stax/ParserOptionsTest.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.parser.stax; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.HashMap; import java.util.Map; import javax.xml.namespace.QName; import org.apache.abdera.Abdera; import org.apache.abdera.filter.ParseFilter; import org.apache.abdera.model.Document; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.parser.Parser; import org.apache.abdera.parser.ParserOptions; import org.apache.abdera.util.filter.AbstractParseFilter; import org.junit.Test; public class ParserOptionsTest { private static final Abdera abdera = new Abdera(); @Test public void testIgnoreComments() { Parser parser = abdera.getParser(); ParserOptions options = parser.getDefaultParserOptions(); ParseFilter filter = new SimpleParseFilter(); filter.setIgnoreComments(true); options.setParseFilter(filter); Document<Feed> doc = parser.parse(ParserOptionsTest.class.getResourceAsStream( "/parseroptionstest.xml"), options); assertTrue(abdera.getXPath().selectNodes("//comment()", doc).isEmpty()); } @Test public void testIgnoreProcessingInstructions() { Parser parser = abdera.getParser(); ParserOptions options = parser.getDefaultParserOptions(); ParseFilter filter = new SimpleParseFilter(); filter.setIgnoreProcessingInstructions(true); options.setParseFilter(filter); Document<Feed> doc = parser.parse(ParserOptionsTest.class.getResourceAsStream( "/parseroptionstest.xml"), options); assertTrue(abdera.getXPath().selectNodes("//processing-instruction()", doc).isEmpty()); } @Test public void testIgnoreWhitespace() { Parser parser = abdera.getParser(); ParserOptions options = parser.getDefaultParserOptions(); ParseFilter filter = new SimpleParseFilter(); filter.setIgnoreWhitespace(true); options.setParseFilter(filter); Document<Feed> doc = parser.parse(ParserOptionsTest.class.getResourceAsStream( "/parseroptionstest.xml"), options); assertEquals("", doc.getRoot().getEntries().get(0).getSummary()); } @Test public void testAttributeFiltering() { final QName filteredAttribute = new QName("urn:test", "attr"); Parser parser = abdera.getParser(); ParserOptions options = parser.getDefaultParserOptions(); options.setParseFilter(new AbstractParseFilter() { public boolean acceptable(QName qname) { return true; } public boolean acceptable(QName qname, QName attribute) { return !filteredAttribute.equals(attribute); } }); Document<Feed> doc = parser.parse(ParserOptionsTest.class.getResourceAsStream( "/parseroptionstest.xml"), options); Entry entry = doc.getRoot().getEntries().get(0); assertNull(entry.getAttributeValue(filteredAttribute)); } @Test public void testQNameAliasMapping() { Parser parser = abdera.getParser(); ParserOptions options = parser.getDefaultParserOptions(); Map<QName,QName> qnameAliases = new HashMap<QName,QName>(); qnameAliases.put(new QName("urn:test", "mylink"), new QName("http://www.w3.org/2005/Atom", "link")); options.setQNameAliasMap(qnameAliases); options.setQNameAliasMappingEnabled(true); Document<Feed> doc = parser.parse(ParserOptionsTest.class.getResourceAsStream( "/parseroptionstest.xml"), options); assertFalse(doc.getRoot().getEntries().get(0).getLinks().isEmpty()); } }
7,430
0
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser/stax/ParserTest.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.parser.stax; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import org.apache.abdera.Abdera; import org.apache.abdera.model.Document; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.model.Service; import org.apache.abdera.parser.Parser; import org.junit.Test; public class ParserTest { private static Abdera abdera = new Abdera(); private static Parser getParser() { return abdera.getParser(); } @Test public void testParse() throws Exception { Document<Feed> feedDoc = getParser().parse(ParserTest.class.getResourceAsStream("/simpleFeed.xml")); assertTrue(feedDoc.getRoot() instanceof Feed); assertEquals("utf-8", feedDoc.getCharset()); Document<Entry> entryDoc = getParser().parse(ParserTest.class.getResourceAsStream("/simpleEntry.xml")); assertTrue(entryDoc.getRoot() instanceof Entry); assertEquals("utf-8", entryDoc.getCharset()); Document<Service> serviceDoc = getParser().parse(ParserTest.class.getResourceAsStream("/simpleService.xml")); assertTrue(serviceDoc.getRoot() instanceof Service); assertEquals("utf-8", serviceDoc.getCharset()); } @Test public void testParseReader() throws Exception { InputStream is = ParserTest.class.getResourceAsStream("/simpleFeed.xml"); Document<Feed> feedDoc = getParser().parse(new InputStreamReader(is), getResourceName("/simpleEntry.xml")); assertTrue(feedDoc.getRoot() instanceof Feed); assertEquals("utf-8", feedDoc.getCharset()); is = ParserTest.class.getResourceAsStream("/simpleEntry.xml"); Document<Entry> entryDoc = getParser().parse(new InputStreamReader(is), getResourceName("/simpleEntry.xml")); assertTrue(entryDoc.getRoot() instanceof Entry); assertEquals("utf-8", entryDoc.getCharset()); is = ParserTest.class.getResourceAsStream("/simpleService.xml"); Document<Service> serviceDoc = getParser().parse(new InputStreamReader(is), getResourceName("/simpleEntry.xml")); assertTrue(serviceDoc.getRoot() instanceof Service); assertEquals("utf-8", serviceDoc.getCharset()); } private static String getResourceName(String name) { return ParserTest.class.getResource(name).toExternalForm().replaceAll(" ", "%20"); } /** * Test for ABDERA-22. * * @see https://issues.apache.org/jira/browse/ABDERA-22 */ @Test public void testParseReaderNoBase() throws Exception { InputStream is = ParserTest.class.getResourceAsStream("/simpleEntry.xml"); Reader reader = new InputStreamReader(is); Document<Entry> entryDoc = getParser().parse(reader); assertTrue(entryDoc.getRoot() instanceof Entry); assertEquals("utf-8", entryDoc.getCharset()); } }
7,431
0
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser/stax/FeedValidatorTest.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.parser.stax; 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.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.activation.DataHandler; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.iri.IRISyntaxException; import org.apache.abdera.model.AtomDate; import org.apache.abdera.model.Category; import org.apache.abdera.model.Content; 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.Source; import org.apache.abdera.model.Text; import org.apache.abdera.util.MimeTypeParseException; import org.apache.axiom.om.OMException; import org.junit.BeforeClass; import org.junit.Test; //@Ignore("ABDERA-256") public class FeedValidatorTest extends BaseParserTestCase { private static IRI baseURI = null; @BeforeClass public static void setUp() throws Exception { baseURI = new IRI("http://feedvalidator.org/testcases/atom/"); } @Test public void testSection11BriefNoError() throws Exception { // http://feedvalidator.org/testcases/atom/1.1/brief-noerror.xml IRI uri = baseURI.resolve("1.1/brief-noerror.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); Text title = feed.getTitleElement(); assertNotNull(title); assertEquals(Text.Type.TEXT, title.getTextType()); String value = title.getValue(); assertNotNull(value); assertEquals("Example Feed", value); List<Link> links = feed.getLinks(); assertEquals(1, links.size()); for (Link link : links) { assertNull(link.getRel()); // it's an alternate link assertEquals(new IRI("http://example.org/"), link.getHref()); assertNull(link.getHrefLang()); assertNull(link.getMimeType()); assertNull(link.getTitle()); assertEquals(-1, link.getLength()); } links = feed.getLinks(Link.REL_ALTERNATE); assertEquals(1, links.size()); links = feed.getLinks(Link.REL_RELATED); assertEquals(0, links.size()); assertNotNull(feed.getUpdatedElement()); DateTime dte = feed.getUpdatedElement(); AtomDate dt = dte.getValue(); assertNotNull(dt); Calendar c = dt.getCalendar(); AtomDate cdt = new AtomDate(c); assertEquals(dt.getTime(), cdt.getTime()); Person person = feed.getAuthor(); assertNotNull(person); assertEquals("John Doe", person.getName()); assertNull(person.getEmail()); assertNull(person.getUri()); IRIElement id = feed.getIdElement(); assertNotNull(id); assertEquals(new IRI("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6"), id.getValue()); List<Entry> entries = feed.getEntries(); assertEquals(1, entries.size()); for (Entry entry : entries) { title = entry.getTitleElement(); assertNotNull(title); assertEquals(Text.Type.TEXT, title.getTextType()); value = title.getValue(); assertEquals("Atom-Powered Robots Run Amok", value); links = entry.getLinks(); assertEquals(1, links.size()); for (Link link : links) { assertNull(link.getRel()); // it's an alternate link assertEquals(new IRI("http://example.org/2003/12/13/atom03"), link.getHref()); assertNull(link.getHrefLang()); assertNull(link.getMimeType()); assertNull(link.getTitle()); assertEquals(-1, link.getLength()); } links = entry.getLinks(Link.REL_ALTERNATE); assertEquals(1, links.size()); links = entry.getLinks(Link.REL_RELATED); assertEquals(0, links.size()); id = entry.getIdElement(); assertNotNull(id); assertEquals(new IRI("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a"), id.getValue()); assertNotNull(entry.getUpdatedElement()); dte = entry.getUpdatedElement(); dt = dte.getValue(); assertNotNull(dt); c = dt.getCalendar(); cdt = new AtomDate(c); assertEquals(cdt.getTime(), dt.getTime()); Text summary = entry.getSummaryElement(); assertNotNull(summary); assertEquals(Text.Type.TEXT, summary.getTextType()); value = summary.getValue(); assertEquals("Some text.", value); } } @Test public void testSection11ExtensiveNoError() throws Exception { // http://feedvalidator.org/testcases/atom/1.1/extensive-noerror.xml IRI uri = baseURI.resolve("1.1/extensive-noerror.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); assertNotNull(feed.getTitleElement()); assertEquals(Text.Type.TEXT, feed.getTitleElement().getTextType()); assertEquals("dive into mark", feed.getTitleElement().getValue()); assertNotNull(feed.getSubtitleElement()); assertEquals(Text.Type.TEXT, feed.getTitleElement().getTextType()); assertNotNull(feed.getSubtitleElement().getValue()); assertNotNull(feed.getUpdatedElement()); assertNotNull(feed.getUpdatedElement().getValue()); assertNotNull(feed.getUpdatedElement().getValue().getDate()); assertNotNull(feed.getIdElement()); assertTrue(feed.getIdElement() instanceof IRIElement); assertEquals(new IRI("tag:example.org,2003:3"), feed.getIdElement().getValue()); List<Link> links = feed.getLinks(Link.REL_ALTERNATE); assertEquals(1, links.size()); for (Link link : links) { assertEquals("alternate", link.getRel()); assertEquals("text/html", link.getMimeType().toString()); assertEquals("en", link.getHrefLang()); assertEquals(new IRI("http://example.org/"), link.getHref()); assertNull(link.getTitle()); assertEquals(-1, link.getLength()); } links = feed.getLinks(Link.REL_SELF); assertEquals(1, links.size()); for (Link link : links) { assertEquals("self", link.getRel()); assertEquals("application/atom+xml", link.getMimeType().toString()); assertEquals(new IRI("http://example.org/feed.atom"), link.getHref()); assertNull(link.getHrefLang()); assertNull(link.getTitle()); assertEquals(-1, link.getLength()); } assertNotNull(feed.getRightsElement()); assertEquals(Text.Type.TEXT, feed.getRightsElement().getTextType()); assertEquals("Copyright (c) 2003, Mark Pilgrim", feed.getRightsElement().getValue()); assertNotNull(feed.getGenerator()); Generator generator = feed.getGenerator(); assertEquals(new IRI("http://www.example.com/"), generator.getUri()); assertEquals("1.0", generator.getVersion()); assertNotNull(generator.getText()); assertEquals("Example Toolkit", generator.getText().trim()); List<Entry> entries = feed.getEntries(); assertNotNull(entries); assertEquals(1, entries.size()); for (Entry entry : entries) { assertNotNull(entry.getTitleElement()); assertEquals(Text.Type.TEXT, entry.getTitleElement().getTextType()); assertEquals("Atom draft-07 snapshot", entry.getTitleElement().getValue()); links = entry.getLinks(Link.REL_ALTERNATE); assertEquals(1, links.size()); for (Link link : links) { assertEquals("alternate", link.getRel()); assertEquals("text/html", link.getMimeType().toString()); assertEquals(new IRI("http://example.org/2005/04/02/atom"), link.getHref()); assertNull(link.getHrefLang()); assertNull(link.getTitle()); assertEquals(-1, link.getLength()); } links = entry.getLinks(Link.REL_ENCLOSURE); assertEquals(1, links.size()); for (Link link : links) { assertEquals("enclosure", link.getRel()); assertEquals("audio/mpeg", link.getMimeType().toString()); assertEquals(new IRI("http://example.org/audio/ph34r_my_podcast.mp3"), link.getHref()); assertEquals(1337, link.getLength()); assertNull(link.getHrefLang()); assertNull(link.getTitle()); } assertNotNull(entry.getIdElement()); assertEquals(new IRI("tag:example.org,2003:3.2397"), entry.getIdElement().getValue()); assertNotNull(entry.getUpdatedElement()); assertNotNull(entry.getPublishedElement()); Person person = entry.getAuthor(); assertNotNull(person); assertEquals("Mark Pilgrim", person.getName()); assertEquals("f8dy@example.com", person.getEmail()); assertNotNull(person.getUriElement()); assertEquals(new IRI("http://example.org/"), person.getUriElement().getValue()); List<Person> contributors = entry.getContributors(); assertNotNull(contributors); assertEquals(2, contributors.size()); assertNotNull(entry.getContentElement()); assertEquals(Content.Type.XHTML, entry.getContentElement().getContentType()); assertEquals("en", entry.getContentElement().getLanguage()); assertEquals(new IRI("http://diveintomark.org/"), entry.getContentElement().getBaseUri()); } } @Test public void testSection12MissingNamespace() throws Exception { // http://feedvalidator.org/testcases/atom/1.2/missing-namespace.xml IRI uri = baseURI.resolve("1.2/missing-namespace.xml"); Document<?> doc = parse(uri); assertFalse(doc.getRoot() instanceof Feed); } @Test public void testSection12PrefixedNamespace() throws Exception { // http://feedvalidator.org/testcases/atom/1.2/prefixed-namespace.xml IRI uri = baseURI.resolve("1.2/prefixed-namespace.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); assert (feed.getQName().getPrefix().equals("atom")); } @Test public void testSection12WrongNamespaceCase() throws Exception { // http://feedvalidator.org/testcases/atom/1.2/wrong-namespace-case.xml IRI uri = baseURI.resolve("1.2/wrong-namespace-case.xml"); Document<?> doc = parse(uri); assertFalse(doc.getRoot() instanceof Feed); } @Test public void testSection12WrongNamespace() throws Exception { // http://feedvalidator.org/testcases/atom/1.2/wrong-namespace.xml IRI uri = baseURI.resolve("1.2/wrong-namespace.xml"); Document<?> doc = parse(uri); assertFalse(doc.getRoot() instanceof Feed); } @Test public void testSection2BriefEntry() throws Exception { // http://feedvalidator.org/testcases/atom/2/brief-entry-noerror.xml IRI uri = baseURI.resolve("2/brief-entry-noerror.xml"); Document<Entry> doc = parse(uri); Entry entry = doc.getRoot(); assertNotNull(entry); assertNotNull(entry.getTitleElement()); assertEquals(1, entry.getLinks(Link.REL_ALTERNATE).size()); assertNotNull(entry.getIdElement()); assertNotNull(entry.getIdElement().getValue()); assertNotNull(entry.getUpdatedElement()); assertNotNull(entry.getUpdatedElement().getValue()); assertNotNull(entry.getUpdatedElement().getValue().getDate()); assertNotNull(entry.getSummaryElement()); assertEquals(Text.Type.TEXT, entry.getSummaryElement().getTextType()); assertNotNull(entry.getAuthor()); assertEquals("John Doe", entry.getAuthor().getName()); } @Test public void testSection2InfosetAttrOrder() throws Exception { // http://feedvalidator.org/testcases/atom/2/infoset-attr-order.xml IRI uri = baseURI.resolve("2/infoset-attr-order.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Link> links = feed.getLinks(Link.REL_ALTERNATE); assertEquals(2, links.size()); for (Link link : links) { assertEquals("alternate", link.getRel()); assertNotNull(link.getHref()); } } @Test public void testSection2InfosetCDATA() throws Exception { // http://feedvalidator.org/testcases/atom/2/infoset-cdata.xml IRI uri = baseURI.resolve("2/infoset-cdata.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { Text summary = entry.getSummaryElement(); assertNotNull(summary); assertEquals(Text.Type.TEXT, summary.getTextType()); String value = summary.getValue(); assertEquals("Some <b>bold</b> text.", value); } } @SuppressWarnings("deprecation") @Test public void testSection2InfosetCharRef() throws Exception { // http://feedvalidator.org/testcases/atom/2/infoset-char-ref.xml IRI uri = baseURI.resolve("2/infoset-char-ref.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { DateTime updated = entry.getUpdatedElement(); assertNotNull(updated); assertNotNull(updated.getValue()); assertNotNull(updated.getValue().getDate()); assertEquals(103, updated.getValue().getDate().getYear()); } } @Test public void testSection2InfosetElementWhitespace() throws Exception { // http://feedvalidator.org/testcases/atom/2/infoset-element-whitespace.xml IRI uri = baseURI.resolve("2/infoset-element-whitespace.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); Link link = feed.getAlternateLink(); assertEquals(new IRI("http://example.org/"), link.getResolvedHref()); // the feed has a second alternate link that we will ignore } @Test public void testSection2InfosetEmpty1() throws Exception { // http://feedvalidator.org/testcases/atom/2/infoset-empty1.xml IRI uri = baseURI.resolve("2/infoset-empty1.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); Entry entry = feed.getEntries().get(0); assertEquals("", entry.getTitle()); } @Test public void testSection2InfosetEmpty2() throws Exception { // http://feedvalidator.org/testcases/atom/2/infoset-empty2.xml IRI uri = baseURI.resolve("2/infoset-empty2.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); Entry entry = feed.getEntries().get(0); assertEquals("", entry.getTitle()); } @Test public void testSection2InfosetSingleQuote() throws Exception { // http://feedvalidator.org/testcases/atom/2/infoset-quote-single.xml IRI uri = baseURI.resolve("2/infoset-quote-single.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("http://example.org/"), doc.getRoot().getAlternateLink().getResolvedHref()); } @Test public void testSection2InvalidXmlBase() throws Exception { // http://feedvalidator.org/testcases/atom/2/invalid-xml-base.xml IRI uri = baseURI.resolve("2/invalid-xml-base.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); try { feed.getBaseUri(); } catch (Exception e) { assertTrue(e instanceof IRISyntaxException); } } @Test public void testSection2InvalidXmlLang() throws Exception { // http://feedvalidator.org/testcases/atom/2/invalid-xml-lang.xml IRI uri = baseURI.resolve("2/invalid-xml-lang.xml"); Document<Feed> doc = parse(uri); assertFalse(java.util.Locale.US.equals(doc.getRoot().getLocale())); } @Test public void testSection2Iri() throws Exception { // http://feedvalidator.org/testcases/atom/2/iri.xml IRI uri = baseURI.resolve("2/iri.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); assertNotNull(feed.getIdElement().getValue()); assertNotNull(feed.getAuthor().getUriElement().getValue()); assertNotNull(feed.getAuthor().getUriElement().getValue().toASCIIString()); } @Test public void testSection2XmlBaseAmbiguous() throws Exception { // http://feedvalidator.org/testcases/atom/2/xml-base-ambiguous.xml IRI uri = baseURI.resolve("2/xml-base-ambiguous.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("http://example.org/"), doc.getRoot().getAlternateLink().getResolvedHref()); } @Test public void testSection2XmlBaseElemEqDoc() throws Exception { // http://feedvalidator.org/testcases/atom/2/xml-base-elem-eq-doc.xml IRI uri = baseURI.resolve("2/xml-base-elem-eq-doc.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals(new IRI("http://www.feedvalidator.org/2003/12/13/atom03"), entry.getAlternateLink() .getResolvedHref()); } @Test public void testSection2XmlBaseElemNeDoc() throws Exception { // http://feedvalidator.org/testcases/atom/2/xml-base-elem-ne-doc.xml IRI uri = baseURI.resolve("2/xml-base-elem-ne-doc.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("http://www.feedvalidator.org/testcases/atom/2/xml-base-elem-ne-doc.xml"), doc.getRoot() .getSelfLink().getResolvedHref()); } @Test public void xtestSection2XmlBase() throws Exception { // http://feedvalidator.org/testcases/atom/2/xml-base.xml IRI uri = baseURI.resolve("2/xml-base.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Link> links = feed.getLinks(); for (Link link : links) { assertEquals(new IRI("http://example.org/index.html"), link.getResolvedHref()); } } @Test public void testSection2XmlLangBlank() throws Exception { // http://feedvalidator.org/testcases/atom/2/xml-lang-blank.xml IRI uri = baseURI.resolve("2/xml-lang-blank.xml"); Document<Feed> doc = parse(uri); assertNull(doc.getRoot().getLocale()); } @Test public void testSection2XmlLang() throws Exception { // http://feedvalidator.org/testcases/atom/2/xml-lang.xml IRI uri = baseURI.resolve("2/xml-lang.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); assertEquals("en-us", feed.getLanguage()); assertTrue(feed.getLocale().equals(java.util.Locale.US)); } @Test public void testSection3WsAuthorUri() throws Exception { // http://feedvalidator.org/testcases/atom/3/ws-author-uri.xml IRI uri = baseURI.resolve("3/ws-author-uri.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); Person author = feed.getAuthor(); try { author.getUriElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IRISyntaxException); } } @Test public void testSection3WsCategoryScheme() throws Exception { // http://feedvalidator.org/testcases/atom/3/ws-category-scheme.xml IRI uri = baseURI.resolve("3/ws-category-scheme.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); assertNotNull(entries); for (Entry entry : entries) { List<Category> cats = entry.getCategories(); for (Category cat : cats) { try { cat.getScheme(); } catch (Exception e) { assertTrue(e instanceof IRISyntaxException); } } } } @Test public void testSection3WsContentSrc() throws Exception { // http://feedvalidator.org/testcases/atom/3/ws-content-src.xml IRI uri = baseURI.resolve("3/ws-content-src.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); assertNotNull(entries); for (Entry entry : entries) { Content content = entry.getContentElement(); assertNotNull(content); try { content.getSrc(); } catch (Exception e) { assertTrue(e instanceof IRISyntaxException); } } } @Test public void testSection3WsEntryId() throws Exception { // http://feedvalidator.org/testcases/atom/3/ws-entry-id.xml IRI uri = baseURI.resolve("3/ws-entry-id.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); assertNotNull(entries); for (Entry entry : entries) { IRIElement id = entry.getIdElement(); assertNotNull(id); try { id.getValue(); } catch (Exception e) { assertTrue(e instanceof IRISyntaxException); } } } @Test public void testSection3WsEntryPublished() throws Exception { // http://feedvalidator.org/testcases/atom/3/ws-entry-published.xml IRI uri = baseURI.resolve("3/ws-entry-published.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); assertNotNull(entries); for (Entry entry : entries) { try { entry.getPublishedElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); // bad date } } } @Test public void testSection3WsEntryUpdated() throws Exception { // http://feedvalidator.org/testcases/atom/3/ws-entry-updated.xml IRI uri = baseURI.resolve("3/ws-entry-updated.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); assertNotNull(entries); for (Entry entry : entries) { try { entry.getUpdatedElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); // bad date } } } @Test public void testSection3WsFeedIcon() throws Exception { // http://feedvalidator.org/testcases/atom/3/ws-feed-icon.xml IRI uri = baseURI.resolve("3/ws-feed-icon.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); try { feed.getIconElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IRISyntaxException); } } @Test public void testSection3WsFeedId() throws Exception { // http://feedvalidator.org/testcases/atom/3/ws-feed-id.xml IRI uri = baseURI.resolve("3/ws-feed-id.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); try { feed.getIdElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IRISyntaxException); } } @Test public void testSection3WsFeedLogo() throws Exception { // http://feedvalidator.org/testcases/atom/3/ws-feed-logo.xml IRI uri = baseURI.resolve("3/ws-feed-logo.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); try { feed.getLogoElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IRISyntaxException); } } @Test public void testSection3WsFeedUpdated() throws Exception { // http://feedvalidator.org/testcases/atom/3/ws-feed-updated.xml IRI uri = baseURI.resolve("3/ws-feed-updated.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); try { feed.getUpdatedElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testSection3WsGeneratorUri() throws Exception { // http://feedvalidator.org/testcases/atom/3/ws-generator-uri.xml IRI uri = baseURI.resolve("3/ws-generator-uri.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); Generator gen = feed.getGenerator(); assertNotNull(gen); try { gen.getUri(); } catch (Exception e) { assertTrue(e instanceof IRISyntaxException); } } @Test public void testSection3WsLinkHref() throws Exception { // http://feedvalidator.org/testcases/atom/3/ws-link-href.xml IRI uri = baseURI.resolve("3/ws-link-href.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Link> links = feed.getLinks(); for (Link link : links) { try { link.getHref(); } catch (Exception e) { assertTrue(e instanceof IRISyntaxException); } } } @Test public void testSection3WsLinkRel() throws Exception { // http://feedvalidator.org/testcases/atom/3/ws-link-rel.xml IRI uri = baseURI.resolve("3/ws-link-rel.xml"); Document<Feed> doc = parse(uri); assertNull(doc.getRoot().getAlternateLink()); } @Test public void testSection3WsXmlBase() throws Exception { // http://feedvalidator.org/testcases/atom/3/ws-xml-base.xml IRI uri = baseURI.resolve("3/ws-xml-base.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { try { entry.getBaseUri(); } catch (Exception e) { assertTrue(e instanceof IRISyntaxException); } } } @Test public void testSection311SummaryTypeMime() throws Exception { // http://feedvalidator.org/testcases/atom/3.1.1/summary_type_mime.xml IRI uri = baseURI.resolve("3.1.1/summary_type_mime.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); try { feed.getEntries(); } catch (Exception e) { assertTrue(e instanceof OMException); } } @Test public void testSection3111EscapedText() throws Exception { // http://feedvalidator.org/testcases/atom/3.1.1.1/escaped_text.xml IRI uri = baseURI.resolve("3.1.1.1/escaped_text.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { Text text = entry.getSummaryElement(); assertNotNull(text); assertEquals(Text.Type.TEXT, text.getTextType()); String value = text.getValue(); assertEquals("Some&nbsp;escaped&nbsp;html", value); } } @Test public void testSection3111ExampleTextTitle() throws Exception { // http://feedvalidator.org/testcases/atom/3.1.1.1/example_text_title.xml IRI uri = baseURI.resolve("3.1.1.1/example_text_title.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { Text title = entry.getTitleElement(); assertNotNull(title); assertEquals(Text.Type.TEXT, title.getTextType()); String value = title.getValue(); assertEquals("Less: <", value.trim()); } } @Test public void testSection3111SummaryTypeMime() throws Exception { // http://feedvalidator.org/testcases/atom/3.1.1.1/summary_type_mime.xml IRI uri = baseURI.resolve("3.1.1.1/summary_type_mime.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); try { feed.getEntries(); } catch (Exception e) { assertTrue(e instanceof OMException); } } @Test public void testSection3112ExampleHtmlTitle() throws Exception { // http://feedvalidator.org/testcases/atom/3.1.1.2/example_html_title.xml IRI uri = baseURI.resolve("3.1.1.2/example_html_title.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { Text title = entry.getTitleElement(); assertEquals(Text.Type.HTML, title.getTextType()); String value = title.getValue(); assertEquals("Less: <em> &lt; </em>", value.trim()); } } @Test public void testSection3112InvalidHtml() throws Exception { // http://feedvalidator.org/testcases/atom/3.1.1.2/invalid_html.xml IRI uri = baseURI.resolve("3.1.1.2/invalid_html.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals("<a", entry.getSummary().trim()); } @Test public void testSection3112TextWithEscapedHtml() throws Exception { // http://feedvalidator.org/testcases/atom/3.1.1.2/text_with_escaped_html.xml IRI uri = baseURI.resolve("3.1.1.2/text_with_escaped_html.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals("So I was reading <a href=\"http://example.com/\">example.com</a> the other day, it's really interesting.", entry.getSummary().trim()); } @Test public void testSection3112ValidHtml() throws Exception { // http://feedvalidator.org/testcases/atom/3.1.1.2/valid_html.xml IRI uri = baseURI.resolve("3.1.1.2/valid_html.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals("<h3>Heading</h3>", entry.getSummary().trim()); } @Test public void testSection3113ExampleXhtmlSummary1() throws Exception { // http://feedvalidator.org/testcases/atom/3.1.1.3/example_xhtml_summary1.xml IRI uri = baseURI.resolve("3.1.1.3/example_xhtml_summary1.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { Text summary = entry.getSummaryElement(); assertNotNull(summary); assertEquals(Text.Type.XHTML, summary.getTextType()); Div div = summary.getValueElement(); assertNotNull(div); } } @Test public void testSection3113ExampleXhtmlSummary2() throws Exception { // http://feedvalidator.org/testcases/atom/3.1.1.3/example_xhtml_summary2.xml IRI uri = baseURI.resolve("3.1.1.3/example_xhtml_summary2.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { Text summary = entry.getSummaryElement(); assertNotNull(summary); assertEquals(Text.Type.XHTML, summary.getTextType()); Div div = summary.getValueElement(); assertNotNull(div); } } @Test public void testSection3113ExampleXhtmlSummary3() throws Exception { // http://feedvalidator.org/testcases/atom/3.1.1.3/example_xhtml_summary3.xml IRI uri = baseURI.resolve("3.1.1.3/example_xhtml_summary3.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { Text summary = entry.getSummaryElement(); assertNotNull(summary); assertEquals(Text.Type.XHTML, summary.getTextType()); Div div = summary.getValueElement(); assertNotNull(div); } } @Test public void testSection3113MissingXhtmlDiv() throws Exception { // http://feedvalidator.org/testcases/atom/3.1.1.3/missing_xhtml_div.xml IRI uri = baseURI.resolve("3.1.1.3/missing_xhtml_div.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { Text summary = entry.getSummaryElement(); assertNotNull(summary); assertEquals(Text.Type.XHTML, summary.getTextType()); Div div = summary.getValueElement(); assertNull(div); } } @Test public void testSection3113XhtmlNamedEntity() throws Exception { // http://feedvalidator.org/testcases/atom/3.1.1.3/xhtml_named_entity.xml IRI uri = baseURI.resolve("3.1.1.3/xhtml_named_entity.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); try { feed.getEntries(); } catch (Exception e) { assertTrue(e instanceof OMException); } } @Test public void testSection321ContainsEmail() throws Exception { // http://feedvalidator.org/testcases/atom/3.2.1/contains-email.xml // Note: not validating input right now } @Test public void testSection321MultipleNames() throws Exception { // http://feedvalidator.org/testcases/atom/3.2.1/multiple-names.xml IRI uri = baseURI.resolve("3.2.1/multiple-names.xml"); Document<Feed> doc = parse(uri); assertEquals("George Washington", doc.getRoot().getContributors().get(0).getName()); } @Test public void testSection321NoName() throws Exception { // http://feedvalidator.org/testcases/atom/3.2.1/no-name.xml IRI uri = baseURI.resolve("3.2.1/no-name.xml"); Document<Feed> doc = parse(uri); assertNull(doc.getRoot().getContributors().get(0).getName()); } @Test public void testSection322InvalidUri() throws Exception { // http://feedvalidator.org/testcases/atom/3.2.2/invalid-uri.xml IRI uri = baseURI.resolve("3.2.2/invalid-uri.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Person> contr = feed.getContributors(); for (Person person : contr) { try { person.getUriElement(); } catch (Exception e) { assertFalse(e instanceof IRISyntaxException); } } } @Test public void testSection322MultipleUris() throws Exception { // http://feedvalidator.org/testcases/atom/3.2.2/multiple-uris.xml IRI uri = baseURI.resolve("3.2.2/multiple-uris.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("http://example.com/~jane/"), doc.getRoot().getContributors().get(0).getUri()); } @Test public void testSection322RelativeRef() throws Exception { // http://feedvalidator.org/testcases/atom/3.2.2/relative-ref.xml IRI uri = baseURI.resolve("3.2.2/relative-ref.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Person> contr = feed.getContributors(); for (Person person : contr) { assertEquals(new IRI("~jane/"), person.getUriElement().getValue()); assertEquals(uri.resolve("~jane/"), person.getUriElement().getResolvedValue()); } } @Test public void testSection323EmailRss20Style() throws Exception { // http://feedvalidator.org/testcases/atom/3.2.3/email-rss20-style.xml IRI uri = baseURI.resolve("3.2.3/email-rss20-style.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Person> contr = feed.getContributors(); for (Person person : contr) { try { new IRI(person.getEmail()); } catch (Exception e) { assertTrue(e instanceof IRISyntaxException); } } } @Test public void testSection323EmailWithName() throws Exception { // http://feedvalidator.org/testcases/atom/3.2.3/email-with-name.xml IRI uri = baseURI.resolve("3.2.3/email-with-name.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Person> contr = feed.getContributors(); for (Person person : contr) { try { new IRI(person.getEmail()); } catch (Exception e) { assertTrue(e instanceof IRISyntaxException); } } } @Test public void testSection323EmailWithPlus() throws Exception { // http://feedvalidator.org/testcases/atom/3.2.3/email-with-plus.xml IRI uri = baseURI.resolve("3.2.3/email-with-plus.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Person> contr = feed.getContributors(); for (Person person : contr) { new IRI(person.getEmail()); } } @Test public void testSection323InvalidEmail() throws Exception { // http://feedvalidator.org/testcases/atom/3.2.3/invalid-email.xml IRI uri = baseURI.resolve("3.2.3/invalid-email.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Person> contr = feed.getContributors(); for (Person person : contr) { try { new IRI(person.getEmail()); } catch (Exception e) { assertTrue(e instanceof IRISyntaxException); } } } @Test public void testSection323MultipleEmails() throws Exception { // http://feedvalidator.org/testcases/atom/3.2.3/multiple-emails.xml IRI uri = baseURI.resolve("3.2.3/multiple-emails.xml"); Document<Feed> doc = parse(uri); assertEquals("jane@example.com", doc.getRoot().getContributors().get(0).getEmail()); } @Test public void testSection33DuplicateUpdated() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/duplicate-updated.xml IRI uri = baseURI.resolve("3.3/duplicate-updated.xml"); Document<Feed> doc = parse(uri); Date d = AtomDate.parse("2003-12-13T18:30:02Z"); for (Entry entry : doc.getRoot().getEntries()) { Date date = entry.getUpdated(); assertEquals(d, date); } } @Test public void testSection33LowercaseUpdated() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/lowercase-updated.xml IRI uri = baseURI.resolve("3.3/lowercase-updated.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); try { feed.getUpdatedElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } @Test public void testSection33PublishedBadDay() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_bad_day.xml IRI uri = baseURI.resolve("3.3/published_bad_day.xml"); Document<Feed> doc = parse(uri); Date d = AtomDate.parse("2003-07-32T15:51:30-05:00"); assertEquals(d, doc.getRoot().getEntries().get(0).getPublished()); } @Test public void testSection33PublishedBadDay2() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_bad_day2.xml IRI uri = baseURI.resolve("3.3/published_bad_day2.xml"); Document<Feed> doc = parse(uri); // this is an invalid date, but we don't care because we're not doing // validation. Better run those feeds through the feed validator :-) Date d = AtomDate.parse("2003-06-31T15:51:30-05:00"); assertEquals(d, doc.getRoot().getEntries().get(0).getPublished()); } @Test public void testSection33PublishedBadHours() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_bad_hours.xml IRI uri = baseURI.resolve("3.3/published_bad_hours.xml"); Document<Feed> doc = parse(uri); Date d = AtomDate.parse("2003-07-01T25:51:30-05:00"); assertEquals(d, doc.getRoot().getEntries().get(0).getPublished()); } @Test public void testSecton33PublishedBadMinutes() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_bad_minutes.xml IRI uri = baseURI.resolve("3.3/published_bad_minutes.xml"); Document<Feed> doc = parse(uri); Date d = AtomDate.parse("2003-07-01T01:61:30-05:00"); assertEquals(d, doc.getRoot().getEntries().get(0).getPublished()); } @Test public void testSection33PublishedBadMonth() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_bad_month.xml IRI uri = baseURI.resolve("3.3/published_bad_month.xml"); Document<Feed> doc = parse(uri); Date d = AtomDate.parse("2003-13-01T15:51:30-05:00"); assertEquals(d, doc.getRoot().getEntries().get(0).getPublished()); } @Test public void testSection33PublishedBadSeconds() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_bad_seconds.xml IRI uri = baseURI.resolve("3.3/published_bad_seconds.xml"); Document<Feed> doc = parse(uri); Date d = AtomDate.parse("2003-07-01T01:55:61-05:00"); assertEquals(d, doc.getRoot().getEntries().get(0).getPublished()); } @Test public void testSection33PublishedDateOnly() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_date_only.xml IRI uri = baseURI.resolve("3.3/published_date_only.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { try { entry.getPublishedElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } } @Test public void testSection33PublishedExtraSpaces() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_extra_spaces.xml IRI uri = baseURI.resolve("3.3/published_extra_spaces.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { try { entry.getPublishedElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } } @Test public void testSection33PublishedExtraSpaces2() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_extra_spaces2.xml IRI uri = baseURI.resolve("3.3/published_extra_spaces2.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { try { entry.getPublishedElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } } @Test public void testSection33PublishedExtraSpaces3() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_extra_spaces3.xml IRI uri = baseURI.resolve("3.3/published_extra_spaces3.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { try { entry.getPublishedElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } } @Test public void testSection33PublishedExtraSpaces4() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_extra_spaces4.xml IRI uri = baseURI.resolve("3.3/published_extra_spaces4.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { try { entry.getPublishedElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } } @Test public void testSection33PublishedExtraSpaces5() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_extra_spaces5.xml IRI uri = baseURI.resolve("3.3/published_extra_spaces5.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { try { entry.getPublishedElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } } @Test public void testSection33PublishedFractionalSecond() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_fractional_second.xml IRI uri = baseURI.resolve("3.3/published_fractional_second.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { entry.getPublishedElement().getValue(); } } @Test public void testSection33PublishedHoursMinutes() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_hours_minutes.xml IRI uri = baseURI.resolve("3.3/published_hours_minutes.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { try { entry.getPublishedElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } } @Test public void testSection33PublishedNoColons() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_no_colons.xml IRI uri = baseURI.resolve("3.3/published_no_colons.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { try { entry.getPublishedElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } } @Test public void testSection33PublishedNoHyphens() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_no_hyphens.xml IRI uri = baseURI.resolve("3.3/published_no_hyphens.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { try { entry.getPublishedElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } } @Test public void testSection33PublishedNoT() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_no_t.xml IRI uri = baseURI.resolve("3.3/published_no_t.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { try { entry.getPublishedElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } } @Test public void testSection33PublishedNoTimezoneColon() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_no_timezone_colon.xml IRI uri = baseURI.resolve("3.3/published_no_timezone_colon.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { try { entry.getPublishedElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } } @Test public void testSection33PublishedNoYear() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_no_year.xml IRI uri = baseURI.resolve("3.3/published_no_year.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { try { entry.getPublishedElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } } @Test public void testSection33PublishedSeconds() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_seconds.xml IRI uri = baseURI.resolve("3.3/published_seconds.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { entry.getPublishedElement().getValue(); } } @Test public void testSection33PublishedUtc() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_utc.xml IRI uri = baseURI.resolve("3.3/published_utc.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { entry.getPublishedElement().getValue(); } } @Test public void testSection33PublishedWrongFormat() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_wrong_format.xml IRI uri = baseURI.resolve("3.3/published_wrong_format.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { try { entry.getPublishedElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } } @Test public void testSection33PublishedYearAndMonth() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_year_and_month.xml IRI uri = baseURI.resolve("3.3/published_year_and_month.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { try { entry.getPublishedElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } } @Test public void testSection33PublishedYearOnly() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/published_year_only.xml IRI uri = baseURI.resolve("3.3/published_year_only.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { try { entry.getPublishedElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } } @Test public void testSection33UpdatedExample2() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/updated-example2.xml IRI uri = baseURI.resolve("3.3/updated-example2.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { entry.getUpdatedElement().getValue(); } } @Test public void testSection33UpdatedExample3() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/updated-example3.xml IRI uri = baseURI.resolve("3.3/updated-example3.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { entry.getUpdatedElement().getValue(); } } @Test public void testSection33UpdatedExample4() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/updated-example4.xml IRI uri = baseURI.resolve("3.3/updated-example4.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { entry.getUpdatedElement().getValue(); } } @Test public void testSection33UpdatedFuture() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/updated-future.xml IRI uri = baseURI.resolve("3.3/updated-future.xml"); Document<Feed> doc = parse(uri); Date d = AtomDate.parse("2103-12-13T18:30:02Z"); assertEquals(d, doc.getRoot().getEntries().get(0).getUpdated()); } @Test public void testSection33UpdatedPast() throws Exception { // http://feedvalidator.org/testcases/atom/3.3/updated-past.xml IRI uri = baseURI.resolve("3.3/updated-past.xml"); Document<Feed> doc = parse(uri); Date d = AtomDate.parse("0103-12-13T18:30:02Z"); assertEquals(d, doc.getRoot().getEntries().get(0).getUpdated()); } @Test public void testSection411AuthorAtEntryOnly() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/author-at-entry-only.xml IRI uri = baseURI.resolve("4.1.1/author-at-entry-only.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { assertNotNull(entry.getAuthor()); } } @Test public void testSection411AuthorAtFeedAndEntry() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/author-at-feed-and-entry.xml IRI uri = baseURI.resolve("4.1.1/author-at-feed-and-entry.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); assertNotNull(feed.getAuthor()); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { assertNotNull(entry.getAuthor()); } } @Test public void testSection411AuthorAtFeedOnly() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/author-at-feed-only.xml IRI uri = baseURI.resolve("4.1.1/author-at-feed-only.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); assertNotNull(feed.getAuthor()); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { assertNull(entry.getAuthor()); } } @Test public void testSection411AuthorlessWithNoEntries() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/authorless-with-no-entries.xml IRI uri = baseURI.resolve("4.1.1/authorless-with-no-entries.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); assertNull(feed.getAuthor()); } @Test public void testSection411AuthorlessWithOneEntry() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/authorless-with-one-entry.xml IRI uri = baseURI.resolve("4.1.1/authorless-with-one-entry.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); assertNull(feed.getAuthor()); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { assertNull(entry.getAuthor()); } } @Test public void testSection411DuplicateEntries() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/duplicate-entries.xml IRI uri = baseURI.resolve("4.1.1/duplicate-entries.xml"); Document<Feed> doc = parse(uri); Entry e1 = doc.getRoot().getEntries().get(0); Entry e2 = doc.getRoot().getEntries().get(1); assertEquals(e1.getId(), e2.getId()); assertEquals(e1.getUpdated(), e2.getUpdated()); } @Test public void testSection411LinkRelFull() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/link-rel-full.xml IRI uri = baseURI.resolve("4.1.1/link-rel-full.xml"); Document<Feed> doc = parse(uri); Link link = doc.getRoot().getLink("http://xmlns.com/foaf/0.1/"); assertNotNull(link); assertEquals(new IRI("http://example.org/foaf"), link.getResolvedHref()); } @Test public void testSection411MisplacedMetadata() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/misplaced-metadata.xml IRI uri = baseURI.resolve("4.1.1/misplaced-metadata.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6"), doc.getRoot().getId()); } @Test public void testSection411MissingId() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/missing-id.xml IRI uri = baseURI.resolve("4.1.1/missing-id.xml"); Document<Feed> doc = parse(uri); assertNull(doc.getRoot().getId()); } @Test public void testSection411MissingSelf() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/missing-self.xml IRI uri = baseURI.resolve("4.1.1/missing-self.xml"); Document<Feed> doc = parse(uri); assertNull(doc.getRoot().getSelfLink()); } @Test public void testSection411MissingTitles() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/missing-titles.xml IRI uri = baseURI.resolve("4.1.1/missing-titles.xml"); Document<Feed> doc = parse(uri); assertNull(doc.getRoot().getTitle()); } @Test public void testSection411MissingUpdated() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/missing-updated.xml IRI uri = baseURI.resolve("4.1.1/missing-updated.xml"); Document<Feed> doc = parse(uri); assertNull(doc.getRoot().getUpdated()); } @Test public void testSection411MultipleAlternatesDiffering() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/multiple-alternates-differing.xml IRI uri = baseURI.resolve("4.1.1/multiple-alternates-differing.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Link> links = feed.getLinks(Link.REL_ALTERNATE); assertEquals(2, links.size()); } @Test public void testSection411MultipleAlternatesMatching() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/multiple-alternates-matching.xml IRI uri = baseURI.resolve("4.1.1/multiple-alternates-matching.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("http://example.org/front-page.html"), doc.getRoot().getAlternateLink().getResolvedHref()); } @Test public void testSection411MultipleAuthors() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/multiple-authors.xml IRI uri = baseURI.resolve("4.1.1/multiple-authors.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Person> authors = feed.getAuthors(); assertEquals(2, authors.size()); } @Test public void testSection411MultipleCategories() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/multiple-categories.xml IRI uri = baseURI.resolve("4.1.1/multiple-categories.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Category> cats = feed.getCategories(); assertEquals(2, cats.size()); } @Test public void testSection411MultipleContributors() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/multiple-contributors.xml IRI uri = baseURI.resolve("4.1.1/multiple-contributors.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Person> contr = feed.getContributors(); assertEquals(2, contr.size()); } @Test public void testSection411MultipleGenerators() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/multiple-generators.xml IRI uri = baseURI.resolve("4.1.1/multiple-generators.xml"); Document<Feed> doc = parse(uri); Generator g = doc.getRoot().getGenerator(); assertEquals(new IRI("http://www.example.com/"), g.getResolvedUri()); assertEquals("Example Toolkit", g.getText().trim()); } @Test public void testSection411MultipleIcons() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/multiple-icons.xml IRI uri = baseURI.resolve("4.1.1/multiple-icons.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("http://feedvalidator.org/big.icon"), doc.getRoot().getIcon()); } @Test public void testSection411MultipleIds() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/multiple-ids.xml IRI uri = baseURI.resolve("4.1.1/multiple-ids.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6"), doc.getRoot().getId()); } @Test public void testSection411MultipleLogos() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/multiple-logos.xml IRI uri = baseURI.resolve("4.1.1/multiple-logos.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("http://feedvalidator.org/small.jpg"), doc.getRoot().getLogo()); } @Test public void testSection411MultipleRelatedMatching() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/multiple-related-matching.xml IRI uri = baseURI.resolve("4.1.1/multiple-related-matching.xml"); Document<Feed> doc = parse(uri); List<Link> links = doc.getRoot().getLinks("related"); assertEquals(2, links.size()); assertEquals(new IRI("http://example.org/front-page.html"), links.get(0).getResolvedHref()); assertEquals(new IRI("http://example.org/second-page.html"), links.get(1).getResolvedHref()); } @Test public void testSection411MultipleRights() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/multiple-rights.xml IRI uri = baseURI.resolve("4.1.1/multiple-rights.xml"); Document<Feed> doc = parse(uri); assertEquals("Public Domain", doc.getRoot().getRights()); } @Test public void testSection411MultipleSubtitles() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/multiple-subtitles.xml IRI uri = baseURI.resolve("4.1.1/multiple-subtitles.xml"); Document<Feed> doc = parse(uri); assertEquals("A unique feed, just like all the others", doc.getRoot().getSubtitle()); } @Test public void testSection411MultipleTitles() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/multiple-titles.xml IRI uri = baseURI.resolve("4.1.1/multiple-titles.xml"); Document<Feed> doc = parse(uri); assertEquals("Example Feed", doc.getRoot().getTitle()); } @Test public void testSection411MultipleUpdateds() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/multiple-updateds.xml IRI uri = baseURI.resolve("4.1.1/multiple-updateds.xml"); Document<Feed> doc = parse(uri); Date d = AtomDate.parse("2003-12-13T18:30:02Z"); assertEquals(d, doc.getRoot().getUpdated()); } @Test public void testSection411ZeroEntries() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1/zero-entries.xml IRI uri = baseURI.resolve("4.1.1/zero-entries.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); assertEquals(0, feed.getEntries().size()); } @Test public void testSection4111ContentSrc() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1.1/content-src.xml IRI uri = baseURI.resolve("4.1.1.1/content-src.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { Content content = entry.getContentElement(); assertNotNull(content.getSrc()); } } @Test public void testSection4111EmptyContent() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1.1/empty-content.xml IRI uri = baseURI.resolve("4.1.1.1/empty-content.xml"); Document<Feed> doc = parse(uri); assertEquals("", doc.getRoot().getEntries().get(0).getContent()); } @Test public void testSection4111EmptyTitle() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1.1/empty-title.xml IRI uri = baseURI.resolve("4.1.1.1/empty-title.xml"); Document<Feed> doc = parse(uri); assertEquals("", doc.getRoot().getEntries().get(0).getTitle()); } @Test public void testSection4111NoContentOrSummary() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.1.1/no-content-or-summary.xml IRI uri = baseURI.resolve("4.1.1.1/no-content-or-summary.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertNull(entry.getContent()); assertNull(entry.getSummary()); } @Test public void testSection412AlternateNoContent() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/alternate-no-content.xml IRI uri = baseURI.resolve("4.1.2/alternate-no-content.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { assertEquals(1, entry.getLinks(Link.REL_ALTERNATE).size()); assertNotNull(entry.getSummaryElement()); } } @Test public void testSection412ContentBase64NoSummary() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/content-base64-no-summary.xml IRI uri = baseURI.resolve("4.1.2/content-base64-no-summary.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { assertNull(entry.getSummaryElement()); assertNotNull(entry.getContentElement()); Content mediaContent = entry.getContentElement(); DataHandler dataHandler = mediaContent.getDataHandler(); InputStream in = (ByteArrayInputStream)dataHandler.getContent(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int n = -1; while ((n = in.read()) > -1) { baos.write(n); } assertEquals("Some more text.", baos.toString()); } } @Test public void testSection412ContentNoAlternate() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/content-no-alternate.xml IRI uri = baseURI.resolve("4.1.2/content-no-alternate.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { assertEquals(0, entry.getLinks(Link.REL_ALTERNATE).size()); assertNotNull(entry.getContentElement()); } } @Test public void testSection412ContentSrcNoSummary() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/content-src-no-summary.xml IRI uri = baseURI.resolve("4.1.2/content-src-no-summary.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertNull(entry.getSummary()); assertEquals(new IRI("http://example.org/2003/12/13/atom03"), entry.getContentElement().getResolvedSrc()); } @Test public void testSection412EntrySourceAuthor() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/entry-source-author.xml IRI uri = baseURI.resolve("4.1.2/entry-source-author.xml"); Document<Entry> doc = parse(uri); Entry entry = doc.getRoot(); assertNotNull(entry); assertNotNull(entry.getSource()); assertNotNull(entry.getSource().getAuthor()); } @Test public void testSection412LinkFullUri() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/link-full-uri.xml IRI uri = baseURI.resolve("4.1.2/link-full-uri.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { List<Link> links = entry.getLinks("http://xmlns.com/foaf/0.1/"); assertEquals(1, links.size()); } } @Test public void testSection412LinkSameRelDifferentTypes() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/link-same-rel-different-types.xml IRI uri = baseURI.resolve("4.1.2/link-same-rel-different-types.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { List<Link> links = entry.getLinks(Link.REL_ALTERNATE); assertEquals(2, links.size()); } } @Test public void testSection412LinkSameRelTypeDifferentHreflang() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/link-same-rel-type-different-hreflang.xml IRI uri = baseURI.resolve("4.1.2/link-same-rel-type-different-hreflang.xml"); Document<Feed> doc = parse(uri); List<Link> links = doc.getRoot().getEntries().get(0).getLinks("alternate"); assertEquals(2, links.size()); assertEquals("es-es", links.get(0).getHrefLang()); assertEquals("en-us", links.get(1).getHrefLang()); } @Test public void testSection412LinkSameRelTypeHreflang() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/link-same-rel-type-hreflang.xml IRI uri = baseURI.resolve("4.1.2/link-same-rel-type-hreflang.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals(new IRI("http://example.org/2003/12/13/atom02"), entry.getAlternateLink().getResolvedHref()); } @Test public void testSection412LinkSameRelTypeNoHreflang() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/link-same-rel-type-no-hreflang.xml IRI uri = baseURI.resolve("4.1.2/link-same-rel-type-no-hreflang.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals(new IRI("http://example.org/2003/12/13/atom02"), entry.getAlternateLink().getResolvedHref()); } @Test public void testSection412MissingId() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/missing-id.xml IRI uri = baseURI.resolve("4.1.2/missing-id.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertNull(entry.getId()); } @Test public void testSection412MissingTitle() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/missing-title.xml IRI uri = baseURI.resolve("4.1.2/missing-title.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertNull(entry.getTitle()); } @Test public void testSection412MissingUpdated() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/missing-updated.xml IRI uri = baseURI.resolve("4.1.2/missing-updated.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertNull(entry.getUpdated()); } @Test public void testSection412MultiEnclosureTest() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/multi-enclosure-test.xml IRI uri = baseURI.resolve("4.1.2/multi-enclosure-test.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { List<Link> enclosures = entry.getLinks(Link.REL_ENCLOSURE); assertEquals(2, enclosures.size()); } } @Test public void testSection412MultipleCategories() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/multiple-categories.xml IRI uri = baseURI.resolve("4.1.2/multiple-categories.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { List<Category> cats = entry.getCategories(); assertEquals(2, cats.size()); } } @Test public void testSection412MultipleContents() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/multiple-contents.xml // Note: not implemented IRI uri = baseURI.resolve("4.1.2/multiple-contents.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals("No big deal", entry.getContent()); } @Test public void testSection412MultipleContributors() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/multiple-contributors.xml IRI uri = baseURI.resolve("4.1.2/multiple-contributors.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { List<Person> contr = entry.getContributors(); assertEquals(2, contr.size()); } } @Test public void testSection412MultipleIds() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/multiple-ids.xml IRI uri = baseURI.resolve("4.1.2/multiple-ids.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a"), doc.getRoot().getEntries().get(0) .getId()); } @Test public void testSection412MultiplePublished() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/multiple-published.xml IRI uri = baseURI.resolve("4.1.2/multiple-published.xml"); Document<Feed> doc = parse(uri); Date d = AtomDate.parse("2003-12-11T11:13:56Z"); assertEquals(d, doc.getRoot().getEntries().get(0).getPublished()); } @Test public void testSection412MultipleRights() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/multiple-rights.xml IRI uri = baseURI.resolve("4.1.2/multiple-rights.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals("Public Domain", entry.getRights()); } @Test public void testSection412MultipleSources() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/multiple-sources.xml IRI uri = baseURI.resolve("4.1.2/multiple-sources.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Source source = entry.getSource(); assertEquals(new IRI("urn:uuid:9b056ae0-f778-11d9-8cd6-0800200c9a66"), source.getId()); } @Test public void testSection412MultipleSummaries() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/multiple-summaries.xml IRI uri = baseURI.resolve("4.1.2/multiple-summaries.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals("Some text.", entry.getSummary()); } @Test public void testSection412MultipleTitles() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/multiple-titles.xml IRI uri = baseURI.resolve("4.1.2/multiple-titles.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals("Atom-Powered Robots Run Amok", entry.getTitle()); } @Test public void testSection412MultipleUpdated() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/multiple-updated.xml IRI uri = baseURI.resolve("4.1.2/multiple-updated.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Date d = AtomDate.parse("2003-12-13T18:30:02Z"); assertEquals(d, entry.getUpdated()); } @Test public void testSection412NoContentOrAlternate() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/no-content-or-alternate.xml IRI uri = baseURI.resolve("4.1.2/no-content-or-alternate.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertNull(entry.getContent()); assertNull(entry.getAlternateLink()); } @Test public void testSection412RelatedSameRelTypeHreflang() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/related-same-rel-type-hreflang.xml IRI uri = baseURI.resolve("4.1.2/related-same-rel-type-hreflang.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); List<Link> links = entry.getLinks("related"); assertEquals(2, links.size()); assertEquals(new IRI("http://example.org/2003/12/13/atom02"), links.get(0).getResolvedHref()); assertEquals(new IRI("http://example.org/2003/12/13/atom03"), links.get(1).getResolvedHref()); } @Test public void testSection412SummaryContentBase64() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/summary-content-base64.xml IRI uri = baseURI.resolve("4.1.2/summary-content-base64.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { assertNotNull(entry.getSummaryElement()); assertEquals(Text.Type.TEXT, entry.getSummaryElement().getTextType()); assertNotNull(entry.getContentElement()); assertEquals(Content.Type.MEDIA, entry.getContentElement().getContentType()); } } @Test public void testSection412SummaryContentSrc() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.2/summary-content-src.xml IRI uri = baseURI.resolve("4.1.2/summary-content-src.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { assertNotNull(entry.getSummaryElement()); assertEquals(Text.Type.TEXT, entry.getSummaryElement().getTextType()); assertNotNull(entry.getContentElement()); assertEquals(Content.Type.MEDIA, entry.getContentElement().getContentType()); Content mediaContent = entry.getContentElement(); assertNotNull(mediaContent.getSrc()); assertEquals("application/pdf", mediaContent.getMimeType().toString()); } } @Test public void testSection4131TypeHtml() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.1/type-html.xml IRI uri = baseURI.resolve("4.1.3.1/type-html.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { assertNotNull(entry.getContentElement()); assertEquals(Content.Type.HTML, entry.getContentElement().getContentType()); } } @Test public void testSection413TypeMultipartAlternative() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.1/type-multipart-alternative.xml IRI uri = baseURI.resolve("4.1.3.1/type-multipart-alternative.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals("multipart/alternative", entry.getContentElement().getMimeType().toString()); } @Test public void testSection4131TypeTextHtml() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.1/type-text-html.xml IRI uri = baseURI.resolve("4.1.3.1/type-text-html.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { assertNotNull(entry.getContentElement()); assertEquals(Content.Type.MEDIA, entry.getContentElement().getContentType()); Content mediaContent = entry.getContentElement(); assertEquals("text/html", mediaContent.getMimeType().toString()); } } @Test public void testSection4131TypeText() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.1/type-text.xml IRI uri = baseURI.resolve("4.1.3.1/type-text.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { assertNotNull(entry.getContentElement()); assertEquals(Content.Type.TEXT, entry.getContentElement().getContentType()); } } @Test public void testSection4131TypeXhtml() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.1/type-xhtml.xml IRI uri = baseURI.resolve("4.1.3.1/type-xhtml.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { assertNotNull(entry.getContentElement()); assertEquals(Content.Type.XHTML, entry.getContentElement().getContentType()); } } @Test public void testSection413TypeXml() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.1/type-xhtml.xml IRI uri = baseURI.resolve("4.1.3.1/type-xml.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); try { feed.getEntries(); } catch (Exception e) { assertTrue(e instanceof OMException); } } @Test public void testSection4132ContentSrcExtraChild() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.2/content-src-extra-child.xml IRI uri = baseURI.resolve("4.1.3.2/content-src-extra-child.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Content content = entry.getContentElement(); assertEquals(new IRI("http://example.org/2003/12/13/atom03"), content.getResolvedSrc()); assertEquals("extraneous text", entry.getContent().trim()); } @Test public void testSection4132ContentSrcExtraText() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.2/content-src-extra-text.xml try { IRI uri = baseURI.resolve("4.1.3.2/content-src-extra-text.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Content content = entry.getContentElement(); assertEquals(new IRI("http://example.org/2003/12/13/atom03"), content.getResolvedSrc()); } catch (Exception e) { } } @Test public void testSection4132ContentSrcInvalidIri() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.2/content-src-invalid-iri.xml IRI uri = baseURI.resolve("4.1.3.2/content-src-invalid-iri.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { Content content = entry.getContentElement(); assertNotNull(content); try { content.getSrc(); } catch (Exception e) { assertTrue(e instanceof IRISyntaxException); } } } @Test public void testSection4132ContentSrcNoTypeNoError() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.2/content-src-no-type-no-error.xml IRI uri = baseURI.resolve("4.1.3.2/content-src-no-type-no-error.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Content content = entry.getContentElement(); assertEquals(new IRI("http://example.org/2003/12/13/atom03"), content.getResolvedSrc()); assertNull(content.getMimeType()); } @Test public void testSection4132ContentSrcNoType() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.2/content-src-no-type.xml IRI uri = baseURI.resolve("4.1.3.2/content-src-no-type.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Content content = entry.getContentElement(); assertEquals(new IRI("http://example.org/2003/12/13/atom03"), content.getResolvedSrc()); assertNull(content.getMimeType()); } @Test public void testSection4132ContentSrcRelativeRef() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.2/content-src-relative-ref.xml IRI uri = baseURI.resolve("4.1.3.2/content-src-relative-ref.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { Content content = entry.getContentElement(); assertNotNull(content); assertEquals(Content.Type.MEDIA, content.getContentType()); assertEquals(uri.resolve("2003/12/12/atom03.pdf"), content.getResolvedSrc()); } } @Test public void testSection4132ContentSrcTypeHtml() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.2/content-src-type-html.xml IRI uri = baseURI.resolve("4.1.3.2/content-src-type-html.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals("", entry.getContent()); assertEquals(Content.Type.HTML, entry.getContentType()); assertEquals(new IRI("http://example.org/2003/12/13/atom03"), entry.getContentElement().getResolvedSrc()); } @Test public void testSection4132ContentSrcTypeTextHtml() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.2/content-src-type-text-html.xml IRI uri = baseURI.resolve("4.1.3.2/content-src-type-text-html.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals("", entry.getContent()); assertEquals(Content.Type.MEDIA, entry.getContentType()); assertEquals(new IRI("http://example.org/2003/12/13/atom03"), entry.getContentElement().getResolvedSrc()); } @Test public void testSection4132ContentSrcTypeText() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.2/content-src-type-text.xml IRI uri = baseURI.resolve("4.1.3.2/content-src-type-text.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals("", entry.getContent()); assertEquals(Content.Type.TEXT, entry.getContentType()); assertEquals(new IRI("http://example.org/2003/12/13/atom03"), entry.getContentElement().getResolvedSrc()); } @Test public void testSection4132ContentSrcTypeXhtml() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.2/content-src-type-xhtml.xml IRI uri = baseURI.resolve("4.1.3.2/content-src-type-xhtml.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertNull(entry.getContent()); assertEquals(Content.Type.XHTML, entry.getContentType()); assertEquals(new IRI("http://example.org/2003/12/13/atom03"), entry.getContentElement().getResolvedSrc()); } @Test public void testSection4133ContentApplicationXhtml() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.3/content-application-xthml.xml IRI uri = baseURI.resolve("4.1.3.3/content-application-xthml.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { Content content = entry.getContentElement(); assertNotNull(content); assertEquals(Content.Type.XML, entry.getContentElement().getContentType()); } } @Test public void testSection4133ContentHtmlWithChildren() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.3/content-html-with-children.xml IRI uri = baseURI.resolve("4.1.3.3/content-html-with-children.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals("Some text.", entry.getContent()); assertEquals(Content.Type.HTML, entry.getContentType()); } @Test public void testSection4133ContentJpegInvalidBase64() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.3/content-jpeg-invalid-base64.xml IRI uri = baseURI.resolve("4.1.3.3/content-jpeg-invalid-base64.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals(Content.Type.MEDIA, entry.getContentType()); assertEquals("insert image here", entry.getContent()); } @Test public void testSection4133ContentJpegValidBase64() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.3/content-jpeg-valid-base64.xml IRI uri = baseURI.resolve("4.1.3.3/content-jpeg-valid-base64.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals(Content.Type.MEDIA, entry.getContentType()); DataHandler dh = entry.getContentElement().getDataHandler(); ByteArrayInputStream in = (ByteArrayInputStream)dh.getContent(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int n = -1; while ((n = in.read()) != -1) { out.write(n); } out.flush(); assertEquals(1538, out.toByteArray().length); assertEquals("image/jpeg", dh.getContentType()); } @Test public void testSection4133ContentNoTypeEscapedHtml() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.3/content-no-type-escaped-html.xml IRI uri = baseURI.resolve("4.1.3.3/content-no-type-escaped-html.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals("Some <b>bold</b> text.", entry.getContent()); assertEquals(Content.Type.TEXT, entry.getContentType()); } @Test public void testSection4133ContentNoTypeWithChildren() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.3/content-no-type-with-children.xml IRI uri = baseURI.resolve("4.1.3.3/content-no-type-with-children.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals("Some text", entry.getContent().trim()); assertEquals(Content.Type.TEXT, entry.getContentType()); } @Test public void testSection4133ContentPlainWithChildren() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.3/content-plain-with-children.xml IRI uri = baseURI.resolve("4.1.3.3/content-plain-with-children.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals("Some text.", entry.getContent().trim()); assertEquals(Content.Type.MEDIA, entry.getContentType()); } @Test public void testSection4133ContentSvgMixed() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.3/content-svg-mixed.xml IRI uri = baseURI.resolve("4.1.3.3/content-svg-mixed.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Content content = entry.getContentElement(); assertNotNull(content.getValueElement()); // we're pretty forgiving assertEquals(Content.Type.XML, content.getContentType()); } @Test public void testSection4133ContentSvg() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.3/content-svg.xml IRI uri = baseURI.resolve("4.1.3.3/content-svg.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { Content content = entry.getContentElement(); assertNotNull(content); assertEquals(Content.Type.XML, entry.getContentElement().getContentType()); } } @Test public void testSection4133ContentTextHtml() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.3/content-text-html.xml IRI uri = baseURI.resolve("4.1.3.3/content-text-html.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals(Content.Type.MEDIA, entry.getContentType()); } @Test public void testSection4133ContentTextWithChildren() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.3/content-text-with-children.xml IRI uri = baseURI.resolve("4.1.3.3/content-text-with-children.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals(Content.Type.TEXT, entry.getContentType()); assertEquals("Some text", entry.getContent().trim()); } @Test public void testSection4133ContentXhtmlEscaped() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.3/content-xhtml-escaped.xml IRI uri = baseURI.resolve("4.1.3.3/content-xhtml-escaped.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals(Content.Type.XHTML, entry.getContentType()); String c = entry.getContent().trim(); c = c.replaceAll(">", "&gt;"); assertEquals("Some &lt;b&gt;bold&lt;/b&gt; text.", c); } @Test public void testSection4133ContentXhtmlMixed() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.3/content-xhtml-mixed.xml IRI uri = baseURI.resolve("4.1.3.3/content-xhtml-mixed.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals(Content.Type.XHTML, entry.getContentType()); String c = entry.getContent().trim(); c = c.replaceAll("Some &lt;b>bold&lt;/b>", "Some &lt;b&gt;bold&lt;/b&gt;"); assertEquals("<b xmlns=\"http://www.w3.org/1999/xhtml\">Example:</b> Some &lt;b&gt;bold&lt;/b&gt; text.", c); } @Test public void testSection4133ContentXhtmlNoXhtmlDiv() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.3/content-xhtml-no-xhtml-div.xml IRI uri = baseURI.resolve("4.1.3.3/content-xhtml-no-xhtml-div.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals(Content.Type.XHTML, entry.getContentType()); assertNull(entry.getContent()); } @Test public void testSection4133ContentXhtmlNotmarkup() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.3/content-xhtml-notmarkup.xml IRI uri = baseURI.resolve("4.1.3.3/content-xhtml-notmarkup.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals(Content.Type.XHTML, entry.getContentType()); String c = entry.getContent(); c = c.replaceAll(">", "&gt;"); assertEquals("Some &lt;x&gt;bold&lt;/x&gt; text.", c); } @Test public void testSection4133ContentXhtmlTextChildren() throws Exception { // http://feedvalidator.org/testcases/atom/4.1.3.3/content-xhtml-text-children.xml IRI uri = baseURI.resolve("4.1.3.3/content-xhtml-text-children.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals(Content.Type.XHTML, entry.getContentType()); assertNull(entry.getContent()); } @Test public void testSection4221CategoryNoTerm() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.2.1/category-no-term.xml IRI uri = baseURI.resolve("4.2.2.1/category-no-term.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); List<Category> cats = entry.getCategories(); assertEquals(1, cats.size()); assertNull(cats.get(0).getTerm()); } @Test public void testSection4222CategoryNoScheme() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.2.2/category-no-scheme.xml IRI uri = baseURI.resolve("4.2.2.2/category-no-scheme.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); List<Category> cats = entry.getCategories(); assertEquals(1, cats.size()); assertNull(cats.get(0).getScheme()); } @Test public void testSection4222CategorySchemeInvalidIri() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.2.2/category-scheme-invalid-iri.xml IRI uri = baseURI.resolve("4.2.2.2/category-scheme-invalid-iri.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { List<Category> cats = entry.getCategories(); for (Category cat : cats) { try { cat.getScheme(); } catch (Exception e) { assertTrue(e instanceof IRISyntaxException); } } } } @Test public void testSection4222CategorySchemeRelIri() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.2.2/category-scheme-rel-iri.xml IRI uri = baseURI.resolve("4.2.2.2/category-scheme-rel-iri.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Category cat = entry.getCategories().get(0); assertEquals(new IRI("mine"), cat.getScheme()); } @Test public void testSection4223CategoryLabelEscapedHtml() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.2.3/category-label-escaped-html.xml IRI uri = baseURI.resolve("4.2.2.3/category-label-escaped-html.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Category cat = entry.getCategories().get(0); assertEquals("<b>business</b>", cat.getLabel()); } @Test public void testSection4223CategoryNoLabel() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.2.3/category-no-label.xml IRI uri = baseURI.resolve("4.2.2.3/category-no-label.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Category cat = entry.getCategories().get(0); assertNull(cat.getLabel()); } @Test public void testSection424GeneratorEscapedHtml() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.4/generator-escaped-html.xml IRI uri = baseURI.resolve("4.2.4/generator-escaped-html.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); Generator generator = feed.getGenerator(); assertEquals("<b>The</b> generator", generator.getText()); } @Test public void testSection424GeneratorInvalidIri() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.4/generator-invalid-iri.xml IRI uri = baseURI.resolve("4.2.4/generator-invalid-iri.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); Generator generator = feed.getGenerator(); assertNotNull(generator); try { generator.getUri(); } catch (Exception e) { assertTrue(e instanceof IRISyntaxException); } } @Test public void testSection424GeneratorNoText() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.4/generator-no-text.xml IRI uri = baseURI.resolve("4.2.4/generator-no-text.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); Generator generator = feed.getGenerator(); assertEquals("", generator.getText()); } @Test public void testSection424GeneratorWithChild() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.4/generator-with-child.xml IRI uri = baseURI.resolve("4.2.4/generator-with-child.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); Generator generator = feed.getGenerator(); assertEquals("", generator.getText()); } @Test public void testSection424GeneratorRelativeRef() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.4/generator_relative_ref.xml IRI uri = baseURI.resolve("4.2.4/generator_relative_ref.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); Generator generator = feed.getGenerator(); assertNotNull(generator); assertEquals(uri.resolve("misc/Colophon"), generator.getResolvedUri()); } @Test public void testSection425IconInvalidUri() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.5/icon_invalid_uri.xml IRI uri = baseURI.resolve("4.2.5/icon_invalid_uri.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); assertNotNull(feed.getIconElement()); try { feed.getIconElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IRISyntaxException); } } @Test public void testSection425IconRelativeRef() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.5/icon_relative_ref.xml IRI uri = baseURI.resolve("4.2.5/icon_relative_ref.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed); assertNotNull(feed.getIconElement()); assertEquals(uri.resolve("favicon.ico"), feed.getIconElement().getResolvedValue()); } @Test public void testSection426IdDotSegments() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.6/id-dot-segments.xml IRI uri = baseURI.resolve("4.2.6/id-dot-segments.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("http://example.org/./id/1234"), doc.getRoot().getId()); assertEquals(new IRI("http://example.org/id/1234"), IRI.normalize(doc.getRoot().getId())); } @Test public void testSection426IdEmptyFragmentId() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.6/id-empty-fragment-id.xml IRI uri = baseURI.resolve("4.2.6/id-empty-fragment-id.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); feed.getIdElement().getValue(); } @Test public void testSection426IdEmptyPath() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.6/id-empty-path.xml IRI uri = baseURI.resolve("4.2.6/id-empty-path.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("http://example.org"), doc.getRoot().getId()); } @Test public void testSection426IdEmptyQuery() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.6/id-empty-query.xml IRI uri = baseURI.resolve("4.2.6/id-empty-query.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("http://example.org/id/1234?"), doc.getRoot().getId()); } @Test public void testSection426IdExplicitAuthority() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.6/id-explicit-authority.xml IRI uri = baseURI.resolve("4.2.6/id-explicit-authority.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("http://:@example.org/id/1234"), doc.getRoot().getId()); } @Test public void testSection426IdExplicitDefaultPort() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.6/id-explicit-default-port.xml IRI uri = baseURI.resolve("4.2.6/id-explicit-default-port.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("http://example.org:80/id/1234"), doc.getRoot().getId()); } @Test public void testSection426IdHostUppercase() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.6/id-host-uppercase.xml IRI uri = baseURI.resolve("4.2.6/id-host-uppercase.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("http://Example.org/id/1234"), doc.getRoot().getId()); } @Test public void testSection426IdNotUri() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.6/id-not-uri.xml IRI uri = baseURI.resolve("4.2.6/id-not-uri.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); try { feed.getIdElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IRISyntaxException); } } @Test public void testSection426IdPercentEncodedLower() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.6/id-percent-encoded-lower.xml IRI uri = baseURI.resolve("4.2.6/id-percent-encoded-lower.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("http://example.org/id/1234?q=%5c"), doc.getRoot().getId()); } @Test public void testSection426IdPercentEncoded() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.6/id-percent-encoded.xml IRI uri = baseURI.resolve("4.2.6/id-percent-encoded.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("http://example.org/%69%64/1234"), doc.getRoot().getId()); } @Test public void testSection426IdRelativeUri() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.6/id-relative-uri.xml IRI uri = baseURI.resolve("4.2.6/id-relative-uri.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("/id/1234"), doc.getRoot().getId()); } @Test public void testSection426IdUppercaseScheme() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.6/id-uppercase-scheme.xml IRI uri = baseURI.resolve("4.2.6/id-uppercase-scheme.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("Http://example.org/id/1234"), doc.getRoot().getId()); } @Test public void testSection426IdValidTagUris() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.6/id-valid-tag-uris.xml IRI uri = baseURI.resolve("4.2.6/id-valid-tag-uris.xml"); Document<Feed> doc = parse(uri); // we don't care that they're invalid, at least for now assertEquals(new IRI("tag:example.com,2000:"), doc.getRoot().getId()); } @Test public void testSection4271LinkHrefInvalid() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.7.1/link-href-invalid.xml IRI uri = baseURI.resolve("4.2.7.1/link-href-invalid.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { List<Link> links = entry.getLinks(); for (Link link : links) { try { link.getHref(); } catch (Exception e) { assertTrue(e instanceof IRISyntaxException); } } } } @Test public void testSection427LinkHrefRelative() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.7.1/link-href-relative.xml IRI uri = baseURI.resolve("4.2.7.1/link-href-relative.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { List<Link> links = entry.getLinks(); for (Link link : links) { assertEquals(uri.resolve("/2003/12/13/atom03"), link.getResolvedHref()); } } } @Test public void testSection427LinkNoHref() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.7.1/link-no-href.xml IRI uri = baseURI.resolve("4.2.7.1/link-no-href.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Link link = entry.getLinks().get(0); assertNull(link.getHref()); } @Test public void testSection4272AbsoluteRel() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.7.2/absolute_rel.xml IRI uri = baseURI.resolve("4.2.7.2/absolute_rel.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertEquals(1, feed.getLinks(Link.REL_ALTERNATE).size()); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { assertEquals(1, entry.getLinks(Link.REL_ALTERNATE).size()); } } @Test public void testSection4272EmptyPath() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.7.2/empty-path.xml IRI uri = baseURI.resolve("4.2.7.2/empty-path.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); List<Link> links = feed.getLinks(Link.REL_ALTERNATE); for (Link link : links) { assertEquals(uri, link.getResolvedHref()); } } @Test public void testSection4272LinkRelIsegmentNzNc() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.7.2/link-rel-isegment-nz-nc.xml IRI uri = baseURI.resolve("4.2.7.2/link-rel-isegment-nz-nc.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertNotNull(entry.getAlternateLink()); } @Test public void testSection4272LinkRelRelative() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.7.2/link-rel-relative.xml IRI uri = baseURI.resolve("4.2.7.2/link-rel-relative.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Link link = entry.getLink("/foo"); assertNotNull(link); // we don't care that it's invalid } @Test public void testSection4272LinkRelSelfMatch() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.7.2/link-rel-self-match.xml IRI uri = baseURI.resolve("4.2.7.2/link-rel-self-match.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("http://www.feedvalidator.org/testcases/atom/4.2.7.2/link-rel-self-match.xml"), doc .getRoot().getSelfLink().getResolvedHref()); } @Test public void testSection4272LinkRelSelfNoMatch() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.7.2/link-rel-self-nomatch.xml IRI uri = baseURI.resolve("4.2.7.2/link-rel-self-nomatch.xml"); Document<Feed> doc = parse(uri); assertEquals(new IRI("http://www.feedvalidator.org/testcases/atom/4.2.7.2/link-rel-self-match.xml"), doc .getRoot().getSelfLink().getResolvedHref()); } @Test public void testSection4272SelfVsAlternate() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.7.2/self-vs-alternate.xml IRI uri = baseURI.resolve("4.2.7.2/self-vs-alternate.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertNull(entry.getAlternateLink()); Link self = entry.getLink("self"); assertEquals("text/html", self.getMimeType().toString()); } @Test public void testSection4272UnregisteredRel() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.7.2/unregistered-rel.xml IRI uri = baseURI.resolve("4.2.7.2/unregistered-rel.xml"); Document<Feed> doc = parse(uri); assertNotNull(doc.getRoot().getLink("service.post")); } @Test public void testSection4273LinkTypeInvalidMime() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.7.3/link-type-invalid-mime.xml IRI uri = baseURI.resolve("4.2.7.3/link-type-invalid-mime.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { List<Link> links = entry.getLinks(); for (Link link : links) { try { link.getMimeType(); } catch (Exception e) { assertTrue(e instanceof MimeTypeParseException); } } } } @Test public void testSection4273LinkTypeParameters() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.7.3/link-type-parameters.xml IRI uri = baseURI.resolve("4.2.7.3/link-type-parameters.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { List<Link> links = entry.getLinks(); for (Link link : links) { assertEquals("text/html", link.getMimeType().getBaseType()); assertEquals("utf-8", link.getMimeType().getParameter("charset")); } } } @Test public void testSection4274LinkHreflangInvalidLanguage() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.7.4/link-hreflang-invalid-language.xml IRI uri = baseURI.resolve("4.2.7.4/link-hreflang-invalid-language.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Link link = entry.getAlternateLink(); assertEquals("insert language here", link.getHrefLang()); } @Test public void testSection4275LinkTitleWithBadchars() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.7.5/link-title-with-badchars.xml IRI uri = baseURI.resolve("4.2.7.5/link-title-with-badchars.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Link link = entry.getAlternateLink(); assertEquals("This is a \u00A3\u0093test.\u0094", link.getTitle()); } @Test public void testSection4275LinkTitleWithHtml() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.7.5/link-title-with-html.xml IRI uri = baseURI.resolve("4.2.7.5/link-title-with-html.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Link link = entry.getAlternateLink(); assertEquals("very, <b>very</b>, scary indeed", link.getTitle()); } @Test public void testSection4276LinkLengthNotPositive() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.7.6/link-length-not-positive.xml IRI uri = baseURI.resolve("4.2.7.6/link-length-not-positive.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Link link = entry.getAlternateLink(); assertEquals(-1, link.getLength()); } @Test public void testSection428LogoInvalidUri() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.8/logo-invalid-uri.xml IRI uri = baseURI.resolve("4.2.8/logo-invalid-uri.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed.getLogoElement()); try { feed.getLogoElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IRISyntaxException); } } @Test public void testSection428LogoRelativeRef() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.8/logo_relative_ref.xml IRI uri = baseURI.resolve("4.2.8/logo_relative_ref.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); assertNotNull(feed.getLogoElement()); assertEquals(uri.resolve("atomlogo.png"), feed.getLogoElement().getResolvedValue()); } @Test public void testSection429PublishedInvalidDate() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.9/published-invalid-date.xml IRI uri = baseURI.resolve("4.2.9/published-invalid-date.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { try { entry.getPublishedElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } } @Test public void testSection4210RightsInvalidType() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.10/rights-invalid-type.xml try { IRI uri = baseURI.resolve("4.2.10/rights-invalid-type.xml"); Document<Feed> doc = parse(uri); doc.getRoot().getRights(); } catch (Exception e) { } } @Test public void testSection4210RightsTextWithEscapedHtml() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.10/rights-text-with-escaped-html.xml IRI uri = baseURI.resolve("4.2.10/rights-text-with-escaped-html.xml"); Document<Feed> doc = parse(uri); assertEquals("Copyright &copy; 2005", doc.getRoot().getRights()); } @Test public void testSection4210RightsXhtmlNoXmldiv() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.10/rights-xhtml-no-xmldiv.xml IRI uri = baseURI.resolve("4.2.10/rights-xhtml-no-xmldiv.xml"); Document<Feed> doc = parse(uri); assertNull(doc.getRoot().getRights()); } @Test public void testSection4211MissingId() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.11/missing-id.xml IRI uri = baseURI.resolve("4.2.11/missing-id.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Source source = entry.getSource(); assertNull(source.getId()); } @Test public void testSection4211MissingTitle() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.11/missing-title.xml IRI uri = baseURI.resolve("4.2.11/missing-title.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Source source = entry.getSource(); assertNull(source.getTitle()); } @Test public void testSection4211MissingUpdated() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.11/missing-updated.xml IRI uri = baseURI.resolve("4.2.11/missing-updated.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Source source = entry.getSource(); assertNull(source.getUpdated()); } @Test public void testSection4211MultipleAlternatesDiffering() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.11/multiple-alternates-differing.xml IRI uri = baseURI.resolve("4.2.11/multiple-alternates-differing.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Source source = entry.getSource(); List<Link> links = source.getLinks("alternate"); assertEquals(2, links.size()); assertEquals(new IRI("http://example.org/"), links.get(0).getResolvedHref()); assertEquals(new IRI("http://example.es/"), links.get(1).getResolvedHref()); } @Test public void testSection4211MultipleAlternatesMatching() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.11/multiple-alternates-matching.xml IRI uri = baseURI.resolve("4.2.11/multiple-alternates-matching.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Source source = entry.getSource(); assertEquals(new IRI("http://example.org/front-page.html"), source.getAlternateLink().getResolvedHref()); } @Test public void testSection4211MultipleAuthors() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.11/multiple-authors.xml IRI uri = baseURI.resolve("4.2.11/multiple-authors.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { Source source = entry.getSource(); assertNotNull(source); assertEquals(2, source.getAuthors().size()); } } @Test public void testSection4211MultipleCategories() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.11/multiple-categories.xml IRI uri = baseURI.resolve("4.2.11/multiple-categories.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { Source source = entry.getSource(); assertNotNull(source); assertEquals(2, source.getCategories().size()); } } @Test public void testSection4211MultipleContributors() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.11/multiple-contributors.xml IRI uri = baseURI.resolve("4.2.11/multiple-contributors.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { Source source = entry.getSource(); assertNotNull(source); assertEquals(2, source.getContributors().size()); } } @Test public void testSection4211MultipleGenerators() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.11/multiple-generators.xml IRI uri = baseURI.resolve("4.2.11/multiple-generators.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Generator g = entry.getSource().getGenerator(); assertEquals(new IRI("http://www.example.com/"), g.getResolvedUri()); } @Test public void testSection4211MultipleIcons() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.11/multiple-icons.xml IRI uri = baseURI.resolve("4.2.11/multiple-icons.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals(new IRI("http://feedvalidator.org/big.icon"), entry.getSource().getIcon()); } @Test public void testSection4211MultipleIds() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.11/multiple-ids.xml IRI uri = baseURI.resolve("4.2.11/multiple-ids.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals(new IRI("urn:uuid:28213c50-f84c-11d9-8cd6-0800200c9a66"), entry.getSource().getId()); } @Test public void testSection4211MultipleLogos() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.11/multiple-logos.xml IRI uri = baseURI.resolve("4.2.11/multiple-logos.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals(new IRI("http://feedvalidator.org/small.jpg"), entry.getSource().getLogo()); } @Test public void testSection4211MultipleRights() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.11/multiple-rights.xml IRI uri = baseURI.resolve("4.2.11/multiple-rights.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals("Public Domain", entry.getSource().getRights().trim()); } @Test public void testSection4211MultipleSubtitles() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.11/multiple-subtitles.xml IRI uri = baseURI.resolve("4.2.11/multiple-subtitles.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals("A unique feed, just like all the others", entry.getSource().getSubtitle().trim()); } @Test public void testSection4211MultipleTitles() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.11/multiple-titles.xml IRI uri = baseURI.resolve("4.2.11/multiple-titles.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); assertEquals("Source of all knowledge", entry.getSource().getTitle().trim()); } @Test public void testSection4211MultipleUpdateds() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.11/multiple-updateds.xml IRI uri = baseURI.resolve("4.2.11/multiple-updateds.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Date d = AtomDate.parse("2003-12-13T17:46:27Z"); assertEquals(d, entry.getSource().getUpdated()); } @Test public void testSection4211SourceEntry() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.11/source-entry.xml IRI uri = baseURI.resolve("4.2.11/source-entry.xml"); Document<Feed> doc = parse(uri); Entry entry = doc.getRoot().getEntries().get(0); Source source = entry.getSource(); assertNotNull(source); } @Test public void testSection4212SubtitleBlank() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.12/subtitle-blank.xml IRI uri = baseURI.resolve("4.2.12/subtitle-blank.xml"); Document<Feed> doc = parse(uri); assertEquals("", doc.getRoot().getSubtitle()); } @Test public void testSection4214TitleBlank() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.14/title-blank.xml IRI uri = baseURI.resolve("4.2.14/title-blank.xml"); Document<Feed> doc = parse(uri); assertEquals("", doc.getRoot().getTitle()); } @Test public void testSection4215UpdatedInvalidDate() throws Exception { // http://feedvalidator.org/testcases/atom/4.2.15/updated-invalid-date.xml IRI uri = baseURI.resolve("4.2.15/updated-invalid-date.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); List<Entry> entries = feed.getEntries(); for (Entry entry : entries) { try { entry.getUpdatedElement().getValue(); } catch (Exception e) { assertTrue(e instanceof IllegalArgumentException); } } } }
7,432
0
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser/stax/AtomConformanceTest.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.parser.stax; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.util.List; import javax.xml.namespace.QName; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Content; import org.apache.abdera.model.Document; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.model.Link; import org.apache.abdera.model.Text; import org.apache.axiom.om.OMElement; import org.junit.Test; public class AtomConformanceTest extends BaseParserTestCase { /** * Test to make sure that the parser properly detects the various kinds of extended content types allowed by Atom */ @Test public void testContentTypes() throws Exception { IRI uri = new IRI("http://www.snellspace.com/public/contentsummary.xml"); Document<Feed> doc = parse(uri); Feed feed = doc.getRoot(); int n = 1; for (Entry entry : feed.getEntries()) { Content content = entry.getContentElement(); Text summary = entry.getSummaryElement(); switch (n) { case 1: // XML Content Type assertEquals(Content.Type.XML, content.getContentType()); assertTrue(content.getMimeType().match("application/xml")); assertEquals(Text.Type.TEXT, summary.getTextType()); break; case 2: // XML Content Type by src reference assertEquals(Content.Type.XML, content.getContentType()); assertNotNull(content.getResolvedSrc()); assertEquals(Text.Type.TEXT, summary.getTextType()); break; case 3: // Text Content Type. This is really an order test, // to determine how a reader selects which text to show assertEquals(Content.Type.TEXT, content.getContentType()); assertEquals(Text.Type.TEXT, summary.getTextType()); break; case 4: // Text Content Type. This is really an order test, // to determine how a reader selects which text to show assertEquals(Content.Type.TEXT, content.getContentType()); assertEquals(Text.Type.TEXT, summary.getTextType()); break; case 5: // Embedded iCalendar assertEquals(Content.Type.MEDIA, content.getContentType()); assertTrue(content.getMimeType().match("text/calendar")); assertEquals(Text.Type.TEXT, summary.getTextType()); break; case 6: // Embedded Base64 encoded GIF assertEquals(Content.Type.MEDIA, content.getContentType()); assertTrue(content.getMimeType().match("image/gif")); assertEquals(Text.Type.TEXT, summary.getTextType()); break; } n++; } } /** * Tests the parsers support for various XML Namespace options */ @Test public void testXmlNamespace() throws Exception { String[] tests = {"http://www.snellspace.com/public/nondefaultnamespace.xml", "http://www.snellspace.com/public/nondefaultnamespace2.xml", "http://www.snellspace.com/public/nondefaultnamespace3.xml"}; int n = 1; for (String test : tests) { IRI uri = new IRI(test); Document<Feed> doc = parse(uri); assertNotNull(doc); Feed feed = doc.getRoot(); Entry entry = feed.getEntries().get(0); switch (n) { case 1: assertNotNull(entry.getTitleElement()); assertEquals(new IRI("tag:example.org,2007:bar"), entry.getIdElement().getValue()); Text summary = entry.getSummaryElement(); assertNotNull(summary); assertEquals(Text.Type.XHTML, summary.getTextType()); OMElement element = (OMElement)summary; OMElement div = element.getFirstChildWithName(new QName("http://www.w3.org/1999/xhtml", "div")); assertNotNull(div); break; case 2: assertNotNull(entry.getTitleElement()); assertEquals(new IRI("tag:example.org,2007:bar"), entry.getIdElement().getValue()); summary = entry.getSummaryElement(); assertNotNull(summary); assertEquals(Text.Type.XHTML, summary.getTextType()); element = (OMElement)summary; div = element.getFirstChildWithName(new QName("http://www.w3.org/1999/xhtml", "div")); assertNotNull(div); break; case 3: assertNotNull(entry.getTitleElement()); assertEquals(new IRI("tag:example.org,2007:bar"), entry.getIdElement().getValue()); summary = entry.getSummaryElement(); assertNotNull(summary); assertEquals(Text.Type.XHTML, summary.getTextType()); element = (OMElement)summary; div = element.getFirstChildWithName(new QName("http://www.w3.org/1999/xhtml", "div")); assertNotNull(div); break; } n++; } } /** * Test to ensure that the parser properly resolves relative URI */ @Test public void testXmlBase() throws Exception { IRI uri = new IRI("http://www.snellspace.com/public/xmlbase.xml"); Document<Feed> doc = parse(uri); assertNotNull(doc); Feed feed = doc.getRoot(); assertEquals(new IRI("http://www.snellspace.com/public/xmlbase.xml"), feed.getBaseUri()); assertEquals(new IRI("http://www.snellspace.com/public/atom-logo.png"), feed.getLogoElement() .getResolvedValue()); assertEquals(new IRI("http://www.snellspace.com/public/atom-icon.png"), feed.getIconElement() .getResolvedValue()); Entry entry = feed.getEntries().get(0); assertEquals("http://www.snellspace.com/wp", entry.getAlternateLinkResolvedHref().toString()); } /** * This tests the parsers ability to properly ignore the ordering of elements in the Atom feed/entry. The parser * should be able to properly select the requested elements regardless of the order in which they appear */ @Test public void testOrder() throws Exception { // http://www.snellspace.com/public/ordertest.xml IRI uri = new IRI("http://www.snellspace.com/public/ordertest.xml"); Document<Feed> doc = parse(uri); assertNotNull(doc); Feed feed = doc.getRoot(); List<Entry> entries = feed.getEntries(); int n = 1; for (Entry entry : entries) { switch (n) { case 1: assertEquals(new IRI("tag:example.org,2006:atom/conformance/element_order/1"), entry.getIdElement() .getValue()); assertEquals(Text.Type.TEXT, entry.getTitleType()); assertEquals(Text.Type.TEXT, entry.getSummaryType()); assertNotNull(entry.getUpdatedElement().getValue()); assertEquals(1, entry.getLinks(Link.REL_ALTERNATE).size()); break; case 2: assertEquals(new IRI("tag:example.org,2006:atom/conformance/element_order/2"), entry.getIdElement() .getValue()); assertEquals(Text.Type.TEXT, entry.getTitleType()); assertEquals(Text.Type.TEXT, entry.getSummaryType()); assertNotNull(entry.getUpdatedElement().getValue()); assertEquals(1, entry.getLinks(Link.REL_ALTERNATE).size()); break; case 3: assertEquals(2, entry.getLinks(Link.REL_ALTERNATE).size()); assertEquals(new IRI("http://www.snellspace.com/public/alternate"), entry .getLinks(Link.REL_ALTERNATE).get(0).getHref()); assertEquals(new IRI("http://www.snellspace.com/public/alternate2"), entry .getLinks(Link.REL_ALTERNATE).get(1).getHref()); break; case 4: assertEquals(1, entry.getLinks(Link.REL_ALTERNATE).size()); assertEquals(new IRI("http://www.snellspace.com/public/alternate"), entry .getLinks(Link.REL_ALTERNATE).get(0).getHref()); break; case 5: Text title = entry.getTitleElement(); assertEquals(Text.Type.TEXT, entry.getTitleType()); String value = title.getValue(); assertEquals("Entry with a source first", value); assertEquals(1, entry.getLinks(Link.REL_ALTERNATE).size()); assertEquals(new IRI("http://www.snellspace.com/public/alternate"), entry .getLinks(Link.REL_ALTERNATE).get(0).getHref()); break; case 6: title = entry.getTitleElement(); assertEquals(Text.Type.TEXT, entry.getTitleType()); value = title.getValue(); assertEquals("Entry with a source last", value); assertEquals(1, entry.getLinks(Link.REL_ALTERNATE).size()); assertEquals(new IRI("http://www.snellspace.com/public/alternate"), entry .getLinks(Link.REL_ALTERNATE).get(0).getHref()); break; case 7: title = entry.getTitleElement(); assertEquals(Text.Type.TEXT, entry.getTitleType()); value = title.getValue(); assertEquals("Entry with a source in the middle", value); assertEquals(1, entry.getLinks(Link.REL_ALTERNATE).size()); assertEquals(new IRI("http://www.snellspace.com/public/alternate"), entry .getLinks(Link.REL_ALTERNATE).get(0).getHref()); break; case 8: title = entry.getTitleElement(); assertEquals(Text.Type.TEXT, entry.getTitleType()); value = title.getValue(); assertEquals("Atom elements in an extension element", value); assertEquals(new IRI("tag:example.org,2006:atom/conformance/element_order/8"), entry.getIdElement() .getValue()); break; case 9: title = entry.getTitleElement(); assertEquals(Text.Type.TEXT, entry.getTitleType()); value = title.getValue(); assertEquals("Atom elements in an extension element", value); assertEquals(new IRI("tag:example.org,2006:atom/conformance/element_order/9"), entry.getIdElement() .getValue()); break; } n++; } } /** * Tests the parsers support for the various link relation types */ @Test public void testLink() throws Exception { // http://www.snellspace.com/public/linktests.xml IRI uri = new IRI("http://www.snellspace.com/public/linktests.xml"); Document<Feed> doc = parse(uri); assertNotNull(doc); Feed feed = doc.getRoot(); List<Entry> entries = feed.getEntries(); int n = 1; for (Entry entry : entries) { switch (n) { case 1: assertEquals(1, entry.getLinks(Link.REL_ALTERNATE).size()); assertEquals(new IRI("http://www.snellspace.com/public/linktests/alternate"), entry .getLinks(Link.REL_ALTERNATE).get(0).getHref()); break; case 2: assertEquals(4, entry.getLinks(Link.REL_ALTERNATE).size()); assertEquals(new IRI("http://www.snellspace.com/public/linktests/alternate"), entry .getLinks(Link.REL_ALTERNATE).get(1).getHref()); assertEquals(new IRI("http://www.snellspace.com/public/linktests/alternate2"), entry .getLinks(Link.REL_ALTERNATE).get(2).getHref()); break; case 3: assertEquals(1, entry.getLinks(Link.REL_ALTERNATE).size()); assertEquals(1, entry.getLinks(Link.REL_ENCLOSURE).size()); assertEquals(1, entry.getLinks(Link.REL_RELATED).size()); assertEquals(1, entry.getLinks(Link.REL_SELF).size()); assertEquals(1, entry.getLinks(Link.REL_VIA).size()); assertEquals(new IRI("http://www.snellspace.com/public/linktests/alternate"), entry .getLinks(Link.REL_ALTERNATE).get(0).getHref()); assertEquals(new IRI("http://www.snellspace.com/public/linktests/enclosure"), entry .getLinks(Link.REL_ENCLOSURE).get(0).getHref()); assertEquals(new IRI("http://www.snellspace.com/public/linktests/related"), entry .getLinks(Link.REL_RELATED).get(0).getHref()); assertEquals(new IRI("http://www.snellspace.com/public/linktests/self"), entry .getLinks(Link.REL_SELF).get(0).getHref()); assertEquals(new IRI("http://www.snellspace.com/public/linktests/via"), entry .getLinks(Link.REL_VIA).get(0).getHref()); break; case 4: assertEquals(2, entry.getLinks(Link.REL_ALTERNATE).size()); assertEquals(1, entry.getLinks(Link.REL_ENCLOSURE).size()); assertEquals(1, entry.getLinks(Link.REL_RELATED).size()); assertEquals(1, entry.getLinks(Link.REL_SELF).size()); assertEquals(1, entry.getLinks(Link.REL_VIA).size()); assertEquals(new IRI("http://www.snellspace.com/public/linktests/alternate"), entry .getLinks(Link.REL_ALTERNATE).get(0).getHref()); assertEquals(new IRI("http://www.snellspace.com/public/linktests/alternate2"), entry .getLinks(Link.REL_ALTERNATE).get(1).getHref()); assertEquals(new IRI("http://www.snellspace.com/public/linktests/enclosure"), entry .getLinks(Link.REL_ENCLOSURE).get(0).getHref()); assertEquals(new IRI("http://www.snellspace.com/public/linktests/related"), entry .getLinks(Link.REL_RELATED).get(0).getHref()); assertEquals(new IRI("http://www.snellspace.com/public/linktests/self"), entry .getLinks(Link.REL_SELF).get(0).getHref()); assertEquals(new IRI("http://www.snellspace.com/public/linktests/via"), entry .getLinks(Link.REL_VIA).get(0).getHref()); break; case 5: assertEquals(1, entry.getLinks(Link.REL_ALTERNATE).size()); assertEquals(1, entry.getLinks(Link.REL_LICENSE).size()); assertEquals(new IRI("http://www.snellspace.com/public/linktests/alternate"), entry .getLinks(Link.REL_ALTERNATE).get(0).getHref()); assertEquals(new IRI("http://www.snellspace.com/public/linktests/license"), entry .getLinks(Link.REL_LICENSE).get(0).getHref()); break; case 6: assertEquals(1, entry.getLinks(Link.REL_ALTERNATE).size()); assertEquals(1, entry.getLinks("http://example.org").size()); assertEquals(new IRI("http://www.snellspace.com/public/linktests/alternate"), entry .getLinks(Link.REL_ALTERNATE).get(0).getHref()); assertEquals(new IRI("http://www.snellspace.com/public/linktests/example"), entry .getLinks("http://example.org").get(0).getHref()); break; } n++; } } }
7,433
0
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser/stax/FOMTest.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.parser.stax; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import java.io.OutputStreamWriter; import java.net.URL; import java.util.Calendar; import java.util.Date; import javax.activation.DataHandler; import javax.activation.MimeType; import javax.xml.namespace.QName; import javax.xml.transform.Result; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerFactory; import javax.xml.transform.stream.StreamResult; import org.apache.abdera.Abdera; import org.apache.abdera.factory.Factory; import org.apache.abdera.filter.ListParseFilter; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.rfc4646.Lang; import org.apache.abdera.model.AtomDate; 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; import org.apache.abdera.parser.ParserFactory; import org.apache.abdera.parser.ParserOptions; import org.apache.abdera.util.AbderaSource; import org.apache.abdera.util.Constants; import org.apache.abdera.util.Version; import org.apache.abdera.util.filter.BlackListParseFilter; import org.apache.abdera.util.filter.WhiteListParseFilter; import org.apache.abdera.writer.Writer; import org.apache.abdera.writer.WriterFactory; import org.apache.abdera.xpath.XPath; import org.apache.axiom.attachments.ByteArrayDataSource; import org.junit.Test; public class FOMTest { private static Abdera abdera = new Abdera(); private static Parser getParser() { return abdera.getParser(); } private static Factory getFactory() { return abdera.getFactory(); } private static XPath getXPath() { return abdera.getXPath(); } private static WriterFactory getWriterFactory() { return abdera.getWriterFactory(); } private static ParserFactory getParserFactory() { return abdera.getParserFactory(); } private static Writer getWriter() { return abdera.getWriter(); } @Test public void testMinimalConfiguration() { assertNotNull(getFactory()); assertNotNull(getParser()); assertNotNull(getXPath()); assertNotNull(getWriterFactory()); assertNotNull(getParserFactory()); assertNotNull(getWriter()); } @Test public void testParser() throws Exception { InputStream in = FOMTest.class.getResourceAsStream("/simple.xml"); Document<Feed> doc = getParser().parse(in); Feed feed = doc.getRoot(); assertEquals("Example Feed", feed.getTitle()); assertEquals(Text.Type.TEXT, feed.getTitleType()); assertEquals("http://example.org/", feed.getAlternateLink().getResolvedHref().toString()); assertNotNull(feed.getUpdated()); assertEquals("John Doe", feed.getAuthor().getName()); assertEquals("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6", feed.getId().toString()); Entry entry = feed.getEntries().get(0); assertEquals("Atom-Powered Robots Run Amok", entry.getTitle()); assertEquals(Text.Type.TEXT, entry.getTitleType()); assertEquals("http://example.org/2003/12/13/atom03", entry.getAlternateLink().getResolvedHref().toString()); assertEquals("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a", entry.getId().toString()); assertNotNull(entry.getUpdated()); assertEquals("Some text.", entry.getSummary()); assertEquals(Text.Type.TEXT, entry.getSummaryType()); } @Test public void testCreate() throws Exception { Feed feed = getFactory().newFeed(); feed.setLanguage("en-US"); feed.setBaseUri("http://example.org"); feed.setTitle("Example Feed"); feed.addLink("http://example.org/"); feed.addAuthor("John Doe"); feed.setId("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6", false); feed.addContributor("Bob Jones"); feed.addCategory("example"); Entry entry = feed.insertEntry(); entry.setTitle("Atom-Powered Robots Run Amok"); entry.addLink("http://example.org/2003/12/13/atom03"); entry.setId("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a", false); entry.setSummary("Some text."); Entry entry2 = feed.insertEntry(); entry2.setTitle("re: Atom-Powered Robots Run Amok"); entry2.addLink("/2003/12/13/atom03/1"); entry2.setId("urn:uuid:1225c695-cfb8-4ebb-aaaa-80cb323feb5b", false); entry2.setSummary("A response"); assertEquals("urn:uuid:1225c695-cfb8-4ebb-aaaa-80cb323feb5b", feed.getEntries().get(0).getId().toString()); assertEquals("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a", feed.getEntries().get(1).getId().toString()); } @Test public void testWhiteListParseFilter() throws Exception { ListParseFilter filter = new WhiteListParseFilter(); filter.add(Constants.FEED); filter.add(Constants.ENTRY); filter.add(Constants.TITLE); filter.add(Constants.ID); ParserOptions options = getParser().getDefaultParserOptions(); options.setParseFilter(filter); URL url = FOMTest.class.getResource("/simple.xml"); InputStream in = url.openStream(); Document<Feed> doc = getParser().parse(in, url.toString().replaceAll(" ", "%20"), options); Feed feed = doc.getRoot(); assertEquals("Example Feed", feed.getTitle()); assertEquals(Text.Type.TEXT, feed.getTitleType()); assertNull(feed.getAlternateLink()); assertNull(feed.getUpdated()); assertNull(feed.getAuthor()); assertEquals("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6", feed.getId().toString()); Entry entry = feed.getEntries().get(0); assertEquals("Atom-Powered Robots Run Amok", entry.getTitle()); assertEquals(Text.Type.TEXT, entry.getTitleType()); assertNull(entry.getAlternateLink()); assertEquals("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a", entry.getId().toString()); assertNull(entry.getUpdated()); assertNull(entry.getSummary()); assertNull(entry.getSummaryType()); } @Test public void testBlackListParseFilter() throws Exception { ListParseFilter filter = new BlackListParseFilter(); filter.add(Constants.UPDATED); ParserOptions options = getParser().getDefaultParserOptions(); options.setParseFilter(filter); URL url = FOMTest.class.getResource("/simple.xml"); InputStream in = url.openStream(); Document<Feed> doc = getParser().parse(in, url.toString().replaceAll(" ", "%20"), options); Feed feed = doc.getRoot(); assertEquals("Example Feed", feed.getTitle()); assertEquals(Text.Type.TEXT, feed.getTitleType()); assertEquals("http://example.org/", feed.getAlternateLink().getResolvedHref().toString()); assertNull(feed.getUpdated()); assertEquals("John Doe", feed.getAuthor().getName()); assertEquals("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6", feed.getId().toString()); Entry entry = feed.getEntries().get(0); assertEquals("Atom-Powered Robots Run Amok", entry.getTitle()); assertEquals(Text.Type.TEXT, entry.getTitleType()); assertEquals("http://example.org/2003/12/13/atom03", entry.getAlternateLink().getResolvedHref().toString()); assertEquals("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a", entry.getId().toString()); assertNull(entry.getUpdated()); assertEquals("Some text.", entry.getSummary()); assertEquals(Text.Type.TEXT, entry.getSummaryType()); } @Test public void testXPath() throws Exception { InputStream in = FOMTest.class.getResourceAsStream("/simple.xml"); Document<Feed> doc = getParser().parse(in); Feed feed = doc.getRoot(); XPath xpath = getXPath(); assertEquals(1.0d, xpath.evaluate("count(/a:feed)", feed)); assertTrue(xpath.booleanValueOf("/a:feed/a:entry", feed)); assertEquals(1.0d, xpath.numericValueOf("count(/a:feed)", feed)); assertEquals("Atom-Powered Robots Run Amok", xpath.valueOf("/a:feed/a:entry/a:title", feed)); assertEquals(1, xpath.selectNodes("/a:feed/a:entry", feed).size()); assertTrue(xpath.selectSingleNode("/a:feed", feed) instanceof Feed); assertEquals(feed, xpath.selectSingleNode("..", feed.getTitleElement())); assertEquals(feed, xpath.selectSingleNode("ancestor::*", feed.getEntries().get(0))); assertEquals("The feed is is urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6", xpath .valueOf("concat('The feed is is ',/a:feed/a:id)", feed)); } @Test public void testUriNormalization() throws Exception { String s1 = "HTTP://www.Example.ORG:80/./foo/%2d/../%2d/./foo"; String s2 = "HTTP://www.Example.ORG:81/./foo/%2d/../%2d/./foo"; assertEquals("http://www.example.org/foo/-/foo", IRI.normalizeString(s1)); assertEquals("http://www.example.org:81/foo/-/foo", IRI.normalizeString(s2)); } @Test public void testFactory() throws Exception { Factory factory = getFactory(); Person author = factory.newAuthor(); assertNotNull(author); author = factory.newAuthor(); author.setName("a"); author.setEmail("b"); author.setUri("c"); assertNotNull(author); assertEquals("a", author.getName()); assertEquals("b", author.getEmail()); assertEquals("c", author.getUri().toString()); author = factory.newAuthor(); author.setName("a"); author.setEmail("b"); author.setUri("c"); assertNotNull(author); assertEquals("a", author.getName()); assertEquals("b", author.getEmail()); assertEquals("c", author.getUri().toString()); Category category = factory.newCategory(); assertNotNull(category); category = factory.newCategory(); category.setScheme("a"); category.setTerm("b"); category.setLabel("c"); assertNotNull(category); assertEquals("a", category.getScheme().toString()); assertEquals("b", category.getTerm()); assertEquals("c", category.getLabel()); Collection collection = factory.newCollection(); assertNotNull(collection); Content content = factory.newContent(Content.Type.TEXT); assertNotNull(content); assertEquals(Content.Type.TEXT, content.getContentType()); content = factory.newContent(Content.Type.HTML); assertEquals(Content.Type.HTML, content.getContentType()); content = factory.newContent(Content.Type.XHTML); assertEquals(Content.Type.XHTML, content.getContentType()); content = factory.newContent(Content.Type.MEDIA); assertEquals(Content.Type.MEDIA, content.getContentType()); content = factory.newContent(Content.Type.XML); assertEquals(Content.Type.XML, content.getContentType()); content = factory.newContent(new MimeType("text/foo")); assertEquals(Content.Type.MEDIA, content.getContentType()); assertEquals("text/foo", content.getMimeType().toString()); Person contributor = factory.newContributor(); assertNotNull(contributor); contributor = factory.newContributor(); contributor.setName("a"); contributor.setEmail("b"); contributor.setUri("c"); assertNotNull(contributor); assertEquals("a", contributor.getName()); assertEquals("b", contributor.getEmail()); assertEquals("c", contributor.getUri().toString()); contributor = factory.newContributor(); contributor.setName("a"); contributor.setEmail("b"); contributor.setUri("c"); assertNotNull(contributor); assertEquals("a", contributor.getName()); assertEquals("b", contributor.getEmail()); assertEquals("c", contributor.getUri().toString()); Control control = factory.newControl(); assertNotNull(control); control = factory.newControl(); control.setDraft(true); assertTrue(control.isDraft()); Date now = new Date(); DateTime dateTime = factory.newDateTime(Constants.UPDATED, null); dateTime.setValue(AtomDate.valueOf(now)); assertEquals(now, dateTime.getDate()); Calendar cal = Calendar.getInstance(); dateTime = factory.newDateTime(Constants.UPDATED, null); dateTime.setCalendar(cal); assertEquals(cal, dateTime.getCalendar()); dateTime = factory.newDateTime(Constants.UPDATED, null); dateTime.setDate(now); assertEquals(now, dateTime.getDate()); dateTime = factory.newDateTime(Constants.UPDATED, null); assertNotNull(dateTime); dateTime = factory.newDateTime(Constants.UPDATED, null); dateTime.setTime(now.getTime()); assertEquals(now.getTime(), dateTime.getTime()); dateTime = factory.newDateTime(Constants.UPDATED, null); dateTime.setString(AtomDate.format(now)); assertEquals(AtomDate.format(now), dateTime.getString()); assertEquals(now, dateTime.getDate()); Generator generator = factory.newDefaultGenerator(); assertNotNull(generator); assertEquals(Version.APP_NAME, generator.getText()); assertEquals(Version.VERSION, generator.getVersion()); assertEquals(Version.URI, generator.getUri().toString()); Div div = factory.newDiv(); assertNotNull(div); Document<?> doc = factory.newDocument(); assertNotNull(doc); Element el = factory.newEmail(); assertNotNull(el); el = factory.newEmail(); el.setText("a"); assertEquals("a", el.getText()); Entry entry = factory.newEntry(); assertNotNull(entry); entry = factory.newEntry(); assertNotNull(entry); Element ee = factory.newExtensionElement(new QName("urn:foo", "bar", "b")); assertNotNull(ee); assertEquals(new QName("urn:foo", "bar", "b"), ee.getQName()); Feed feed = factory.newFeed(); assertNotNull(feed); generator = factory.newGenerator(); assertNotNull(generator); generator = factory.newGenerator(); generator.setUri(Version.URI); generator.setVersion(Version.VERSION); generator.setText(Version.APP_NAME); assertNotNull(generator); assertEquals(Version.APP_NAME, generator.getText()); assertEquals(Version.VERSION, generator.getVersion()); assertEquals(Version.URI, generator.getUri().toString()); content = factory.newContent(Content.Type.HTML); content.setValue("a"); assertNotNull(content); assertEquals("a", content.getValue()); assertEquals(Content.Type.HTML, content.getContentType()); Text text = factory.newRights(Text.Type.HTML); text.setValue("a"); assertNotNull(text); assertEquals("a", text.getValue()); assertEquals(Text.Type.HTML, text.getTextType()); text = factory.newSubtitle(Text.Type.HTML); text.setValue("a"); assertEquals("a", text.getValue()); assertEquals(Text.Type.HTML, text.getTextType()); text = factory.newSummary(Text.Type.HTML); text.setValue("a"); assertEquals("a", text.getValue()); assertEquals(Text.Type.HTML, text.getTextType()); text = factory.newText(Constants.TITLE, Text.Type.HTML, null); text.setValue("a"); assertEquals("a", text.getValue()); assertEquals(Text.Type.HTML, text.getTextType()); assertEquals(Constants.TITLE, text.getQName()); text = factory.newTitle(Text.Type.HTML); text.setValue("a"); assertEquals("a", text.getValue()); assertEquals(Text.Type.HTML, text.getTextType()); IRIElement iri = factory.newIcon(); assertNotNull(iri); iri = factory.newIcon(); iri.setValue("http://example.org/foo"); assertEquals("http://example.org/foo", iri.getValue().toString()); iri = factory.newIcon(); iri.setValue("http://example.org/foo"); assertEquals("http://example.org/foo", iri.getValue().toString()); iri = factory.newID(); assertNotNull(iri); iri = factory.newID(); iri.setValue("http://example.org/foo"); assertEquals("http://example.org/foo", iri.getValue().toString()); iri = factory.newID(); iri.setValue("http://example.org/foo"); assertEquals("http://example.org/foo", iri.getValue().toString()); iri = factory.newIRIElement(Constants.ID, null); assertNotNull(iri); iri = factory.newIRIElement(Constants.ID, null); iri.setValue("http://example.org/foo"); assertEquals("http://example.org/foo", iri.getValue().toString()); iri = factory.newIRIElement(Constants.ID, null); iri.setValue("http://example.org/foo"); assertEquals("http://example.org/foo", iri.getValue().toString()); Link link = factory.newLink(); assertNotNull(link); link = factory.newLink(); link.setHref("http://example.org/foo"); link.setRel("a"); link.setMimeType("text/foo"); link.setTitle("b"); link.setHrefLang("en"); link.setLength(10); assertEquals("http://example.org/foo", link.getHref().toString()); assertEquals("a", link.getRel()); assertEquals("text/foo", link.getMimeType().toString()); assertEquals("b", link.getTitle()); assertEquals("en", link.getHrefLang()); assertEquals(10, link.getLength()); link = factory.newLink(); link.setHref("http://example.org/foo"); link.setRel("a"); link.setMimeType("text/foo"); link.setTitle("b"); link.setHrefLang("en"); link.setLength(10); assertEquals("http://example.org/foo", link.getHref().toString()); assertEquals("a", link.getRel()); assertEquals("text/foo", link.getMimeType().toString()); assertEquals("b", link.getTitle()); assertEquals("en", link.getHrefLang()); assertEquals(10, link.getLength()); iri = factory.newLogo(); assertNotNull(iri); iri = factory.newLogo(); iri.setValue("http://example.org/foo"); assertEquals("http://example.org/foo", iri.getValue().toString()); iri = factory.newLogo(); iri.setValue("http://example.org/foo"); assertEquals("http://example.org/foo", iri.getValue().toString()); content = factory.newContent(new MimeType("text/foo")); content.setSrc("foo"); assertNotNull(content); assertEquals("text/foo", content.getMimeType().toString()); assertEquals("foo", content.getSrc().toString()); content = factory.newContent(new MimeType("text/foo")); content.setDataHandler(new DataHandler(new ByteArrayDataSource("foo".getBytes()))); assertEquals("Zm9v", content.getValue()); assertEquals(Content.Type.MEDIA, content.getContentType()); el = factory.newName(); assertNotNull(el); el = factory.newName(); el.setText("a"); assertEquals("a", el.getText()); Parser parser = factory.newParser(); assertNotNull(parser); Person person = factory.newPerson(Constants.AUTHOR, null); assertNotNull(person); assertEquals(Constants.AUTHOR, person.getQName()); person = factory.newPerson(Constants.AUTHOR, null); person.setName("a"); person.setEmail("b"); person.setUri("c"); assertEquals("a", person.getName()); assertEquals("b", person.getEmail()); assertEquals("c", person.getUri().toString()); person = factory.newPerson(Constants.AUTHOR, null); person.setName("a"); person.setEmail("b"); person.setUri("c"); assertEquals("a", person.getName()); assertEquals("b", person.getEmail()); assertEquals("c", person.getUri().toString()); now = new Date(); dateTime = factory.newPublished(); dateTime.setValue(AtomDate.valueOf(now)); assertEquals(now, dateTime.getDate()); cal = Calendar.getInstance(); dateTime = factory.newPublished(); dateTime.setCalendar(cal); assertEquals(cal, dateTime.getCalendar()); dateTime = factory.newPublished(); dateTime.setDate(now); assertEquals(now, dateTime.getDate()); dateTime = factory.newPublished(); assertNotNull(dateTime); dateTime = factory.newPublished(); dateTime.setTime(now.getTime()); assertEquals(now.getTime(), dateTime.getTime()); dateTime = factory.newPublished(); dateTime.setString(AtomDate.format(now)); assertEquals(AtomDate.format(now), dateTime.getString()); assertEquals(now, dateTime.getDate()); Service service = factory.newService(); assertNotNull(service); Source source = factory.newSource(); assertNotNull(source); el = factory.newElement(Constants.NAME); assertNotNull(el); assertEquals(Constants.NAME, el.getQName()); el = factory.newElement(Constants.NAME); el.setText("a"); assertNotNull(el); assertEquals(Constants.NAME, el.getQName()); assertEquals("a", el.getText()); text = factory.newText(Constants.TITLE, Text.Type.TEXT); assertNotNull(text); assertEquals(Text.Type.TEXT, text.getTextType()); text = factory.newRights(); text.setValue("a"); assertEquals("a", text.getValue()); assertEquals(Text.Type.TEXT, text.getTextType()); text = factory.newSubtitle(); text.setValue("a"); assertEquals("a", text.getValue()); assertEquals(Text.Type.TEXT, text.getTextType()); text = factory.newSummary(); text.setValue("a"); assertEquals("a", text.getValue()); assertEquals(Text.Type.TEXT, text.getTextType()); text = factory.newText(Constants.TITLE, Text.Type.TEXT, null); text.setValue("a"); assertEquals(Constants.TITLE, text.getQName()); assertEquals("a", text.getValue()); assertEquals(Text.Type.TEXT, text.getTextType()); text = factory.newTitle(); text.setValue("a"); assertEquals("a", text.getValue()); assertEquals(Text.Type.TEXT, text.getTextType()); content = factory.newContent(Content.Type.TEXT); content.setValue("a"); assertEquals("a", content.getValue()); assertEquals(Content.Type.TEXT, content.getContentType()); now = new Date(); dateTime = factory.newUpdated(); dateTime.setValue(AtomDate.valueOf(now)); assertEquals(now, dateTime.getDate()); cal = Calendar.getInstance(); dateTime = factory.newUpdated(); dateTime.setCalendar(cal); assertEquals(cal, dateTime.getCalendar()); dateTime = factory.newUpdated(); dateTime.setDate(now); assertEquals(now, dateTime.getDate()); dateTime = factory.newUpdated(); assertNotNull(dateTime); dateTime = factory.newUpdated(); dateTime.setTime(now.getTime()); assertEquals(now.getTime(), dateTime.getTime()); dateTime = factory.newUpdated(); dateTime.setString(AtomDate.format(now)); assertEquals(AtomDate.format(now), dateTime.getString()); assertEquals(now, dateTime.getDate()); iri = factory.newUri(); assertNotNull(iri); iri = factory.newUri(); iri.setValue("http://example.org/foo"); assertEquals("http://example.org/foo", iri.getValue().toString()); iri = factory.newUri(); iri.setValue("http://example.org/foo"); assertEquals("http://example.org/foo", iri.getValue().toString()); Workspace workspace = factory.newWorkspace(); assertNotNull(workspace); div = factory.newDiv(); content = factory.newContent(Content.Type.XHTML); content.setValueElement(div); assertNotNull(content); assertEquals(Content.Type.XHTML, content.getContentType()); assertNotNull(content.getValueElement()); assertEquals(div, content.getValueElement()); content = factory.newContent(new MimeType("application/xml")); content.setValueElement(div); assertNotNull(content); assertEquals(Content.Type.XML, content.getContentType()); assertNotNull(content.getValueElement()); assertEquals(div, content.getValueElement()); text = factory.newRights(); text.setValueElement(div); assertNotNull(text); assertEquals(Text.Type.XHTML, text.getTextType()); assertEquals(div, text.getValueElement()); text = factory.newSubtitle(); text.setValueElement(div); assertNotNull(text); assertEquals(Text.Type.XHTML, text.getTextType()); assertEquals(div, text.getValueElement()); text = factory.newSummary(); text.setValueElement(div); assertNotNull(text); assertEquals(Text.Type.XHTML, text.getTextType()); assertEquals(div, text.getValueElement()); text = factory.newText(Constants.TITLE, null); text.setValueElement(div); assertNotNull(text); assertEquals(Constants.TITLE, text.getQName()); assertEquals(Text.Type.XHTML, text.getTextType()); assertEquals(div, text.getValueElement()); text = factory.newTitle(); text.setValueElement(div); assertNotNull(text); assertEquals(Text.Type.XHTML, text.getTextType()); assertEquals(div, text.getValueElement()); } @Test public void testRoundtrip() throws Exception { Feed feed = getFactory().newFeed(); feed.setLanguage("en-US"); feed.setBaseUri("http://example.org"); feed.setTitle("Example Feed"); feed.addLink("http://example.org/"); feed.addAuthor("John Doe"); feed.setId("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6", false); feed.addContributor("Bob Jones"); feed.addCategory("example"); Entry entry = feed.insertEntry(); entry.setTitle("Atom-Powered Robots Run Amok"); entry.addLink("http://example.org/2003/12/13/atom03"); entry.setId("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a", false); entry.setSummary("Some text."); Entry entry2 = feed.insertEntry(); entry2.setTitle("re: Atom-Powered Robots Run Amok"); entry2.addLink("/2003/12/13/atom03/1"); entry2.setId("urn:uuid:1225c695-cfb8-4ebb-aaaa-80cb323feb5b", false); entry2.setSummary("A response"); ByteArrayOutputStream out = new ByteArrayOutputStream(); feed.getDocument().writeTo(out); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); Document<Feed> doc = getParser().parse(in); feed = doc.getRoot(); assertEquals("en-US", feed.getLanguage()); assertEquals("http://example.org", feed.getBaseUri().toString()); assertEquals("Example Feed", feed.getTitle()); assertEquals("http://example.org/", feed.getAlternateLink().getHref().toString()); assertEquals("John Doe", feed.getAuthor().getName()); assertEquals("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6", feed.getId().toString()); assertEquals("Bob Jones", feed.getContributors().get(0).getName()); assertEquals("example", feed.getCategories().get(0).getTerm()); assertEquals(2, feed.getEntries().size()); entry = feed.getFirstChild(Constants.ENTRY); assertNotNull(entry); assertEquals("re: Atom-Powered Robots Run Amok", entry.getTitle()); assertEquals("/2003/12/13/atom03/1", entry.getAlternateLink().getHref().toString()); assertEquals("http://example.org/2003/12/13/atom03/1", entry.getAlternateLink().getResolvedHref().toString()); assertEquals("urn:uuid:1225c695-cfb8-4ebb-aaaa-80cb323feb5b", entry.getId().toString()); assertEquals("A response", entry.getSummary()); entry = entry.getNextSibling(Constants.ENTRY); assertNotNull(entry); assertEquals("Atom-Powered Robots Run Amok", entry.getTitle()); assertEquals("http://example.org/2003/12/13/atom03", entry.getAlternateLink().getHref().toString()); assertEquals("urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a", entry.getId().toString()); assertEquals("Some text.", entry.getSummary()); } @Test public void testSourceResult() throws Exception { try { // Apply an XSLT transform to the entire Feed TransformerFactory factory = TransformerFactory.newInstance(); Document<Element> xslt = getParser().parse(FOMTest.class.getResourceAsStream("/test.xslt")); AbderaSource xsltSource = new AbderaSource(xslt); Transformer transformer = factory.newTransformer(xsltSource); Document<Feed> feed = getParser().parse(FOMTest.class.getResourceAsStream("/simple.xml")); AbderaSource feedSource = new AbderaSource(feed); ByteArrayOutputStream out = new ByteArrayOutputStream(); Result result = new StreamResult(out); transformer.transform(feedSource, result); assertEquals("This is a test urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6", out.toString()); // Apply an XSLT transform to XML in the content element xslt = getParser().parse(FOMTest.class.getResourceAsStream("/content.xslt")); xsltSource = new AbderaSource(xslt); transformer = factory.newTransformer(xsltSource); feed = getParser().parse(FOMTest.class.getResourceAsStream("/xmlcontent.xml")); Entry entry = feed.getRoot().getEntries().get(0); Content content = entry.getContentElement(); AbderaSource contentSource = new AbderaSource(content.getValueElement()); out = new ByteArrayOutputStream(); result = new StreamResult(out); transformer.transform(contentSource, result); assertEquals("This is a test test", out.toString()); } catch (Exception exception) { // TrAX is likely not configured, skip the test } } @Test public void testContentClone() throws Exception { String s = "<entry xmlns='http://www.w3.org/2005/Atom'><content type='html'>test</content></entry>"; ByteArrayInputStream in = new ByteArrayInputStream(s.getBytes()); Abdera abdera = new Abdera(); Parser parser = abdera.getParser(); Document<Entry> doc = parser.parse(in); Entry entry = (Entry)(doc.getRoot().clone()); assertEquals(Content.Type.HTML, entry.getContentType()); } @Test public void testSimpleExtension() throws Exception { Abdera abdera = new Abdera(); Entry entry = abdera.newEntry(); entry.setDraft(true); // this will create an app:control element assertNull(entry.getControl().getSimpleExtension(new QName("urn:foo", "foo"))); } @Test public void testLang() throws Exception { Abdera abdera = new Abdera(); Entry entry = abdera.newEntry(); entry.setLanguage("en-US"); assertEquals("en-US", entry.getLanguage()); Lang lang = entry.getLanguageTag(); assertNotNull(lang); assertEquals("en", lang.getLanguage().getName()); assertEquals("US", lang.getRegion().getName()); assertEquals(java.util.Locale.US, lang.getLocale()); } @Test public void testSetContent() throws Exception { Abdera abdera = new Abdera(); Entry entry = abdera.newEntry(); Document<Element> foodoc = abdera.getParser().parse(new ByteArrayInputStream("<a><b><c/></b></a>".getBytes())); Element foo = foodoc.getRoot(); entry.setContent(foo, "application/foo+xml"); assertEquals(foo, entry.getContentElement().getValueElement()); } @Test public void testSetContent2() throws Exception { Abdera abdera = new Abdera(); Entry entry = abdera.newEntry(); InputStream in = new ByteArrayInputStream("tóst".getBytes("utf-16")); Document<Entry> edoc = entry.getDocument(); entry.setContent(in, "text/plain;charset=\"utf-16\""); ByteArrayOutputStream out = new ByteArrayOutputStream(); OutputStreamWriter w = new OutputStreamWriter(out, "utf-16"); edoc.writeTo(w); in = new ByteArrayInputStream(out.toByteArray()); entry = (Entry)abdera.getParser().parse(in).getRoot(); assertEquals("tóst", entry.getContent()); } }
7,434
0
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser/stax/BaseParserTestCase.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.parser.stax; import java.io.InputStream; import org.apache.abdera.Abdera; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.parser.Parser; public abstract class BaseParserTestCase { private static Abdera abdera = new Abdera(); protected static Parser getParser() { return abdera.getParser(); } protected static <T extends Element> Document<T> parse(IRI uri) throws Exception { String uriStr = uri.toString(); String path = uriStr.substring(uriStr.indexOf("//") + 1); InputStream stream = BaseParserTestCase.class.getResourceAsStream(path); return getParser().parse(stream, uri.toString()); } }
7,435
0
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser/stax/FeedParserTest.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.parser.stax; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.InputStream; import javax.activation.DataHandler; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Content; import org.apache.abdera.model.Document; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.model.Person; import org.junit.BeforeClass; import org.junit.Test; public class FeedParserTest extends BaseParserTestCase { static IRI baseURI; @BeforeClass public static void setUp() throws Exception { baseURI = new IRI("http://www.feedparser.org/tests/wellformed/atom10/"); } @Test public void testAtom10Namespace() throws Exception { Document<?> doc = parse(baseURI.resolve("atom10_namespace.xml")); assertNotNull(doc); } @Test public void testEntryAuthorEmail() throws Exception { Document<Feed> doc = parse(baseURI.resolve("entry_author_email.xml")); Feed feed = doc.getRoot(); Entry entry = feed.getEntries().get(0); Person person = entry.getAuthor(); assertEquals("me@example.com", person.getEmail()); } @Test public void testEntryAuthorName() throws Exception { Document<Feed> doc = parse(baseURI.resolve("entry_author_name.xml")); Feed feed = doc.getRoot(); Entry entry = feed.getEntries().get(0); Person person = entry.getAuthor(); assertEquals("Example author", person.getName()); } @Test public void testEntryContentBase64() throws Exception { Document<Feed> doc = parse(baseURI.resolve("entry_content_base64.xml")); Feed feed = doc.getRoot(); Entry entry = feed.getEntries().get(0); Content mediaContent = entry.getContentElement(); assertEquals("application/octet-stream", mediaContent.getMimeType().toString()); DataHandler dataHandler = mediaContent.getDataHandler(); InputStream in = (ByteArrayInputStream)dataHandler.getContent(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int n = -1; while ((n = in.read()) > -1) { baos.write(n); } assertEquals("Example <b>Atom</b>", baos.toString()); } @Test public void testEntryContentBase642() throws Exception { Document<Feed> doc = parse(baseURI.resolve("entry_content_base64_2.xml")); Feed feed = doc.getRoot(); Entry entry = feed.getEntries().get(0); Content mediaContent = entry.getContentElement(); assertEquals("application/octet-stream", mediaContent.getMimeType().toString()); DataHandler dataHandler = mediaContent.getDataHandler(); InputStream in = (ByteArrayInputStream)dataHandler.getContent(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); int n = -1; while ((n = in.read()) > -1) { baos.write(n); } assertEquals("<p>History of the &lt;blink&gt; tag</p>", baos.toString()); } }
7,436
0
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser/stax/EntryLinkTest.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.parser.stax; import static org.junit.Assert.assertNotNull; 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.model.Feed; import org.apache.abdera.model.Link; import org.apache.abdera.parser.Parser; import org.junit.Test; public class EntryLinkTest { /** * Link in entry disappears after adding entry to a feed. * * @see https://issues.apache.org/jira/browse/ABDERA-70 FOM Objects should automatically complete the parse when * modifications are made */ @Test public void testEntryLinkInFeed() throws Exception { Abdera abdera = new Abdera(); Factory factory = abdera.getFactory(); Feed feed = factory.newFeed(); feed.setTitle("Test"); feed.setId("http://example.com/feed"); Parser parser = abdera.getParser(); Document<Entry> doc = parser.parse(this.getClass().getResourceAsStream("/entry.xml")); Entry entry = doc.getRoot(); Link link = factory.newLink(); link.setHref(entry.getId().toString()); link.setRel(Link.REL_EDIT); entry.addLink(link); assertNotNull("Link is null", entry.getLink(Link.REL_EDIT)); feed.addEntry(entry); assertNotNull("Link is null", entry.getLink(Link.REL_EDIT)); for (Entry e : feed.getEntries()) { assertNotNull("Link is null", e.getLink(Link.REL_EDIT)); } } }
7,437
0
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser/stax/FOMDivTest.java
package org.apache.abdera.test.parser.stax; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.InputStream; import org.apache.abdera.Abdera; import org.apache.abdera.model.Document; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Text; import org.junit.Test; public class FOMDivTest { @Test public void getInternalValueWithUtf8Characters (){ Abdera abdera = new Abdera (); InputStream in = FOMTest.class.getResourceAsStream("/utf8characters.xml"); Document<Entry> doc = abdera.getParser().parse(in); Entry entry = doc.getRoot(); assertEquals("Item", entry.getTitle()); assertEquals(Text.Type.TEXT, entry.getTitleType()); String value = entry.getContentElement().getValue(); assertTrue(value.contains("Ȁȁ")); } }
7,438
0
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser/stax/SimpleParseFilter.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.parser.stax; import javax.xml.namespace.QName; import org.apache.abdera.util.filter.AbstractParseFilter; public class SimpleParseFilter extends AbstractParseFilter { private static final long serialVersionUID = -7037334325964942488L; public boolean acceptable(QName qname) { return true; } public boolean acceptable(QName qname, QName attribute) { return true; } }
7,439
0
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser/stax/ConcurrencyTest.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.parser.stax; import static org.junit.Assert.fail; import java.io.InputStream; import org.apache.abdera.Abdera; import org.apache.abdera.model.Content; import org.apache.abdera.model.Document; import org.apache.abdera.model.Entry; import org.apache.abdera.parser.Parser; import org.junit.Test; /** * Test possible concurrency issues. * * @version $Id$ */ public class ConcurrencyTest { private static final int N_THREADS = 100; /** * Test for a concurrency issue that caused a ConcurrentModificationException in Abdera 0.1.0 but seems to be fixed * in 0.2. We leave the test here to prevent possible regressions. */ @Test public void testSetContentMT() throws Exception { Thread t[] = new Thread[N_THREADS]; final boolean failed[] = new boolean[t.length]; for (int i = 0; i < t.length; ++i) { final int j = i; failed[i] = false; Runnable r = new Runnable() { public void run() { try { setContent(); } catch (Exception e) { e.printStackTrace(); failed[j] = true; fail(e.toString()); } } }; t[i] = new Thread(r); t[i].start(); } for (int i = 0; i < t.length; ++i) { t[i].join(); if (failed[i]) { fail("Thread " + t[i] + " failed."); } } } private void setContent() throws Exception { // For Abdera 0.1.0 this would be: // Parser parser = Factory.INSTANCE.newParser(); Parser parser = Abdera.getNewParser(); InputStream is = ParserTest.class.getResourceAsStream("/entry.xml"); Document<Entry> doc = parser.parse(is); Entry entry = doc.getRoot(); Content content = entry.getFactory().newContent(Content.Type.XML); content.setValue("<some><xml>document</xml></some>"); content.setMimeType("application/xml"); entry.setContentElement(content); } }
7,440
0
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser
Create_ds/abdera/parser/src/test/java/org/apache/abdera/test/parser/stax/XhtmlTest.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.parser.stax; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import org.apache.abdera.Abdera; import org.apache.abdera.model.Content; import org.apache.abdera.model.Div; import org.apache.abdera.model.Element; import org.apache.abdera.model.Entry; import org.junit.Test; public class XhtmlTest { @Test public void testXhtml() throws Exception { Abdera abdera = new Abdera(); Entry entry = abdera.newEntry(); entry.setContentAsXhtml("<p>Test</p>"); assertNotNull(entry.getContent()); assertEquals(Content.Type.XHTML, entry.getContentType()); Element el = entry.getContentElement().getValueElement(); assertTrue(el instanceof Div); entry = abdera.newEntry(); entry.setContent("<a><b><c/></b></a>", Content.Type.XML); assertNotNull(entry.getContent()); assertEquals(Content.Type.XML, entry.getContentType()); assertNotNull(entry.getContentElement().getValueElement()); } @Test public void testSpecialCharacters() { Abdera abdera = new Abdera(); Entry entry = abdera.newEntry(); entry.setContentAsXhtml("<p>&Auml;sthetik</p>"); assertNotNull(entry.getContent()); assertEquals(Content.Type.XHTML, entry.getContentType()); Element el = entry.getContentElement().getValueElement(); char umlaut = ((Element)el.getFirstChild()).getText().charAt(0); // hexadecimal value of &Auml; is U+00C4 assertEquals("c4", Integer.toHexString(umlaut)); } }
7,441
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMExtensibleElement.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.parser.stax; import java.util.List; import javax.xml.namespace.QName; import org.apache.abdera.model.Element; import org.apache.abdera.model.ElementWrapper; import org.apache.abdera.model.ExtensibleElement; import org.apache.abdera.parser.stax.util.FOMElementIteratorWrapper; import org.apache.abdera.parser.stax.util.FOMExtensionIterator; import org.apache.abdera.parser.stax.util.FOMList; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMXMLParserWrapper; @SuppressWarnings("unchecked") public class FOMExtensibleElement extends FOMElement implements ExtensibleElement { private static final long serialVersionUID = -1652430686161947531L; protected FOMExtensibleElement(String name, OMNamespace namespace, OMContainer parent, OMFactory factory) throws OMException { super(name, namespace, parent, factory); } protected FOMExtensibleElement(QName qname, OMContainer parent, OMFactory factory) throws OMException { super(qname, parent, factory); } protected FOMExtensibleElement(String localName, OMContainer parent, OMFactory factory, OMXMLParserWrapper builder) throws OMException { super(localName, parent, factory, builder); } public List<Element> getExtensions() { return new FOMList<Element>(new FOMExtensionIterator(this)); } public List<Element> getExtensions(String uri) { return new FOMList<Element>(new FOMExtensionIterator(this, uri)); } public <T extends Element> List<T> getExtensions(QName qname) { FOMFactory factory = (FOMFactory)this.getFactory(); return new FOMList<T>(new FOMElementIteratorWrapper(factory, getChildrenWithName(qname))); } public <T extends Element> T getExtension(QName qname) { FOMFactory factory = (FOMFactory)getFactory(); T t = (T)this.getFirstChildWithName(qname); return (T)((t != null) ? factory.getElementWrapper(t) : null); } public <T extends ExtensibleElement> T addExtension(Element extension) { complete(); if (extension instanceof ElementWrapper) { ElementWrapper wrapper = (ElementWrapper)extension; extension = wrapper.getInternal(); } QName qname = extension.getQName(); String prefix = qname.getPrefix(); declareIfNecessary(qname.getNamespaceURI(), prefix); addChild((OMElement)extension); return (T)this; } public <T extends Element> T addExtension(QName qname) { complete(); FOMFactory fomfactory = (FOMFactory)getOMFactory(); String prefix = qname.getPrefix(); declareIfNecessary(qname.getNamespaceURI(), prefix); return (T)fomfactory.newExtensionElement(qname, this); } public <T extends Element> T addExtension(String namespace, String localpart, String prefix) { complete(); declareIfNecessary(namespace, prefix); return (prefix != null) ? (T)addExtension(new QName(namespace, localpart, prefix)) : (T)addExtension(new QName(namespace, localpart, "")); } public Element addSimpleExtension(QName qname, String value) { complete(); FOMFactory fomfactory = (FOMFactory)getOMFactory(); Element el = fomfactory.newElement(qname, this); el.setText(value); String prefix = qname.getPrefix(); declareIfNecessary(qname.getNamespaceURI(), prefix); return el; } public Element addSimpleExtension(String namespace, String localPart, String prefix, String value) { complete(); declareIfNecessary(namespace, prefix); return addSimpleExtension((prefix != null) ? new QName(namespace, localPart, prefix) : new QName(namespace, localPart), value); } public String getSimpleExtension(QName qname) { Element el = getExtension(qname); return (el != null) ? el.getText() : null; } public String getSimpleExtension(String namespace, String localPart, String prefix) { return getSimpleExtension(new QName(namespace, localPart, prefix)); } public void addExtensions(List<Element> extensions) { for (Element e : extensions) { addExtension(e); } } /** * Trick using Generics to find an extension element without having to pass in it's QName */ public <T extends Element> T getExtension(Class<T> _class) { T t = null; List<Element> extensions = getExtensions(); for (Element ext : extensions) { if (_class.isAssignableFrom(ext.getClass())) { t = (T)ext; break; } } return t; } private Element getInternal(Element element) { if (element instanceof ElementWrapper) { ElementWrapper wrapper = (ElementWrapper)element; element = wrapper.getInternal(); } return element; } public <T extends ExtensibleElement> T addExtension(Element extension, Element before) { complete(); extension = getInternal(extension); before = getInternal(before); if (before instanceof ElementWrapper) { ElementWrapper wrapper = (ElementWrapper)before; before = wrapper.getInternal(); } if (before == null) { addExtension(extension); } else { ((OMElement)before).insertSiblingBefore((OMElement)extension); } return (T)this; } public <T extends Element> T addExtension(QName qname, QName before) { complete(); OMElement el = getFirstChildWithName(before); T element = (T)getFactory().newElement(qname); if (el == null) { addExtension(element); } else { el.insertSiblingBefore((OMElement)getInternal(element)); } return (T)element; } }
7,442
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMDateTime.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.parser.stax; import java.util.Calendar; import java.util.Date; import javax.xml.namespace.QName; import org.apache.abdera.model.AtomDate; import org.apache.abdera.model.DateTime; import org.apache.abdera.model.Element; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMXMLParserWrapper; public class FOMDateTime extends FOMElement implements DateTime { private static final long serialVersionUID = -6611503566172011733L; private AtomDate value; protected FOMDateTime(String name, OMNamespace namespace, OMContainer parent, OMFactory factory) throws OMException { super(name, namespace, parent, factory); } protected FOMDateTime(QName qname, OMContainer parent, OMFactory factory) throws OMException { super(qname, parent, factory); } protected FOMDateTime(String localName, OMContainer parent, OMFactory factory, OMXMLParserWrapper builder) throws OMException { super(localName, parent, factory, builder); } public AtomDate getValue() { if (value == null) { String v = getText(); if (v != null) { value = AtomDate.valueOf(v); } } return value; } public DateTime setValue(AtomDate dateTime) { complete(); value = null; if (dateTime != null) ((Element)this).setText(dateTime.getValue()); else _removeAllChildren(); return this; } public DateTime setDate(Date date) { complete(); value = null; if (date != null) ((Element)this).setText(AtomDate.valueOf(date).getValue()); else _removeAllChildren(); return this; } public DateTime setCalendar(Calendar date) { complete(); value = null; if (date != null) ((Element)this).setText(AtomDate.valueOf(date).getValue()); else _removeAllChildren(); return this; } public DateTime setTime(long date) { complete(); value = null; ((Element)this).setText(AtomDate.valueOf(date).getValue()); return this; } public DateTime setString(String date) { complete(); value = null; if (date != null) ((Element)this).setText(AtomDate.valueOf(date).getValue()); else _removeAllChildren(); 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,443
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMParserOptions.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.parser.stax; import org.apache.abdera.factory.Factory; import org.apache.abdera.i18n.text.Localizer; import org.apache.abdera.util.AbstractParserOptions; public class FOMParserOptions extends AbstractParserOptions { public FOMParserOptions(Factory factory) { this.factory = factory; this.detect = true; } protected void initFactory() { if (factory == null) factory = new FOMFactory(); } protected void checkFactory(Factory factory) { if (!(factory instanceof FOMFactory)) throw new FOMException(Localizer.sprintf("WRONG.PARSER.INSTANCE", FOMFactory.class.getName())); } }
7,444
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMPerson.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.parser.stax; import javax.xml.namespace.QName; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Element; import org.apache.abdera.model.IRIElement; import org.apache.abdera.model.Person; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMXMLParserWrapper; public class FOMPerson extends FOMExtensibleElement implements Person { private static final long serialVersionUID = 2147684807662492625L; protected FOMPerson(String name, OMNamespace namespace, OMContainer parent, OMFactory factory) throws OMException { super(name, namespace, parent, factory); } protected FOMPerson(QName qname, OMContainer parent, OMFactory factory) throws OMException { super(qname, parent, factory); } protected FOMPerson(String localName, OMContainer parent, OMFactory factory, OMXMLParserWrapper builder) throws OMException { super(localName, parent, factory, builder); } public Element getNameElement() { return (Element)getFirstChildWithName(NAME); } public Person setNameElement(Element element) { complete(); if (element != null) _setChild(NAME, (OMElement)element); else _removeChildren(NAME, false); return this; } public Element setName(String name) { complete(); if (name != null) { FOMFactory fomfactory = (FOMFactory)getOMFactory(); Element el = fomfactory.newName(null); el.setText(name); _setChild(NAME, (OMElement)el); return el; } else { _removeChildren(NAME, false); return null; } } public String getName() { Element name = getNameElement(); return (name != null) ? name.getText() : null; } public Element getEmailElement() { return (Element)getFirstChildWithName(EMAIL); } public Person setEmailElement(Element element) { complete(); if (element != null) _setChild(EMAIL, (OMElement)element); else _removeChildren(EMAIL, false); return this; } public Element setEmail(String email) { complete(); if (email != null) { FOMFactory fomfactory = (FOMFactory)getOMFactory(); Element el = fomfactory.newEmail(null); el.setText(email); _setChild(EMAIL, (OMElement)el); return el; } else { _removeChildren(EMAIL, false); return null; } } public String getEmail() { Element email = getEmailElement(); return (email != null) ? email.getText() : null; } public IRIElement getUriElement() { return (IRIElement)getFirstChildWithName(URI); } public Person setUriElement(IRIElement uri) { complete(); if (uri != null) _setChild(URI, (OMElement)uri); else _removeChildren(URI, false); return this; } public IRIElement setUri(String uri) { complete(); if (uri != null) { FOMFactory fomfactory = (FOMFactory)getOMFactory(); IRIElement el = fomfactory.newUri(null); el.setValue(uri); _setChild(URI, (OMElement)el); return el; } else { _removeChildren(URI, false); return null; } } public IRI getUri() { IRIElement iri = getUriElement(); return (iri != null) ? iri.getResolvedValue() : null; } }
7,445
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMFactory.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.parser.stax; import java.util.ArrayList; import java.util.List; import javax.activation.MimeType; import javax.xml.namespace.QName; import org.apache.abdera.Abdera; import org.apache.abdera.factory.ExtensionFactory; import org.apache.abdera.factory.ExtensionFactoryMap; import org.apache.abdera.factory.Factory; 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.ExtensibleElement; 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.model.Content.Type; import org.apache.abdera.parser.Parser; import org.apache.abdera.parser.stax.util.FOMHelper; import org.apache.abdera.util.Constants; import org.apache.abdera.util.MimeTypeHelper; import org.apache.abdera.util.Version; import org.apache.axiom.core.CoreCDATASection; import org.apache.axiom.core.CoreCharacterData; import org.apache.axiom.om.OMAbstractFactory; import org.apache.axiom.om.OMComment; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMDocument; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMProcessingInstruction; import org.apache.axiom.om.OMXMLParserWrapper; import org.apache.axiom.om.impl.llom.factory.OMLinkedListImplFactory; @SuppressWarnings( {"unchecked", "deprecation"}) public class FOMFactory extends OMLinkedListImplFactory implements Factory, Constants, ExtensionFactory { private final ExtensionFactoryMap factoriesMap; private final Abdera abdera; public static void registerAsDefault() { System.setProperty(OMAbstractFactory.META_FACTORY_NAME_PROPERTY, FOMFactory.class.getName()); } public FOMFactory() { this(new Abdera()); } public FOMFactory(Abdera abdera) { List<ExtensionFactory> f = abdera.getConfiguration().getExtensionFactories(); factoriesMap = new ExtensionFactoryMap((f != null) ? new ArrayList<ExtensionFactory>(f) : new ArrayList<ExtensionFactory>()); this.abdera = abdera; } public Parser newParser() { return new FOMParser(abdera); } public <T extends Element> Document<T> newDocument() { return new FOMDocument(this); } @Override public OMDocument createOMDocument(OMXMLParserWrapper parserWrapper) { return new FOMDocument(parserWrapper, this); } public Service newService(Base parent) { return new FOMService((OMContainer)parent, this); } public Workspace newWorkspace() { return newWorkspace(null); } public Workspace newWorkspace(Element parent) { return new FOMWorkspace((OMContainer)parent, this); } public Collection newCollection() { return newCollection(null); } public Collection newCollection(Element parent) { return new FOMCollection((OMContainer)parent, this); } public Collection newMultipartCollection(Element parent) { return new FOMMultipartCollection((OMContainer)parent, this); } public Feed newFeed() { Document<Feed> doc = newDocument(); return newFeed(doc); } public Entry newEntry() { Document<Entry> doc = newDocument(); return newEntry(doc); } public Service newService() { Document<Service> doc = newDocument(); return newService(doc); } public Feed newFeed(Base parent) { return new FOMFeed((OMContainer)parent, this); } public Entry newEntry(Base parent) { return new FOMEntry((OMContainer)parent, this); } public Category newCategory() { return newCategory(null); } public Category newCategory(Element parent) { return new FOMCategory((OMContainer)parent, this); } public Content newContent() { return newContent(Content.Type.TEXT); } public Content newContent(Type type) { if (type == null) type = Content.Type.TEXT; return newContent(type, null); } public Content newContent(Type type, Element parent) { if (type == null) type = Content.Type.TEXT; Content content = new FOMContent(type, (OMContainer)parent, this); if (type.equals(Content.Type.XML)) content.setMimeType(XML_MEDIA_TYPE); return content; } public Content newContent(MimeType mediaType) { return newContent(mediaType, null); } public Content newContent(MimeType mediaType, Element parent) { Content.Type type = (MimeTypeHelper.isXml(mediaType.toString())) ? Content.Type.XML : Content.Type.MEDIA; Content content = newContent(type, parent); content.setMimeType(mediaType.toString()); return content; } public DateTime newDateTime(QName qname, Element parent) { return new FOMDateTime(qname, (OMContainer)parent, this); } public Generator newDefaultGenerator() { return newDefaultGenerator(null); } public Generator newDefaultGenerator(Element parent) { Generator generator = newGenerator(parent); generator.setVersion(Version.VERSION); generator.setText(Version.APP_NAME); generator.setUri(Version.URI); return generator; } public Generator newGenerator() { return newGenerator(null); } public Generator newGenerator(Element parent) { return new FOMGenerator((OMContainer)parent, this); } public IRIElement newID() { return newID(null); } public IRIElement newID(Element parent) { return new FOMIRI(Constants.ID, (OMContainer)parent, this); } public IRIElement newIRIElement(QName qname, Element parent) { return new FOMIRI(qname, (OMContainer)parent, this); } public Link newLink() { return newLink(null); } public Link newLink(Element parent) { return new FOMLink((OMContainer)parent, this); } public Person newPerson(QName qname, Element parent) { return new FOMPerson(qname, (OMContainer)parent, this); } public Source newSource() { return newSource(null); } public Source newSource(Element parent) { return new FOMSource((OMContainer)parent, this); } public Text newText(QName qname, Text.Type type) { return newText(qname, type, null); } public Text newText(QName qname, Text.Type type, Element parent) { if (type == null) type = Text.Type.TEXT; return new FOMText(type, qname, (OMContainer)parent, this); } public <T extends Element> T newElement(QName qname) { return (T)newElement(qname, null); } public <T extends Element> T newElement(QName qname, Base parent) { return (T)newExtensionElement(qname, parent); } public <T extends Element> T newExtensionElement(QName qname) { return (T)newExtensionElement(qname, null); } public <T extends Element> T newExtensionElement(QName qname, Base parent) { String ns = qname.getNamespaceURI(); Element el = (Element)createElement(qname, (OMContainer)parent, this, null); return (T)((ATOM_NS.equals(ns) || APP_NS.equals(ns)) ? el : factoriesMap.getElementWrapper(el)); } public Control newControl() { return newControl(null); } public Control newControl(Element parent) { return new FOMControl((OMContainer)parent, this); } public DateTime newPublished() { return newPublished(null); } public DateTime newPublished(Element parent) { return newDateTime(Constants.PUBLISHED, parent); } public DateTime newUpdated() { return newUpdated(null); } public DateTime newUpdated(Element parent) { return newDateTime(Constants.UPDATED, parent); } public DateTime newEdited() { return newEdited(null); } public DateTime newEdited(Element parent) { return newDateTime(Constants.EDITED, parent); } public IRIElement newIcon() { return newIcon(null); } public IRIElement newIcon(Element parent) { return newIRIElement(Constants.ICON, parent); } public IRIElement newLogo() { return newLogo(null); } public IRIElement newLogo(Element parent) { return newIRIElement(Constants.LOGO, parent); } public IRIElement newUri() { return newUri(null); } public IRIElement newUri(Element parent) { return newIRIElement(Constants.URI, parent); } public Person newAuthor() { return newAuthor(null); } public Person newAuthor(Element parent) { return newPerson(Constants.AUTHOR, parent); } public Person newContributor() { return newContributor(null); } public Person newContributor(Element parent) { return newPerson(Constants.CONTRIBUTOR, parent); } public Text newTitle() { return newTitle(Text.Type.TEXT); } public Text newTitle(Element parent) { return newTitle(Text.Type.TEXT, parent); } public Text newTitle(Text.Type type) { return newTitle(type, null); } public Text newTitle(Text.Type type, Element parent) { return newText(Constants.TITLE, type, parent); } public Text newSubtitle() { return newSubtitle(Text.Type.TEXT); } public Text newSubtitle(Element parent) { return newSubtitle(Text.Type.TEXT, parent); } public Text newSubtitle(Text.Type type) { return newSubtitle(type, null); } public Text newSubtitle(Text.Type type, Element parent) { return newText(Constants.SUBTITLE, type, parent); } public Text newSummary() { return newSummary(Text.Type.TEXT); } public Text newSummary(Element parent) { return newSummary(Text.Type.TEXT, parent); } public Text newSummary(Text.Type type) { return newSummary(type, null); } public Text newSummary(Text.Type type, Element parent) { return newText(Constants.SUMMARY, type, parent); } public Text newRights() { return newRights(Text.Type.TEXT); } public Text newRights(Element parent) { return newRights(Text.Type.TEXT, parent); } public Text newRights(Text.Type type) { return newRights(type, null); } public Text newRights(Text.Type type, Element parent) { return newText(Constants.RIGHTS, type, parent); } public Element newName() { return newName(null); } public Element newName(Element parent) { return newElement(Constants.NAME, parent); } public Element newEmail() { return newEmail(null); } public Element newEmail(Element parent) { return newElement(Constants.EMAIL, parent); } public Div newDiv() { return newDiv(null); } public Div newDiv(Base parent) { return new FOMDiv(DIV, (OMContainer)parent, this); } protected OMElement createElement(QName qname, OMContainer parent, OMFactory factory, Object objecttype) { OMElement element = null; OMNamespace namespace = this.createOMNamespace(qname.getNamespaceURI(), qname.getPrefix()); if (FEED.equals(qname)) { element = new FOMFeed(qname.getLocalPart(), namespace, parent, factory); } else if (SERVICE.equals(qname) || PRE_RFC_SERVICE.equals(qname)) { element = new FOMService(qname.getLocalPart(), namespace, parent, factory); } else if (ENTRY.equals(qname)) { element = new FOMEntry(qname.getLocalPart(), namespace, parent, factory); } else if (AUTHOR.equals(qname)) { element = new FOMPerson(qname.getLocalPart(), namespace, parent, factory); } else if (CATEGORY.equals(qname)) { element = new FOMCategory(qname.getLocalPart(), namespace, parent, factory); } else if (CONTENT.equals(qname)) { Content.Type type = (Content.Type)objecttype; element = new FOMContent(qname.getLocalPart(), namespace, type, parent, factory); } else if (CONTRIBUTOR.equals(qname)) { element = new FOMPerson(qname.getLocalPart(), namespace, parent, factory); } else if (GENERATOR.equals(qname)) { element = new FOMGenerator(qname.getLocalPart(), namespace, parent, factory); } else if (ICON.equals(qname)) { element = new FOMIRI(qname.getLocalPart(), namespace, parent, factory); } else if (ID.equals(qname)) { element = new FOMIRI(qname.getLocalPart(), namespace, parent, factory); } else if (LOGO.equals(qname)) { element = new FOMIRI(qname.getLocalPart(), namespace, parent, factory); } else if (LINK.equals(qname)) { element = new FOMLink(qname.getLocalPart(), namespace, parent, factory); } else if (PUBLISHED.equals(qname)) { element = new FOMDateTime(qname.getLocalPart(), namespace, parent, factory); } else if (RIGHTS.equals(qname)) { Text.Type type = (Text.Type)objecttype; element = new FOMText(type, qname.getLocalPart(), namespace, parent, factory); } else if (SOURCE.equals(qname)) { element = new FOMSource(qname.getLocalPart(), namespace, parent, factory); } else if (SUBTITLE.equals(qname)) { Text.Type type = (Text.Type)objecttype; element = new FOMText(type, qname.getLocalPart(), namespace, parent, factory); } else if (SUMMARY.equals(qname)) { Text.Type type = (Text.Type)objecttype; element = new FOMText(type, qname.getLocalPart(), namespace, parent, factory); } else if (TITLE.equals(qname)) { Text.Type type = (Text.Type)objecttype; element = new FOMText(type, qname.getLocalPart(), namespace, parent, factory); } else if (UPDATED.equals(qname)) { element = new FOMDateTime(qname.getLocalPart(), namespace, parent, factory); } else if (WORKSPACE.equals(qname) || PRE_RFC_WORKSPACE.equals(qname)) { element = new FOMWorkspace(qname.getLocalPart(), namespace, parent, factory); } else if (COLLECTION.equals(qname) || PRE_RFC_COLLECTION.equals(qname)) { element = new FOMCollection(qname.getLocalPart(), namespace, parent, factory); } else if (NAME.equals(qname)) { element = new FOMElement(qname.getLocalPart(), namespace, parent, factory); } else if (EMAIL.equals(qname)) { element = new FOMElement(qname.getLocalPart(), namespace, parent, factory); } else if (URI.equals(qname)) { element = new FOMIRI(qname.getLocalPart(), namespace, parent, factory); } else if (CONTROL.equals(qname) || PRE_RFC_CONTROL.equals(qname)) { element = new FOMControl(qname.getLocalPart(), namespace, parent, factory); } else if (DIV.equals(qname)) { element = new FOMDiv(qname.getLocalPart(), namespace, parent, factory); } else if (CATEGORIES.equals(qname) || PRE_RFC_CATEGORIES.equals(qname)) { element = new FOMCategories(qname.getLocalPart(), namespace, parent, factory); } else if (EDITED.equals(qname) || PRE_RFC_EDITED.equals(qname)) { element = new FOMDateTime(qname.getLocalPart(), namespace, parent, factory); } else if (parent instanceof ExtensibleElement || parent instanceof Document) { element = (OMElement)new FOMExtensibleElement(qname, parent, this); } else { element = (OMElement)new FOMExtensibleElement(qname, null, this); } return element; } protected OMElement createElement(QName qname, OMContainer parent, FOMBuilder builder) { OMElement element = null; if (FEED.equals(qname)) { element = new FOMFeed(qname.getLocalPart(), parent, this, builder); } else if (SERVICE.equals(qname) || PRE_RFC_SERVICE.equals(qname)) { element = new FOMService(qname.getLocalPart(), parent, this, builder); } else if (ENTRY.equals(qname)) { element = new FOMEntry(qname.getLocalPart(), parent, this, builder); } else if (AUTHOR.equals(qname)) { element = new FOMPerson(qname.getLocalPart(), parent, this, builder); } else if (CATEGORY.equals(qname)) { element = new FOMCategory(qname.getLocalPart(), parent, this, builder); } else if (CONTENT.equals(qname)) { Content.Type type = builder.getContentType(); if (type == null) type = Content.Type.TEXT; element = new FOMContent(qname.getLocalPart(), type, parent, this, builder); } else if (CONTRIBUTOR.equals(qname)) { element = new FOMPerson(qname.getLocalPart(), parent, this, builder); } else if (GENERATOR.equals(qname)) { element = new FOMGenerator(qname.getLocalPart(), parent, this, builder); } else if (ICON.equals(qname)) { element = new FOMIRI(qname.getLocalPart(), parent, this, builder); } else if (ID.equals(qname)) { element = new FOMIRI(qname.getLocalPart(), parent, this, builder); } else if (LOGO.equals(qname)) { element = new FOMIRI(qname.getLocalPart(), parent, this, builder); } else if (LINK.equals(qname)) { element = new FOMLink(qname.getLocalPart(), parent, this, builder); } else if (PUBLISHED.equals(qname)) { element = new FOMDateTime(qname.getLocalPart(), parent, this, builder); } else if (RIGHTS.equals(qname)) { Text.Type type = builder.getTextType(); if (type == null) type = Text.Type.TEXT; element = new FOMText(type, qname.getLocalPart(), parent, this, builder); } else if (SOURCE.equals(qname)) { element = new FOMSource(qname.getLocalPart(), parent, this, builder); } else if (SUBTITLE.equals(qname)) { Text.Type type = builder.getTextType(); if (type == null) type = Text.Type.TEXT; element = new FOMText(type, qname.getLocalPart(), parent, this, builder); } else if (SUMMARY.equals(qname)) { Text.Type type = builder.getTextType(); if (type == null) type = Text.Type.TEXT; element = new FOMText(type, qname.getLocalPart(), parent, this, builder); } else if (TITLE.equals(qname)) { Text.Type type = builder.getTextType(); if (type == null) type = Text.Type.TEXT; element = new FOMText(type, qname.getLocalPart(), parent, this, builder); } else if (UPDATED.equals(qname)) { element = new FOMDateTime(qname.getLocalPart(), parent, this, builder); } else if (WORKSPACE.equals(qname) || PRE_RFC_WORKSPACE.equals(qname)) { element = new FOMWorkspace(qname.getLocalPart(), parent, this, builder); } else if (COLLECTION.equals(qname) || PRE_RFC_COLLECTION.equals(qname)) { element = new FOMCollection(qname.getLocalPart(), parent, this, builder); } else if (NAME.equals(qname)) { element = new FOMElement(qname.getLocalPart(), parent, this, builder); } else if (EMAIL.equals(qname)) { element = new FOMElement(qname.getLocalPart(), parent, this, builder); } else if (URI.equals(qname)) { element = new FOMIRI(qname.getLocalPart(), parent, this, builder); } else if (CONTROL.equals(qname) || PRE_RFC_CONTROL.equals(qname)) { element = new FOMControl(qname.getLocalPart(), parent, this, builder); } else if (DIV.equals(qname)) { element = new FOMDiv(qname.getLocalPart(), parent, this, builder); } else if (CATEGORIES.equals(qname) || PRE_RFC_CATEGORIES.equals(qname)) { element = new FOMCategories(qname.getLocalPart(), parent, this, builder); } else if (EDITED.equals(qname) || PRE_RFC_EDITED.equals(qname)) { element = new FOMDateTime(qname.getLocalPart(), parent, this, builder); } else if (parent instanceof ExtensibleElement || parent instanceof Document) { element = new FOMExtensibleElement(qname.getLocalPart(), parent, this, builder); } return element; } public Factory registerExtension(ExtensionFactory factory) { factoriesMap.addFactory(factory); return this; } public Categories newCategories() { Document<Categories> doc = newDocument(); return newCategories(doc); } public Categories newCategories(Base parent) { return new FOMCategories((OMContainer)parent, this); } public String newUuidUri() { return FOMHelper.generateUuid(); } // public void setElementWrapper(Element internal, Element wrapper) { // factoriesMap.setElementWrapper(internal, wrapper); // } // public <T extends Element> T getElementWrapper(Element internal) { if (internal == null) return null; String ns = internal.getQName().getNamespaceURI(); return (T)((ATOM_NS.equals(ns) || APP_NS.equals(ns) || internal.getQName().equals(DIV)) ? internal : factoriesMap.getElementWrapper(internal)); } public String[] getNamespaces() { return factoriesMap.getNamespaces(); } public boolean handlesNamespace(String namespace) { return factoriesMap.handlesNamespace(namespace); } public Abdera getAbdera() { return abdera; } public <T extends Base> String getMimeType(T base) { String type = factoriesMap.getMimeType(base); return type; } public String[] listExtensionFactories() { return factoriesMap.listExtensionFactories(); } @Override public OMComment createOMComment(OMContainer arg0, String arg1) { return new FOMComment(arg0, arg1, this, false); } @Override public OMProcessingInstruction createOMProcessingInstruction(OMContainer arg0, String arg1, String arg2) { return new FOMProcessingInstruction(arg0, arg1, arg2, this, false); } @Override public CoreCharacterData createCharacterData() { return new FOMCharacterData(this); } @Override public CoreCDATASection createCDATASection() { return new FOMCDATASection(this); } }
7,446
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMCharacterData.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.parser.stax; import java.io.IOException; import java.io.InputStream; import javax.activation.DataHandler; import org.apache.abdera.factory.Factory; import org.apache.abdera.model.Base; import org.apache.abdera.model.Element; import org.apache.abdera.model.TextValue; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.impl.llom.CharacterDataImpl; @SuppressWarnings("unchecked") public class FOMCharacterData extends CharacterDataImpl implements TextValue { public FOMCharacterData(OMFactory factory) { super(factory); } public DataHandler getDataHandler() { return (DataHandler)super.getDataHandler(); } public InputStream getInputStream() { try { return getDataHandler().getInputStream(); } catch (IOException ex) { throw new FOMException(ex); } } public <T extends Base> T getParentElement() { T parent = (T)super.getParent(); return (T)((parent instanceof Element) ? getWrapped((Element)parent) : parent); } protected Element getWrapped(Element internal) { if (internal == null) return null; FOMFactory factory = (FOMFactory)getFactory(); return factory.getElementWrapper(internal); } public Factory getFactory() { return (Factory)this.getOMFactory(); } @Override public String toString() { return getText(); } }
7,447
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMMetaFactory.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.parser.stax; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.impl.llom.factory.OMLinkedListMetaFactory; public class FOMMetaFactory extends OMLinkedListMetaFactory { private final OMFactory omFactory = new FOMFactory(); public OMFactory getOMFactory() { return omFactory; } }
7,448
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMCDATASection.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.parser.stax; import java.io.IOException; import java.io.InputStream; import javax.activation.DataHandler; import org.apache.abdera.factory.Factory; import org.apache.abdera.model.Base; import org.apache.abdera.model.Element; import org.apache.abdera.model.TextValue; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.impl.llom.CDATASectionImpl; @SuppressWarnings("unchecked") public class FOMCDATASection extends CDATASectionImpl implements TextValue { public FOMCDATASection(OMFactory factory) { super(factory); } public DataHandler getDataHandler() { return (DataHandler)super.getDataHandler(); } public InputStream getInputStream() { try { return getDataHandler().getInputStream(); } catch (IOException ex) { throw new FOMException(ex); } } public <T extends Base> T getParentElement() { T parent = (T)super.getParent(); return (T)((parent instanceof Element) ? getWrapped((Element)parent) : parent); } protected Element getWrapped(Element internal) { if (internal == null) return null; FOMFactory factory = (FOMFactory)getFactory(); return factory.getElementWrapper(internal); } public Factory getFactory() { return (Factory)this.getOMFactory(); } @Override public String toString() { return getText(); } }
7,449
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMUnsupportedContentTypeException.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.parser.stax; import org.apache.abdera.i18n.text.Localizer; public class FOMUnsupportedContentTypeException extends FOMException { private static final long serialVersionUID = 4156893310308105899L; public FOMUnsupportedContentTypeException(String message) { super(Localizer.sprintf("UNSUPPORTED.CONTENT.TYPE", message)); } }
7,450
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMCollection.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.parser.stax; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.activation.MimeType; import javax.xml.namespace.QName; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Categories; import org.apache.abdera.model.Category; import org.apache.abdera.model.Collection; import org.apache.abdera.model.Element; import org.apache.abdera.model.Text; import org.apache.abdera.util.MimeTypeHelper; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMXMLParserWrapper; @SuppressWarnings("deprecation") public class FOMCollection extends FOMExtensibleElement implements Collection { private static final String[] ENTRY = {"application/atom+xml;type=\"entry\""}; private static final String[] EMPTY = new String[0]; private static final long serialVersionUID = -5291734055253987136L; protected FOMCollection(String name, OMNamespace namespace, OMContainer parent, OMFactory factory) throws OMException { super(name, namespace, parent, factory); } protected FOMCollection(QName qname, OMContainer parent, OMFactory factory) { super(qname, parent, factory); } protected FOMCollection(String localName, OMContainer parent, OMFactory factory, OMXMLParserWrapper builder) { super(localName, parent, factory, builder); } protected FOMCollection(OMContainer parent, OMFactory factory) { super(COLLECTION, parent, factory); } public String getTitle() { Text title = this.getFirstChild(TITLE); return (title != null) ? title.getValue() : null; } private Text setTitle(String title, Text.Type type) { complete(); FOMFactory fomfactory = (FOMFactory)getOMFactory(); Text text = fomfactory.newText(PREFIXED_TITLE, type); text.setValue(title); this._setChild(PREFIXED_TITLE, (OMElement)text); return text; } public Text setTitle(String title) { return setTitle(title, Text.Type.TEXT); } public Text setTitleAsHtml(String title) { return setTitle(title, Text.Type.HTML); } public Text setTitleAsXHtml(String title) { return setTitle(title, Text.Type.XHTML); } public Text getTitleElement() { return getFirstChild(TITLE); } public IRI getHref() { return _getUriValue(getAttributeValue(HREF)); } public IRI getResolvedHref() { return _resolve(getResolvedBaseUri(), getHref()); } public Collection setHref(String href) { complete(); if (href != null) setAttributeValue(HREF, (new IRI(href).toString())); else removeAttribute(HREF); return this; } public String[] getAccept() { List<String> accept = new ArrayList<String>(); Iterator<?> i = getChildrenWithName(ACCEPT); if (i == null || !i.hasNext()) i = getChildrenWithName(PRE_RFC_ACCEPT); while (i.hasNext()) { Element e = (Element)i.next(); String t = e.getText(); if (t != null) { accept.add(t.trim()); } } if (accept.size() > 0) { String[] list = accept.toArray(new String[accept.size()]); return MimeTypeHelper.condense(list); } else { return EMPTY; } } public Collection setAccept(String mediaRange) { return setAccept(new String[] {mediaRange}); } public Collection setAccept(String... mediaRanges) { complete(); if (mediaRanges != null && mediaRanges.length > 0) { _removeChildren(ACCEPT, true); _removeChildren(PRE_RFC_ACCEPT, true); if (mediaRanges.length == 1 && mediaRanges[0].equals("")) { addExtension(ACCEPT); } else { mediaRanges = MimeTypeHelper.condense(mediaRanges); for (String type : mediaRanges) { if (type.equalsIgnoreCase("entry")) { addSimpleExtension(ACCEPT, "application/atom+xml;type=entry"); } else { try { addSimpleExtension(ACCEPT, new MimeType(type).toString()); } catch (javax.activation.MimeTypeParseException e) { throw new org.apache.abdera.util.MimeTypeParseException(e); } } } } } else { _removeChildren(ACCEPT, true); _removeChildren(PRE_RFC_ACCEPT, true); } return this; } public Collection addAccepts(String mediaRange) { return addAccepts(new String[] {mediaRange}); } public Collection addAccepts(String... mediaRanges) { complete(); if (mediaRanges != null) { for (String type : mediaRanges) { if (!accepts(type)) { try { addSimpleExtension(ACCEPT, new MimeType(type).toString()); } catch (Exception e) { } } } } return this; } public Collection addAcceptsEntry() { return addAccepts("application/atom+xml;type=entry"); } public Collection setAcceptsEntry() { return setAccept("application/atom+xml;type=entry"); } public Collection setAcceptsNothing() { return setAccept(""); } public boolean acceptsEntry() { return accepts("application/atom+xml;type=entry"); } public boolean acceptsNothing() { return accepts(""); } public boolean accepts(String mediaType) { String[] accept = getAccept(); if (accept.length == 0) accept = ENTRY; for (String a : accept) { if (MimeTypeHelper.isMatch(a, mediaType)) return true; } return false; } public boolean accepts(MimeType mediaType) { return accepts(mediaType.toString()); } public Categories addCategories() { complete(); return ((FOMFactory)getOMFactory()).newCategories(this); } public Collection addCategories(Categories categories) { complete(); addChild((OMElement)categories); return this; } public Categories addCategories(String href) { complete(); Categories cats = ((FOMFactory)getOMFactory()).newCategories(); cats.setHref(href); addCategories(cats); return cats; } public Categories addCategories(List<Category> categories, boolean fixed, String scheme) { complete(); Categories cats = ((FOMFactory)getOMFactory()).newCategories(); cats.setFixed(fixed); if (scheme != null) cats.setScheme(scheme); if (categories != null) { for (Category category : categories) { cats.addCategory(category); } } addCategories(cats); return cats; } public List<Categories> getCategories() { List<Categories> list = _getChildrenAsSet(CATEGORIES); if (list == null || list.size() == 0) list = _getChildrenAsSet(PRE_RFC_CATEGORIES); return list; } }
7,451
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMBuilder.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.parser.stax; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamReader; import org.apache.abdera.model.Content; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.model.Text; import org.apache.abdera.parser.ParseException; import org.apache.abdera.parser.ParserOptions; import org.apache.abdera.util.Constants; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMException; import org.apache.axiom.om.impl.builder.StAXOMBuilder; @SuppressWarnings("unchecked") public class FOMBuilder extends StAXOMBuilder implements Constants { private final FOMFactory fomfactory; private final ParserOptions parserOptions; public FOMBuilder(FOMFactory factory, XMLStreamReader parser, ParserOptions parserOptions) { super(factory, new FOMStAXFilter(parser, parserOptions)); this.parserOptions = parserOptions; this.fomfactory = factory; } public ParserOptions getParserOptions() { return parserOptions; } protected Text.Type getTextType() { Text.Type ttype = Text.Type.TEXT; String type = parser.getAttributeValue(null, LN_TYPE); if (type != null) { ttype = Text.Type.typeFromString(type); if (ttype == null) throw new FOMUnsupportedTextTypeException(type); } return ttype; } protected Content.Type getContentType() { Content.Type ctype = Content.Type.TEXT; String type = parser.getAttributeValue(null, LN_TYPE); String src = parser.getAttributeValue(null, LN_SRC); if (type != null) { ctype = Content.Type.typeFromString(type); if (ctype == null) throw new FOMUnsupportedContentTypeException(type); } else if (type == null && src != null) { ctype = Content.Type.MEDIA; } return ctype; } /** * Method next. * * @return Returns int. * @throws OMException */ public int next() throws OMException { try { return super.next(); } catch (OMException e) { // TODO: transforming the OMException here is not ideal! throw new ParseException(e); } } @Override protected OMElement constructNode(OMContainer parent, String name) { QName qname = parser.getName(); OMElement element = fomfactory.createElement(qname, parent, this); if (element == null) { element = new FOMElement(qname.getLocalPart(), parent, fomfactory, this); } return element; } public <T extends Element> Document<T> getFomDocument() { // For compatibility with earlier Abdera versions, force creation of the document element. // Note that the only known case where this has a visible effect is when the document is // not well formed. At least one unit test depends on this behavior. getDocumentElement(); return (Document<T>)getDocument(); } public FOMFactory getFactory() { return fomfactory; } }
7,452
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMSource.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.parser.stax; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.xml.namespace.QName; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.iri.IRIHelper; import org.apache.abdera.model.AtomDate; import org.apache.abdera.model.Categories; import org.apache.abdera.model.Category; import org.apache.abdera.model.Collection; import org.apache.abdera.model.DateTime; import org.apache.abdera.model.Div; import org.apache.abdera.model.Element; 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.Source; import org.apache.abdera.model.Text; import org.apache.abdera.parser.stax.util.FOMHelper; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMNode; import org.apache.axiom.om.OMXMLParserWrapper; @SuppressWarnings( {"unchecked", "deprecation"}) public class FOMSource extends FOMExtensibleElement implements Source { private static final long serialVersionUID = 9153127297531238021L; protected FOMSource(String name, OMNamespace namespace, OMContainer parent, OMFactory factory) throws OMException { super(name, namespace, parent, factory); } protected FOMSource(OMContainer parent, OMFactory factory) throws OMException { super(SOURCE, parent, factory); } protected FOMSource(QName qname, OMContainer parent, OMFactory factory) throws OMException { super(qname, parent, factory); } protected FOMSource(String localName, OMContainer parent, OMFactory factory, OMXMLParserWrapper builder) throws OMException { super(localName, parent, factory, builder); } public Person getAuthor() { return (Person)getFirstChildWithName(AUTHOR); } public List<Person> getAuthors() { return _getChildrenAsSet(AUTHOR); } public <T extends Source> T addAuthor(Person person) { complete(); addChild((OMElement)person); return (T)this; } public Person addAuthor(String name) { complete(); FOMFactory fomfactory = (FOMFactory)this.getOMFactory(); Person person = fomfactory.newAuthor(this); person.setName(name); return person; } public Person addAuthor(String name, String email, String uri) { complete(); FOMFactory fomfactory = (FOMFactory)this.getOMFactory(); Person person = fomfactory.newAuthor(this); person.setName(name); person.setEmail(email); person.setUri(uri); return person; } public List<Category> getCategories() { return _getChildrenAsSet(CATEGORY); } public List<Category> getCategories(String scheme) { return FOMHelper.getCategories(this, scheme); } public <T extends Source> T addCategory(Category category) { complete(); Element el = category.getParentElement(); if (el != null && el instanceof Categories) { Categories cats = category.getParentElement(); category = (Category)category.clone(); try { if (category.getScheme() == null && cats.getScheme() != null) category.setScheme(cats.getScheme().toString()); } catch (Exception e) { // Do nothing, shouldn't happen } } addChild((OMElement)category); return (T)this; } public Category addCategory(String term) { complete(); FOMFactory factory = (FOMFactory)this.getOMFactory(); Category category = factory.newCategory(this); category.setTerm(term); return category; } public Category addCategory(String scheme, String term, String label) { complete(); FOMFactory factory = (FOMFactory)this.getOMFactory(); Category category = factory.newCategory(this); category.setTerm(term); category.setScheme(scheme); category.setLabel(label); return category; } public List<Person> getContributors() { return _getChildrenAsSet(CONTRIBUTOR); } public <T extends Source> T addContributor(Person person) { complete(); addChild((OMElement)person); return (T)this; } public Person addContributor(String name) { complete(); FOMFactory fomfactory = (FOMFactory)this.getOMFactory(); Person person = fomfactory.newContributor(this); person.setName(name); return person; } public Person addContributor(String name, String email, String uri) { complete(); FOMFactory fomfactory = (FOMFactory)this.getOMFactory(); Person person = fomfactory.newContributor(this); person.setName(name); person.setEmail(email); person.setUri(uri); return person; } public IRIElement getIdElement() { return (IRIElement)getFirstChildWithName(ID); } public <T extends Source> T setIdElement(IRIElement id) { complete(); if (id != null) _setChild(ID, (OMElement)id); else _removeChildren(ID, false); return (T)this; } public IRI getId() { IRIElement id = getIdElement(); return (id != null) ? id.getValue() : null; } public IRIElement setId(String value) { complete(); return setId(value, false); } public IRIElement newId() { return setId(this.getFactory().newUuidUri(), false); } public IRIElement setId(String value, boolean normalize) { complete(); if (value == null) { _removeChildren(ID, false); return null; } IRIElement id = getIdElement(); if (id != null) { if (normalize) id.setNormalizedValue(value); else id.setValue(value); return id; } else { FOMFactory fomfactory = (FOMFactory)getOMFactory(); IRIElement iri = fomfactory.newID(this); iri.setValue((normalize) ? IRI.normalizeString(value) : value); return iri; } } public List<Link> getLinks() { return _getChildrenAsSet(LINK); } public List<Link> getLinks(String rel) { return FOMHelper.getLinks(this, rel); } public List<Link> getLinks(String... rels) { return FOMHelper.getLinks(this, rels); } public <T extends Source> T addLink(Link link) { complete(); addChild((OMElement)link); return (T)this; } public Link addLink(String href) { return addLink(href, null); } public Link addLink(String href, String rel) { complete(); FOMFactory fomfactory = (FOMFactory)getOMFactory(); Link link = fomfactory.newLink(this); link.setHref(href); if (rel != null) link.setRel(rel); return link; } public Link addLink(String href, String rel, String type, String title, String hreflang, long length) { complete(); FOMFactory fomfactory = (FOMFactory)getOMFactory(); Link link = fomfactory.newLink(this); link.setHref(href); link.setRel(rel); link.setMimeType(type); link.setTitle(title); link.setHrefLang(hreflang); link.setLength(length); return link; } public Text getRightsElement() { return getTextElement(RIGHTS); } public <T extends Source> T setRightsElement(Text text) { complete(); setTextElement(RIGHTS, text, false); return (T)this; } public Text setRights(String value) { complete(); FOMFactory factory = (FOMFactory)this.getOMFactory(); Text text = factory.newRights(); text.setValue(value); setRightsElement(text); return text; } public Text setRightsAsHtml(String value) { return setRights(value, Text.Type.HTML); } public Text setRightsAsXhtml(String value) { return setRights(value, Text.Type.XHTML); } public Text setRights(String value, Text.Type type) { FOMFactory factory = (FOMFactory)this.getOMFactory(); Text text = factory.newRights(type); text.setValue(value); setRightsElement(text); return text; } public Text setRights(Div value) { FOMFactory factory = (FOMFactory)this.getOMFactory(); Text text = factory.newRights(Text.Type.XHTML); text.setValueElement(value); setRightsElement(text); return text; } public String getRights() { return getText(RIGHTS); } public Text getSubtitleElement() { return getTextElement(SUBTITLE); } public <T extends Source> T setSubtitleElement(Text text) { complete(); setTextElement(SUBTITLE, text, false); return (T)this; } public Text setSubtitle(String value) { complete(); FOMFactory factory = (FOMFactory)this.getOMFactory(); Text text = factory.newSubtitle(); text.setValue(value); setSubtitleElement(text); return text; } public Text setSubtitleAsHtml(String value) { return setSubtitle(value, Text.Type.HTML); } public Text setSubtitleAsXhtml(String value) { return setSubtitle(value, Text.Type.XHTML); } public Text setSubtitle(String value, Text.Type type) { FOMFactory factory = (FOMFactory)this.getOMFactory(); Text text = factory.newSubtitle(type); text.setValue(value); setSubtitleElement(text); return text; } public Text setSubtitle(Div value) { FOMFactory factory = (FOMFactory)this.getOMFactory(); Text text = factory.newSubtitle(Text.Type.XHTML); text.setValueElement(value); setSubtitleElement(text); return text; } public String getSubtitle() { return getText(SUBTITLE); } public Text getTitleElement() { return getTextElement(TITLE); } public <T extends Source> T setTitleElement(Text text) { complete(); setTextElement(TITLE, text, false); return (T)this; } public Text setTitle(String value) { complete(); FOMFactory factory = (FOMFactory)this.getOMFactory(); Text text = factory.newTitle(); text.setValue(value); setTitleElement(text); return text; } public Text setTitleAsHtml(String value) { return setTitle(value, Text.Type.HTML); } public Text setTitleAsXhtml(String value) { return setTitle(value, Text.Type.XHTML); } public Text setTitle(String value, Text.Type type) { FOMFactory factory = (FOMFactory)this.getOMFactory(); Text text = factory.newTitle(type); text.setValue(value); setTitleElement(text); return text; } public Text setTitle(Div value) { FOMFactory factory = (FOMFactory)this.getOMFactory(); Text text = factory.newTitle(Text.Type.XHTML); text.setValueElement(value); setTitleElement(text); return text; } public String getTitle() { return getText(TITLE); } public DateTime getUpdatedElement() { return (DateTime)getFirstChildWithName(UPDATED); } public <T extends Source> T setUpdatedElement(DateTime updated) { complete(); if (updated != null) _setChild(UPDATED, (OMElement)updated); else _removeChildren(UPDATED, false); return (T)this; } public String getUpdatedString() { DateTime dte = getUpdatedElement(); return (dte != null) ? dte.getString() : null; } public Date getUpdated() { DateTime dte = getUpdatedElement(); return (dte != null) ? dte.getDate() : null; } private DateTime setUpdated(AtomDate value) { complete(); if (value == null) { _removeChildren(UPDATED, false); return null; } DateTime dte = getUpdatedElement(); if (dte != null) { dte.setValue(value); return dte; } else { FOMFactory fomfactory = (FOMFactory)getOMFactory(); DateTime dt = fomfactory.newUpdated(this); dt.setValue(value); return dt; } } public DateTime setUpdated(Date value) { return setUpdated((value != null) ? AtomDate.valueOf(value) : null); } public DateTime setUpdated(String value) { return setUpdated((value != null) ? AtomDate.valueOf(value) : null); } public Generator getGenerator() { return (Generator)getFirstChildWithName(GENERATOR); } public <T extends Source> T setGenerator(Generator generator) { complete(); if (generator != null) _setChild(GENERATOR, (OMElement)generator); else _removeChildren(GENERATOR, false); return (T)this; } public Generator setGenerator(String uri, String version, String value) { complete(); FOMFactory fomfactory = (FOMFactory)getOMFactory(); Generator generator = fomfactory.newGenerator(this); if (uri != null) generator.setUri(uri); if (version != null) generator.setVersion(version); if (value != null) generator.setText(value); return generator; } public IRIElement getIconElement() { return (IRIElement)getFirstChildWithName(ICON); } public <T extends Source> T setIconElement(IRIElement iri) { complete(); if (iri != null) _setChild(ICON, (OMElement)iri); else _removeChildren(ICON, false); return (T)this; } public IRIElement setIcon(String value) { complete(); if (value == null) { _removeChildren(ICON, false); return null; } FOMFactory fomfactory = (FOMFactory)getOMFactory(); IRIElement iri = fomfactory.newIcon(this); iri.setValue(value); return iri; } public IRI getIcon() { IRIElement iri = getIconElement(); IRI uri = (iri != null) ? iri.getResolvedValue() : null; return (IRIHelper.isJavascriptUri(uri) || IRIHelper.isMailtoUri(uri)) ? null : uri; } public IRIElement getLogoElement() { return (IRIElement)getFirstChildWithName(LOGO); } public <T extends Source> T setLogoElement(IRIElement iri) { complete(); if (iri != null) _setChild(LOGO, (OMElement)iri); else _removeChildren(LOGO, false); return (T)this; } public IRIElement setLogo(String value) { complete(); if (value == null) { _removeChildren(LOGO, false); return null; } FOMFactory fomfactory = (FOMFactory)getOMFactory(); IRIElement iri = fomfactory.newLogo(this); iri.setValue(value); return iri; } public IRI getLogo() { IRIElement iri = getLogoElement(); IRI uri = (iri != null) ? iri.getResolvedValue() : null; return (IRIHelper.isJavascriptUri(uri) || IRIHelper.isMailtoUri(uri)) ? null : uri; } public Link getLink(String rel) { List<Link> self = getLinks(rel); Link link = null; if (self.size() > 0) link = self.get(0); return link; } public Link getSelfLink() { return getLink(Link.REL_SELF); } public Link getAlternateLink() { return getLink(Link.REL_ALTERNATE); } public IRI getLinkResolvedHref(String rel) { Link link = getLink(rel); return (link != null) ? link.getResolvedHref() : null; } public IRI getSelfLinkResolvedHref() { Link link = getSelfLink(); return (link != null) ? link.getResolvedHref() : null; } public IRI getAlternateLinkResolvedHref() { Link link = getAlternateLink(); return (link != null) ? link.getResolvedHref() : null; } public Text.Type getRightsType() { Text text = getRightsElement(); return (text != null) ? text.getTextType() : null; } public Text.Type getSubtitleType() { Text text = getSubtitleElement(); return (text != null) ? text.getTextType() : null; } public Text.Type getTitleType() { Text text = getTitleElement(); return (text != null) ? text.getTextType() : null; } public Collection getCollection() { Collection coll = getFirstChild(COLLECTION); if (coll == null) coll = getFirstChild(PRE_RFC_COLLECTION); return coll; } public <T extends Source> T setCollection(Collection collection) { complete(); if (collection != null) { _removeChildren(PRE_RFC_COLLECTION, true); _setChild(COLLECTION, (OMElement)collection); } else { _removeChildren(COLLECTION, false); } return (T)this; } public Link getAlternateLink(String type, String hreflang) { return selectLink(getLinks(Link.REL_ALTERNATE), type, hreflang); } public IRI getAlternateLinkResolvedHref(String type, String hreflang) { Link link = getAlternateLink(type, hreflang); return (link != null) ? link.getResolvedHref() : null; } public Feed getAsFeed() { FOMFeed feed = (FOMFeed)((FOMFactory)getOMFactory()).newFeed(); for (Iterator i = this.getChildElements(); i.hasNext();) { FOMElement child = (FOMElement)i.next(); if (!child.getQName().equals(ENTRY)) { feed.addChild((OMNode)child.clone()); } } try { if (this.getBaseUri() != null) { feed.setBaseUri(this.getBaseUri()); } } catch (Exception e) { } return feed; } }
7,453
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMGenerator.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.parser.stax; import javax.xml.namespace.QName; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Generator; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMXMLParserWrapper; public class FOMGenerator extends FOMElement implements Generator { private static final long serialVersionUID = -8441971633807437976L; protected FOMGenerator(String name, OMNamespace namespace, OMContainer parent, OMFactory factory) throws OMException { super(name, namespace, parent, factory); } protected FOMGenerator(QName qname, OMContainer parent, OMFactory factory) { super(qname, parent, factory); } protected FOMGenerator(String localName, OMContainer parent, OMFactory factory, OMXMLParserWrapper builder) { super(localName, parent, factory, builder); } protected FOMGenerator(OMContainer parent, OMFactory factory) throws OMException { super(GENERATOR, parent, factory); } public IRI getUri() { String value = getAttributeValue(AURI); return (value != null) ? new IRI(value) : null; } public IRI getResolvedUri() { return _resolve(getResolvedBaseUri(), getUri()); } public Generator setUri(String uri) { complete(); if (uri != null) setAttributeValue(AURI, (new IRI(uri)).toString()); else removeAttribute(AURI); return this; } public String getVersion() { return getAttributeValue(VERSION); } public Generator setVersion(String version) { complete(); if (version != null) setAttributeValue(VERSION, version); else removeAttribute(VERSION); return this; } }
7,454
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMWorkspace.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.parser.stax; import java.util.ArrayList; import java.util.List; import javax.activation.MimeType; import javax.xml.namespace.QName; import org.apache.abdera.model.Collection; import org.apache.abdera.model.Text; import org.apache.abdera.model.Workspace; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMXMLParserWrapper; @SuppressWarnings("deprecation") public class FOMWorkspace extends FOMExtensibleElement implements Workspace { private static final long serialVersionUID = -421749865550509424L; protected FOMWorkspace(String name, OMNamespace namespace, OMContainer parent, OMFactory factory) throws OMException { super(name, namespace, parent, factory); } protected FOMWorkspace(QName qname, OMContainer parent, OMFactory factory) throws OMException { super(qname, parent, factory); } protected FOMWorkspace(String localName, OMContainer parent, OMFactory factory, OMXMLParserWrapper builder) throws OMException { super(localName, parent, factory, builder); } protected FOMWorkspace(OMContainer parent, OMFactory factory) throws OMException { super(WORKSPACE, parent, factory); } public String getTitle() { Text title = this.getFirstChild(TITLE); return (title != null) ? title.getValue() : null; } private Text setTitle(String title, Text.Type type) { complete(); FOMFactory fomfactory = (FOMFactory)getOMFactory(); Text text = fomfactory.newText(PREFIXED_TITLE, type); text.setValue(title); this._setChild(PREFIXED_TITLE, (OMElement)text); return text; } public Text setTitle(String title) { return setTitle(title, Text.Type.TEXT); } public Text setTitleAsHtml(String title) { return setTitle(title, Text.Type.HTML); } public Text setTitleAsXHtml(String title) { return setTitle(title, Text.Type.XHTML); } public Text getTitleElement() { return getFirstChild(TITLE); } public List<Collection> getCollections() { List<Collection> list = _getChildrenAsSet(COLLECTION); if (list == null || list.size() == 0) list = _getChildrenAsSet(PRE_RFC_COLLECTION); return list; } public Collection getCollection(String title) { List<Collection> cols = getCollections(); Collection col = null; for (Collection c : cols) { if (c.getTitle().equals(title)) { col = c; break; } } return col; } public Workspace addCollection(Collection collection) { complete(); addChild((OMElement)collection); return this; } public Collection addCollection(String title, String href) { complete(); FOMFactory fomfactory = (FOMFactory)getOMFactory(); Collection collection = fomfactory.newCollection(this); collection.setTitle(title); collection.setHref(href); return collection; } public Collection addMultipartCollection(String title, String href) { complete(); FOMFactory fomfactory = (FOMFactory)getOMFactory(); Collection collection = fomfactory.newMultipartCollection(this); collection.setTitle(title); collection.setHref(href); return collection; } public Collection getCollectionThatAccepts(MimeType... types) { Collection collection = null; for (Collection coll : getCollections()) { int matches = 0; for (MimeType type : types) if (coll.accepts(type)) matches++; if (matches == types.length) { collection = coll; break; } } return collection; } public Collection getCollectionThatAccepts(String... types) { Collection collection = null; for (Collection coll : getCollections()) { int matches = 0; for (String type : types) if (coll.accepts(type)) matches++; if (matches == types.length) { collection = coll; break; } } return collection; } public List<Collection> getCollectionsThatAccept(MimeType... types) { List<Collection> collections = new ArrayList<Collection>(); for (Collection coll : getCollections()) { int matches = 0; for (MimeType type : types) if (coll.accepts(type)) matches++; if (matches == types.length) { collections.add(coll); } } return collections; } public List<Collection> getCollectionsThatAccept(String... types) { List<Collection> collections = new ArrayList<Collection>(); for (Collection coll : getCollections()) { int matches = 0; for (String type : types) if (coll.accepts(type)) matches++; if (matches == types.length) { collections.add(coll); } } return collections; } }
7,455
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMControl.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.parser.stax; import javax.xml.namespace.QName; import org.apache.abdera.model.Control; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMXMLParserWrapper; @SuppressWarnings("deprecation") public class FOMControl extends FOMExtensibleElement implements Control { private static final long serialVersionUID = -3816493378953555206L; protected FOMControl(String name, OMNamespace namespace, OMContainer parent, OMFactory factory) throws OMException { super(name, namespace, parent, factory); } protected FOMControl(QName qname, OMContainer parent, OMFactory factory) { super(qname, parent, factory); } protected FOMControl(String localName, OMContainer parent, OMFactory factory, OMXMLParserWrapper builder) { super(localName, parent, factory, builder); } protected FOMControl(OMContainer parent, OMFactory factory) throws OMException { super(CONTROL, parent, factory); } public boolean isDraft() { String value = _getElementValue(DRAFT); if (value == null) value = _getElementValue(PRE_RFC_DRAFT); return (value != null && YES.equalsIgnoreCase(value)); } public Control setDraft(boolean draft) { complete(); _removeChildren(PRE_RFC_DRAFT, true); _setElementValue(DRAFT, (draft) ? YES : NO); return this; } public Control unsetDraft() { complete(); _removeChildren(PRE_RFC_DRAFT, true); _removeChildren(DRAFT, true); return this; } }
7,456
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMElement.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.parser.stax; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import javax.activation.DataHandler; import javax.activation.MimeType; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import org.apache.abdera.factory.Factory; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.iri.IRIHelper; import org.apache.abdera.i18n.rfc4646.Lang; import org.apache.abdera.model.Base; import org.apache.abdera.model.Content; import org.apache.abdera.model.Div; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.model.ElementWrapper; import org.apache.abdera.model.Link; import org.apache.abdera.model.Text; import org.apache.abdera.parser.ParseException; import org.apache.abdera.parser.Parser; import org.apache.abdera.parser.ParserOptions; import org.apache.abdera.parser.stax.util.FOMElementIteratorWrapper; import org.apache.abdera.parser.stax.util.FOMList; import org.apache.abdera.util.Constants; import org.apache.abdera.util.MimeTypeHelper; import org.apache.abdera.writer.Writer; import org.apache.abdera.writer.WriterOptions; import org.apache.axiom.om.OMAttribute; import org.apache.axiom.om.OMComment; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMNode; import org.apache.axiom.om.OMOutputFormat; import org.apache.axiom.om.OMProcessingInstruction; import org.apache.axiom.om.OMText; import org.apache.axiom.om.OMXMLParserWrapper; import org.apache.axiom.om.impl.llom.OMElementImpl; @SuppressWarnings("unchecked") public class FOMElement extends OMElementImpl implements Element, OMElement, Constants { private static final long serialVersionUID = 8024257594220911953L; protected FOMElement(String name, OMNamespace namespace, OMContainer parent, OMFactory factory) throws OMException { super(parent, name, namespace, null, factory, true); } protected FOMElement(QName qname, OMContainer parent, OMFactory factory) throws OMException { super(parent, qname.getLocalPart(), getOrCreateNamespace(qname, parent, factory), null, factory, true); } protected FOMElement(String localName, OMContainer parent, OMFactory factory, OMXMLParserWrapper builder) { super(parent, localName, null, builder, factory, false); } private static OMNamespace getOrCreateNamespace(QName qname, OMContainer parent, OMFactory factory) { String namespace = qname.getNamespaceURI(); String prefix = qname.getPrefix(); if (parent != null && parent instanceof OMElement) { OMNamespace ns = ((OMElement)parent).findNamespace(namespace, prefix); if (ns != null) return ns; } return factory.createOMNamespace(qname.getNamespaceURI(), qname.getPrefix()); } protected Element getWrapped(Element internal) { if (internal == null) return null; FOMFactory factory = (FOMFactory)getFactory(); return factory.getElementWrapper(internal); } public <T extends Base> T getParentElement() { T parent = (T)super.getParent(); return (T)((parent instanceof Element) ? getWrapped((Element)parent) : parent); } protected void setParentDocument(Document parent) { ((OMContainer)parent).addChild(this); } public <T extends Element> T setParentElement(Element parent) { if (parent instanceof ElementWrapper) { parent = ((ElementWrapper)parent).getInternal(); } ((FOMElement)parent).addChild(this); return (T)this; } public <T extends Element> T getPreviousSibling() { OMNode el = this.getPreviousOMSibling(); while (el != null) { if (el instanceof Element) return (T)getWrapped((Element)el); else el = el.getPreviousOMSibling(); } return null; } public <T extends Element> T getNextSibling() { OMNode el = this.getNextOMSibling(); while (el != null) { if (el instanceof Element) return (T)getWrapped((Element)el); else el = el.getNextOMSibling(); } return null; } public <T extends Element> T getFirstChild() { return (T)getWrapped((Element)this.getFirstElement()); } public <T extends Element> T getPreviousSibling(QName qname) { Element el = getPreviousSibling(); while (el != null) { OMElement omel = (OMElement)el; if (omel.getQName().equals(qname)) return (T)getWrapped((Element)omel); el = el.getPreviousSibling(); } return null; } public <T extends Element> T getNextSibling(QName qname) { Element el = getNextSibling(); while (el != null) { OMElement omel = (OMElement)el; if (omel.getQName().equals(qname)) return (T)getWrapped((Element)omel); el = el.getNextSibling(); } return null; } public <T extends Element> T getFirstChild(QName qname) { return (T)getWrapped((Element)this.getFirstChildWithName(qname)); } public Lang getLanguageTag() { String lang = getLanguage(); return (lang != null) ? new Lang(lang) : null; } public String getLanguage() { String lang = getAttributeValue(LANG); Base parent = this.getParentElement(); return (lang != null) ? lang : (parent != null && parent instanceof Element) ? ((Element)parent).getLanguage() : (parent != null && parent instanceof Document) ? ((Document)parent).getLanguage() : null; } public <T extends Element> T setLanguage(String language) { setAttributeValue(LANG, language); return (T)this; } public IRI getBaseUri() { IRI uri = _getUriValue(getAttributeValue(BASE)); if (IRIHelper.isJavascriptUri(uri) || IRIHelper.isMailtoUri(uri)) { uri = null; } if (uri == null) { OMContainer parent = getParent(); if (parent instanceof Element) { uri = ((Element)parent).getBaseUri(); } else if (parent instanceof Document) { uri = ((Document)parent).getBaseUri(); } } return uri; } public IRI getResolvedBaseUri() { IRI baseUri = null; IRI uri = _getUriValue(getAttributeValue(BASE)); if (IRIHelper.isJavascriptUri(uri) || IRIHelper.isMailtoUri(uri)) { uri = null; } OMContainer parent = getParent(); if (parent instanceof Element) baseUri = ((Element)parent).getResolvedBaseUri(); else if (parent instanceof Document) baseUri = ((Document)parent).getBaseUri(); if (uri != null && baseUri != null) { uri = baseUri.resolve(uri); } else if (uri == null) { uri = baseUri; } return uri; } public <T extends Element> T setBaseUri(IRI base) { complete(); setAttributeValue(BASE, _getStringValue(base)); return (T)this; } public <T extends Element> T setBaseUri(String base) { setBaseUri((base != null) ? new IRI(base) : null); return (T)this; } public String getAttributeValue(QName qname) { OMAttribute attr = getAttribute(qname); String value = (attr != null) ? attr.getAttributeValue() : null; return getMustPreserveWhitespace() || value == null ? value : value.trim(); } public <T extends Element> T setAttributeValue(QName qname, String value) { OMAttribute attr = this.getAttribute(qname); if (attr != null && value != null) { attr.setAttributeValue(value); } else { if (value != null) { String uri = qname.getNamespaceURI(); String prefix = qname.getPrefix(); OMFactory factory = getOMFactory(); if (uri != null) { OMNamespace ns = findNamespace(uri, prefix); if (ns == null) ns = factory.createOMNamespace(uri, prefix); attr = factory.createOMAttribute(qname.getLocalPart(), ns, value); } else { attr = factory.createOMAttribute(qname.getLocalPart(), null, value); } if (attr != null) addAttribute(attr); } else if (attr != null) { removeAttribute(attr); } } return (T)this; } protected <E extends Element> List<E> _getChildrenAsSet(QName qname) { FOMFactory factory = (FOMFactory)getFactory(); return new FOMList(new FOMElementIteratorWrapper(factory, getChildrenWithName(qname))); } protected void _setChild(QName qname, OMElement element) { OMElement e = getFirstChildWithName(qname); if (e == null && element != null) { addChild(element); } else if (e != null && element != null) { e.insertSiblingBefore(element); e.discard(); } else if (e != null && element == null) { e.discard(); } } protected IRI _getUriValue(String v) { return (v != null) ? new IRI(v) : null; } protected String _getStringValue(IRI uri) { return (uri != null) ? uri.toString() : null; } protected IRI _resolve(IRI base, IRI value) { return base != null ? base.resolve(value) : value; } public void writeTo(OutputStream out, WriterOptions options) throws IOException { Writer writer = this.getFactory().getAbdera().getWriter(); writer.writeTo(this, out, options); } public void writeTo(java.io.Writer out, WriterOptions options) throws IOException { Writer writer = this.getFactory().getAbdera().getWriter(); writer.writeTo(this, out, options); } public void writeTo(Writer writer, OutputStream out) throws IOException { writer.writeTo(this, out); } public void writeTo(Writer writer, java.io.Writer out) throws IOException { writer.writeTo(this, out); } public void writeTo(Writer writer, OutputStream out, WriterOptions options) throws IOException { writer.writeTo(this, out, options); } public void writeTo(Writer writer, java.io.Writer out, WriterOptions options) throws IOException { writer.writeTo(this, out, options); } public void writeTo(OutputStream out) throws IOException { Document doc = getDocument(); String charset = doc != null ? doc.getCharset() : "UTF-8"; Writer writer = this.getFactory().getAbdera().getWriter(); writeTo(writer, new OutputStreamWriter(out, charset)); } public void writeTo(java.io.Writer writer) throws IOException { Writer out = getFactory().getAbdera().getWriter(); if (!(out instanceof FOMWriter)) { out.writeTo(this, writer); } else { try { OMOutputFormat outputFormat = new OMOutputFormat(); if (getDocument() != null && getDocument().getCharset() != null) outputFormat.setCharSetEncoding(getDocument().getCharset()); serialize(writer, outputFormat); } catch (XMLStreamException e) { throw new FOMException(e); } } } public <T extends Element> Document<T> getDocument() { Document<T> document = null; OMContainer parent = getParent(); if (parent != null) { if (parent instanceof Element) { document = ((Element)parent).getDocument(); } else if (parent instanceof Document) { document = (Document<T>)parent; } } return document; } public String getAttributeValue(String name) { return getAttributeValue(new QName(name)); } public <T extends Element> T setAttributeValue(String name, String value) { setAttributeValue(new QName(name), value); return (T)this; } protected void _setElementValue(QName qname, String value) { complete(); OMElement element = this.getFirstChildWithName(qname); if (element != null && value != null) { element.setText(value); } else if (element != null && value == null) { for (Iterator i = element.getChildren(); i.hasNext();) { OMNode node = (OMNode)i.next(); node.discard(); } } else if (element == null && value != null) { element = getOMFactory().createOMElement(qname, this); element.setText(value); this.addChild(element); } } protected String _getElementValue(QName qname) { String value = null; OMElement element = this.getFirstChildWithName(qname); if (element != null) value = element.getText(); return getMustPreserveWhitespace() || value == null ? value : value.trim(); } protected <T extends Text> T getTextElement(QName qname) { return (T)getFirstChildWithName(qname); } protected <T extends Text> void setTextElement(QName qname, T text, boolean many) { complete(); if (text != null) { _setChild(qname, (OMElement)text); } else _removeChildren(qname, false); } protected Text setTextText(QName qname, String value) { if (value == null) { setTextElement(qname, null, false); return null; } FOMFactory fomfactory = (FOMFactory)getOMFactory(); Text text = fomfactory.newText(qname, Text.Type.TEXT); text.setValue(value); setTextElement(qname, text, false); return text; } protected Text setHtmlText(QName qname, String value, IRI baseUri) { if (value == null) { setTextElement(qname, null, false); return null; } FOMFactory fomfactory = (FOMFactory)getOMFactory(); Text text = fomfactory.newText(qname, Text.Type.HTML); if (baseUri != null) text.setBaseUri(baseUri); text.setValue(value); setTextElement(qname, text, false); return text; } protected Text setXhtmlText(QName qname, String value, IRI baseUri) { if (value == null) { setTextElement(qname, null, false); return null; } FOMFactory fomfactory = (FOMFactory)getOMFactory(); Text text = fomfactory.newText(qname, Text.Type.XHTML); if (baseUri != null) text.setBaseUri(baseUri); text.setValue(value); setTextElement(qname, text, false); return text; } protected Text setXhtmlText(QName qname, Div value, IRI baseUri) { if (value == null) { setTextElement(qname, null, false); return null; } FOMFactory fomfactory = (FOMFactory)getOMFactory(); Text text = fomfactory.newText(qname, Text.Type.XHTML); if (baseUri != null) text.setBaseUri(baseUri); text.setValueElement(value); setTextElement(qname, text, false); return text; } public void setText(String text) { complete(); if (text != null) { OMNode child = this.getFirstOMChild(); while (child != null) { if (child.getType() == OMNode.TEXT_NODE) { child.detach(); } child = child.getNextOMSibling(); } getOMFactory().createOMText(this, text); } else _removeAllChildren(); // return (T)this; } public String getText() { StringBuilder buf = new StringBuilder(); Iterator i = getChildren(); while (i.hasNext()) { OMNode node = (OMNode)i.next(); if (node instanceof OMText) { buf.append(((OMText)node).getText()); } else { // for now, let's ignore other elements. eventually, we // should make this work like innerHTML in browsers... stripping // out all markup but leaving all text, even in child nodes } } String value = buf.toString(); return getMustPreserveWhitespace() || value == null ? value : value.trim(); } protected String getText(QName qname) { Text text = getTextElement(qname); return (text != null) ? text.getValue() : null; } public List<QName> getAttributes() { List<QName> list = new ArrayList<QName>(); for (Iterator i = getAllAttributes(); i.hasNext();) { OMAttribute attr = (OMAttribute)i.next(); list.add(attr.getQName()); } return Collections.unmodifiableList(list); } public List<QName> getExtensionAttributes() { List<QName> list = new ArrayList<QName>(); for (Iterator i = getAllAttributes(); i.hasNext();) { OMAttribute attr = (OMAttribute)i.next(); String namespace = (attr.getNamespace() != null) ? attr.getNamespace().getNamespaceURI() : ""; if (!namespace.equals(getNamespace().getNamespaceURI()) && !namespace.equals("")) list.add(attr.getQName()); } return Collections.unmodifiableList(list); } protected Element _parse(String value, IRI baseUri) throws ParseException, UnsupportedEncodingException { if (value == null) return null; FOMFactory fomfactory = (FOMFactory)getOMFactory(); Parser parser = fomfactory.newParser(); ParserOptions options = parser.getDefaultParserOptions(); options.setFactory(fomfactory); Document doc = parser.parse(new StringReader(value), (baseUri != null) ? baseUri.toString() : null, options); return doc.getRoot(); } public <T extends Element> T removeAttribute(QName qname) { OMAttribute attr = getAttribute(qname); if (attr != null) removeAttribute(attr); return (T)this; } public <T extends Element> T removeAttribute(String name) { OMAttribute attr = getAttribute(new QName(name)); if (attr != null) getAttribute(new QName(name)); return (T)this; } protected void _removeChildren(QName qname, boolean many) { complete(); if (many) { for (Iterator i = getChildrenWithName(qname); i.hasNext();) { OMElement element = (OMElement)i.next(); element.discard(); } } else { OMElement element = getFirstChildWithName(qname); if (element != null) element.discard(); } } protected void _removeAllChildren() { complete(); for (Iterator i = getChildren(); i.hasNext();) { OMNode node = (OMNode)i.next(); node.discard(); } } public Object clone() { OMElement el = _create(this); _copyElement(this, el); return el; } protected OMElement _copyElement(OMElement src, OMElement dest) { OMFactory factory = getOMFactory(); for (Iterator i = src.getAllAttributes(); i.hasNext();) { OMAttribute attr = (OMAttribute)i.next(); dest.addAttribute(attr); dest.addAttribute(factory.createOMAttribute(attr.getLocalName(), attr.getNamespace(), attr .getAttributeValue())); } for (Iterator i = src.getChildren(); i.hasNext();) { OMNode node = (OMNode)i.next(); if (node.getType() == OMNode.ELEMENT_NODE) { OMElement element = (OMElement)node; OMElement child = _create(element); if (child != null) { _copyElement(element, child); dest.addChild(child); } } else if (node.getType() == OMNode.CDATA_SECTION_NODE) { OMText text = (OMText)node; factory.createOMText(dest, text.getText(), OMNode.CDATA_SECTION_NODE); } else if (node.getType() == OMNode.TEXT_NODE) { OMText text = (OMText)node; factory.createOMText(dest, text.getText()); } else if (node.getType() == OMNode.COMMENT_NODE) { OMComment comment = (OMComment)node; factory.createOMComment(dest, comment.getValue()); } else if (node.getType() == OMNode.PI_NODE) { OMProcessingInstruction pi = (OMProcessingInstruction)node; factory.createOMProcessingInstruction(dest, pi.getTarget(), pi.getValue()); } else if (node.getType() == OMNode.SPACE_NODE) { OMText text = (OMText)node; factory.createOMText(dest, text.getText(), OMNode.SPACE_NODE); } else if (node.getType() == OMNode.ENTITY_REFERENCE_NODE) { OMText text = (OMText)node; factory.createOMText(dest, text.getText(), OMNode.ENTITY_REFERENCE_NODE); } } return dest; } protected OMElement _create(OMElement src) { OMElement el = null; FOMFactory fomfactory = (FOMFactory)getOMFactory(); Object obj = null; if (src instanceof Content) obj = ((Content)src).getContentType(); if (src instanceof Text) obj = ((Text)src).getTextType(); el = fomfactory.createElement(src.getQName(), (OMContainer)fomfactory.newDocument(), fomfactory, obj); return el; } public Factory getFactory() { return (Factory)this.getOMFactory(); } // This appears to no longer be necessary with Axiom 1.2 // // @Override // protected void internalSerialize( // XMLStreamWriter writer, // boolean bool) throws XMLStreamException { // if (this.getNamespace() != null) { // this.declareNamespace(this.getNamespace()); // } // Iterator i = this.getAllAttributes(); // while (i.hasNext()) { // OMAttribute attr = (OMAttribute) i.next(); // if (attr.getNamespace() != null) // this.declareNamespace(attr.getNamespace()); // } // super.internalSerialize(writer, bool); // } public <T extends Base> T addComment(String value) { getOMFactory().createOMComment(this, value); return (T)this; } public Locale getLocale() { String tag = getLanguage(); if (tag == null || tag.length() == 0) return null; String[] tokens = tag.split("-"); Locale locale = null; switch (tokens.length) { case 0: break; case 1: locale = new Locale(tokens[0]); break; case 2: locale = new Locale(tokens[0], tokens[1]); break; default: locale = new Locale(tokens[0], tokens[1], tokens[2]); break; } return locale; } protected Link selectLink(List<Link> links, String type, String hreflang) { for (Link link : links) { MimeType mt = link.getMimeType(); boolean typematch = MimeTypeHelper.isMatch((mt != null) ? mt.toString() : null, type); boolean langmatch = "*".equals(hreflang) || ((hreflang != null) ? hreflang.equals(link.getHrefLang()) : link.getHrefLang() == null); if (typematch && langmatch) return link; } return null; } public <T extends Element> T declareNS(String uri, String prefix) { if (!isDeclared(uri, prefix)) { super.declareNamespace(uri, prefix); } return (T)this; } protected boolean isDeclared(String ns, String prefix) { for (Iterator i = this.getAllDeclaredNamespaces(); i.hasNext();) { OMNamespace omn = (OMNamespace)i.next(); if (omn.getNamespaceURI().equals(ns) && (omn.getPrefix() != null && omn.getPrefix().equals(prefix))) return true; } Base parent = this.getParentElement(); if (parent != null && parent instanceof FOMElement) { return ((FOMElement)parent).isDeclared(ns, prefix); } else return false; } protected void declareIfNecessary(String ns, String prefix) { if (prefix != null && !prefix.equals("") && !isDeclared(ns, prefix)) { declareNS(ns, prefix); } } public Map<String, String> getNamespaces() { Map<String, String> namespaces = new HashMap<String, String>(); OMElement current = this; while (current != null) { Iterator i = current.getAllDeclaredNamespaces(); while (i.hasNext()) { OMNamespace ns = (OMNamespace)i.next(); String prefix = ns.getPrefix(); String uri = ns.getNamespaceURI(); if (!namespaces.containsKey(prefix)) namespaces.put(prefix, uri); } OMContainer parent = current.getParent(); current = (OMElement)((parent != null && parent instanceof OMElement) ? parent : null); } return Collections.unmodifiableMap(namespaces); } public <T extends Element> List<T> getElements() { return new FOMList<T>(new FOMElementIteratorWrapper((FOMFactory)getOMFactory(), getChildElements())); } public boolean getMustPreserveWhitespace() { OMAttribute attr = getAttribute(SPACE); String space = (attr != null) ? attr.getAttributeValue() : null; Base parent = this.getParentElement(); return space != null && space.equalsIgnoreCase("preserve") ? true : (parent != null && parent instanceof Element) ? ((Element)parent).getMustPreserveWhitespace() : (parent != null && parent instanceof Document) ? ((Document)parent).getMustPreserveWhitespace() : true; } public <T extends Element> T setMustPreserveWhitespace(boolean preserve) { if (preserve && !getMustPreserveWhitespace()) { setAttributeValue(SPACE, "preserve"); } else if (!preserve && getMustPreserveWhitespace()) { setAttributeValue(SPACE, "default"); } return (T)this; } public <T extends Element> T setText(DataHandler handler) { _removeAllChildren(); addChild(getOMFactory().createOMText(handler, true)); return (T)this; } public WriterOptions getDefaultWriterOptions() { return new FOMWriter().getDefaultWriterOptions(); } /** * Ensure that the underlying streams are fully parsed. We might eventually need to find a more efficient way of * doing this, but for now, calling toString() will ensure that this particular object is fully parsed and ready to * be modified. 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. */ public <T extends Base> T complete() { if (!isComplete() && builder != null) super.build(); return (T)this; } /** * Iterate over all child elements */ public Iterator<Element> iterator() { return getElements().iterator(); } public void writeTo(String writer, OutputStream out) throws IOException { writeTo(getFactory().getAbdera().getWriterFactory().getWriter(writer), out); } public void writeTo(String writer, java.io.Writer out) throws IOException { writeTo(getFactory().getAbdera().getWriterFactory().getWriter(writer), out); } public void writeTo(String writer, OutputStream out, WriterOptions options) throws IOException { writeTo(getFactory().getAbdera().getWriterFactory().getWriter(writer), out, options); } public void writeTo(String writer, java.io.Writer out, WriterOptions options) throws IOException { writeTo(getFactory().getAbdera().getWriterFactory().getWriter(writer), out, options); } public String toFormattedString() { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); writeTo("prettyxml", out); return new String(out.toByteArray(), "UTF-8"); } catch (Exception e) { return toString(); } } }
7,457
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMIRI.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.parser.stax; import javax.xml.namespace.QName; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Element; import org.apache.abdera.model.IRIElement; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMXMLParserWrapper; public class FOMIRI extends FOMElement implements IRIElement { private static final long serialVersionUID = -8434722753544181200L; protected FOMIRI(String name, OMNamespace namespace, OMContainer parent, OMFactory factory) throws OMException { super(name, namespace, parent, factory); } protected FOMIRI(QName qname, OMContainer parent, OMFactory factory) throws OMException { super(qname, parent, factory); } protected FOMIRI(String localName, OMContainer parent, OMFactory factory, OMXMLParserWrapper builder) throws OMException { super(localName, parent, factory, builder); } public IRI getValue() { return _getUriValue(getText()); } public IRIElement setValue(String iri) { complete(); if (iri != null) ((Element)this).setText((new IRI(iri)).toString()); else _removeAllChildren(); return this; } public IRI getResolvedValue() { return _resolve(getResolvedBaseUri(), getValue()); } public IRIElement setNormalizedValue(String uri) { if (uri != null) setValue(IRI.normalizeString(uri)); else setValue(null); return this; } }
7,458
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/StaxStreamWriter.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.parser.stax; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Stack; import javax.xml.namespace.NamespaceContext; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.apache.abdera.Abdera; import org.apache.abdera.parser.stax.util.FOMHelper; import org.apache.abdera.util.AbstractStreamWriter; import org.apache.abdera.util.Constants; import org.apache.abdera.writer.StreamWriter; import org.apache.axiom.om.util.StAXUtils; import org.apache.axiom.om.util.StAXWriterConfiguration; import org.apache.axiom.util.stax.dialect.StAXDialect; public class StaxStreamWriter extends AbstractStreamWriter { private static final StAXWriterConfiguration ABDERA_WRITER_CONFIGURATION = new StAXWriterConfiguration() { public XMLOutputFactory configure(XMLOutputFactory factory, StAXDialect dialect) { factory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, true); return factory; } // This is used in log statements inside Axiom @Override public String toString() { return "ABDERA"; } }; private static final String NAME = "default"; private XMLStreamWriter writer; private int depth = 0; private int textwritten = 0; public StaxStreamWriter(Abdera abdera) { super(abdera, NAME); } public StaxStreamWriter(Abdera abdera, Writer writer) { super(abdera, NAME); setWriter(writer); } public StaxStreamWriter(Abdera abdera, OutputStream out) { super(abdera, NAME); setOutputStream(out); } public StaxStreamWriter(Abdera abdera, OutputStream out, String charset) { super(abdera, NAME); setOutputStream(out, charset); } public StreamWriter setWriter(java.io.Writer writer) { try { this.writer = createXMLStreamWriter(writer); } catch (Exception e) { throw new RuntimeException(e); } return this; } private static XMLStreamWriter createXMLStreamWriter(Writer out) throws XMLStreamException { XMLOutputFactory outputFactory = StAXUtils.getXMLOutputFactory(ABDERA_WRITER_CONFIGURATION); XMLStreamWriter writer = outputFactory.createXMLStreamWriter(out); return writer; } public StreamWriter setOutputStream(java.io.OutputStream out) { try { this.writer = createXMLStreamWriter(out, "UTF-8"); } catch (Exception e) { throw new RuntimeException(e); } return this; } private static XMLStreamWriter createXMLStreamWriter(OutputStream out, String encoding) throws XMLStreamException { XMLOutputFactory outputFactory = StAXUtils.getXMLOutputFactory(ABDERA_WRITER_CONFIGURATION); XMLStreamWriter writer = outputFactory.createXMLStreamWriter(out, encoding); return writer; } public StreamWriter setOutputStream(java.io.OutputStream out, String charset) { try { this.writer = createXMLStreamWriter(out, charset); } catch (Exception e) { throw new RuntimeException(e); } return this; } public StreamWriter startDocument(String xmlversion, String charset) { try { writer.writeStartDocument(xmlversion, charset); } catch (XMLStreamException e) { throw new RuntimeException(e); } return this; } public StreamWriter startDocument(String xmlversion) { try { writer.writeStartDocument(xmlversion); } catch (XMLStreamException e) { throw new RuntimeException(e); } return this; } public StreamWriter endDocument() { try { writer.writeEndDocument(); writer.flush(); if (autoclose) writer.close(); } catch (XMLStreamException e) { throw new RuntimeException(e); } return this; } public StreamWriter endElement() { try { if (autoindent && textwritten == 0) { pop(); indent(); } else pop(); writer.writeEndElement(); if (autoflush) writer.flush(); } catch (XMLStreamException e) { throw new RuntimeException(e); } return this; } private void writeNamespace(String prefix, String namespace, boolean attr) throws XMLStreamException { prefix = prefix != null ? prefix : ""; if (!declared(prefix, namespace)) { if (attr && (namespace == null || "".equals(namespace))) return; if (prefix != null) writer.writeNamespace(prefix, namespace); else writer.writeDefaultNamespace(namespace); declare(prefix, namespace); if (autoflush) writer.flush(); } } private boolean needToWriteNamespace(String prefix, String namespace) { NamespaceContext nc = writer.getNamespaceContext(); String uri = nc.getNamespaceURI(prefix != null ? prefix : ""); return uri != null ? !uri.equals(namespace) : true; } public StreamWriter startElement(String name, String namespace, String prefix) { try { if (prefix == null || prefix.equals("")) prefix = writer.getPrefix(namespace); if (autoindent && textwritten == 0) indent(); push(); if (prefix != null && !prefix.equals("")) { writer.writeStartElement(prefix, name, namespace); if (needToWriteNamespace(prefix, namespace)) writeNamespace(prefix, namespace, false); } else if (namespace != null) { writer.writeStartElement("", name, namespace); if (needToWriteNamespace(prefix, namespace)) writeNamespace(prefix, namespace, false); } else { writer.writeStartElement("", name, ""); writer.writeDefaultNamespace(""); } if (autoflush) writer.flush(); } catch (XMLStreamException e) { throw new RuntimeException(e); } return this; } public StreamWriter writeElementText(String value) { try { textwritten++; writer.writeCharacters(value); if (autoflush) writer.flush(); } catch (XMLStreamException e) { throw new RuntimeException(e); } return this; } public StreamWriter writeComment(String value) { try { if (autoindent) indent(); writer.writeComment(value); if (autoflush) writer.flush(); } catch (XMLStreamException e) { throw new RuntimeException(e); } return this; } public StreamWriter writePI(String value) { try { if (autoindent) indent(); writer.writeProcessingInstruction(value); if (autoflush) writer.flush(); } catch (XMLStreamException e) { throw new RuntimeException(e); } return this; } public StreamWriter writePI(String value, String target) { try { if (autoindent) indent(); writer.writeProcessingInstruction(value, target); if (autoflush) writer.flush(); } catch (XMLStreamException e) { throw new RuntimeException(e); } return this; } public StreamWriter writeId() { return writeId(FOMHelper.generateUuid()); } public StreamWriter writeDefaultNamespace(String uri) { try { writer.writeDefaultNamespace(uri); } catch (XMLStreamException e) { throw new RuntimeException(e); } return this; } public StreamWriter writeNamespace(String prefix, String uri) { try { writer.writeNamespace(prefix, uri); } catch (XMLStreamException e) { throw new RuntimeException(e); } return this; } public StreamWriter writeAttribute(String name, String namespace, String prefix, String value) { if (value == null) return this; try { if (prefix != null) { if (!prefix.equals("xml")) writeNamespace(prefix, namespace, true); writer.writeAttribute(prefix, namespace, name, value); } else if (namespace != null) { if (!namespace.equals(Constants.XML_NS)) ; writeNamespace(prefix, namespace, true); writer.writeAttribute(namespace, name, value); } else { writer.writeAttribute(name, value); } if (autoflush) writer.flush(); } catch (XMLStreamException e) { throw new RuntimeException(e); } return this; } private final Stack<Map<String, String>> namespaces = new Stack<Map<String, String>>(); private void push() { namespaces.push(new HashMap<String, String>()); depth++; } private void pop() { depth--; if (textwritten > 0) textwritten--; if (!namespaces.isEmpty()) namespaces.pop(); } private void declare(String prefix, String namespace) { if (namespaces.isEmpty()) return; Map<String, String> frame = namespaces.peek(); frame.put(prefix, namespace); } private boolean declared(String prefix, String namespace) { for (int n = namespaces.size() - 1; n >= 0; n--) { Map<String, String> frame = namespaces.get(n); String chk = frame.get(prefix); if (chk == null && namespace == null) return true; if (chk == null && namespace != null) continue; if (chk != null && namespace == null) continue; if (chk.equals(namespace)) return true; } return false; } public StreamWriter flush() { try { writer.flush(); } catch (XMLStreamException e) { throw new RuntimeException(e); } return this; } public StreamWriter indent() { try { char[] indent = new char[depth * 2]; Arrays.fill(indent, ' '); writer.writeCharacters("\n"); writer.writeCharacters(indent, 0, indent.length); } catch (XMLStreamException e) { throw new RuntimeException(e); } return this; } public void close() throws IOException { try { writer.close(); } catch (XMLStreamException e) { throw new RuntimeException(e); } } public StreamWriter setPrefix(String prefix, String uri) { try { writer.setPrefix(prefix, uri); } catch (XMLStreamException e) { throw new RuntimeException(e); } return this; } }
7,459
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMAttribute.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.parser.stax; import javax.xml.namespace.QName; import org.apache.abdera.factory.Factory; import org.apache.abdera.model.Attribute; import org.apache.axiom.om.OMAttribute; public class FOMAttribute implements Attribute { private final OMAttribute attr; protected FOMAttribute(OMAttribute attr) { this.attr = attr; } public QName getQName() { return attr.getQName(); } public String getText() { return attr.getAttributeValue(); } public Attribute setText(String text) { attr.setAttributeValue(text); return this; } public Factory getFactory() { return (Factory)attr.getOMFactory(); } @Override public int hashCode() { final int PRIME = 31; int result = 1; result = PRIME * result + ((attr == null) ? 0 : attr.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 FOMAttribute other = (FOMAttribute)obj; if (attr == null) { if (other.attr != null) return false; } else if (!attr.equals(other.attr)) return false; return true; } }
7,460
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMProcessingInstruction.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.parser.stax; import org.apache.abdera.factory.Factory; import org.apache.abdera.model.Base; import org.apache.abdera.model.Element; import org.apache.abdera.model.ProcessingInstruction; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.impl.llom.OMProcessingInstructionImpl; @SuppressWarnings("unchecked") public class FOMProcessingInstruction extends OMProcessingInstructionImpl implements ProcessingInstruction { public FOMProcessingInstruction(OMContainer parent, String target, String value, OMFactory factory, boolean fromBuilder) { super(parent, target, value, factory, fromBuilder); } public <T extends Base> T getParentElement() { T parent = (T)super.getParent(); return (T)((parent instanceof Element) ? getWrapped((Element)parent) : parent); } protected Element getWrapped(Element internal) { if (internal == null) return null; FOMFactory factory = (FOMFactory)getFactory(); return factory.getElementWrapper(internal); } public Factory getFactory() { return (Factory)this.getOMFactory(); } public String getText() { return getValue(); } public <T extends ProcessingInstruction> T setText(String text) { setValue(text); return (T)this; } public String toString() { java.io.CharArrayWriter w = new java.io.CharArrayWriter(); try { super.serialize(w); } catch (Exception e) { } return w.toString(); } public void setTarget(String target) { super.setTarget(target); } }
7,461
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMEntry.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.parser.stax; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Date; import java.util.List; import javax.activation.DataHandler; import javax.activation.MimeType; import javax.xml.namespace.QName; import org.apache.abdera.model.AtomDate; import org.apache.abdera.model.Categories; import org.apache.abdera.model.Category; 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.IRIElement; import org.apache.abdera.model.Link; import org.apache.abdera.model.Person; import org.apache.abdera.model.Source; import org.apache.abdera.model.Text; import org.apache.abdera.model.Content.Type; import org.apache.abdera.parser.stax.util.FOMHelper; import org.apache.abdera.util.Constants; import org.apache.abdera.util.MimeTypeHelper; import org.apache.abdera.i18n.text.io.InputStreamDataSource; import org.apache.abdera.i18n.iri.IRI; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMXMLParserWrapper; @SuppressWarnings( {"unchecked", "deprecation"}) public class FOMEntry extends FOMExtensibleElement implements Entry { private static final long serialVersionUID = 1L; public FOMEntry() { super(Constants.ENTRY, new FOMDocument<Entry>(), new FOMFactory()); } protected FOMEntry(String name, OMNamespace namespace, OMContainer parent, OMFactory factory) throws OMException { super(name, namespace, parent, factory); } protected FOMEntry(QName qname, OMContainer parent, OMFactory factory) { super(qname, parent, factory); } protected FOMEntry(String localName, OMContainer parent, OMFactory factory, OMXMLParserWrapper builder) { super(localName, parent, factory, builder); } protected FOMEntry(OMContainer parent, OMFactory factory) throws OMException { super(ENTRY, parent, factory); } public Person getAuthor() { return (Person)getFirstChildWithName(AUTHOR); } public List<Person> getAuthors() { return _getChildrenAsSet(AUTHOR); } public Entry addAuthor(Person person) { complete(); addChild((OMElement)person); return this; } public Person addAuthor(String name) { complete(); FOMFactory fomfactory = (FOMFactory)this.getOMFactory(); Person person = fomfactory.newAuthor(this); person.setName(name); return person; } public Person addAuthor(String name, String email, String uri) { complete(); FOMFactory fomfactory = (FOMFactory)this.getOMFactory(); Person person = fomfactory.newAuthor(this); person.setName(name); person.setEmail(email); person.setUri(uri); return person; } public List<Category> getCategories() { return _getChildrenAsSet(CATEGORY); } public List<Category> getCategories(String scheme) { return FOMHelper.getCategories(this, scheme); } public Entry addCategory(Category category) { complete(); Element el = category.getParentElement(); if (el != null && el instanceof Categories) { Categories cats = category.getParentElement(); category = (Category)category.clone(); try { if (category.getScheme() == null && cats.getScheme() != null) category.setScheme(cats.getScheme().toString()); } catch (Exception e) { // Do nothing, shouldn't happen } } addChild((OMElement)category); return this; } public Category addCategory(String term) { complete(); FOMFactory factory = (FOMFactory)this.getOMFactory(); Category category = factory.newCategory(this); category.setTerm(term); return category; } public Category addCategory(String scheme, String term, String label) { complete(); FOMFactory factory = (FOMFactory)this.getOMFactory(); Category category = factory.newCategory(this); category.setTerm(term); category.setScheme(scheme); category.setLabel(label); return category; } public Content getContentElement() { return (Content)getFirstChildWithName(CONTENT); } public Entry setContentElement(Content content) { complete(); if (content != null) { _setChild(CONTENT, (OMElement)content); } else { _removeChildren(CONTENT, false); } return this; } /** * Sets the content for this entry as @type="text" */ public Content setContent(String value) { complete(); FOMFactory factory = (FOMFactory)this.getOMFactory(); Content content = factory.newContent(); content.setValue(value); setContentElement(content); return content; } public Content setContentAsHtml(String value) { return setContent(value, Content.Type.HTML); } public Content setContentAsXhtml(String value) { return setContent(value, Content.Type.XHTML); } /** * Sets the content for this entry */ public Content setContent(String value, Content.Type type) { FOMFactory factory = (FOMFactory)this.getOMFactory(); Content content = factory.newContent(type); content.setValue(value); setContentElement(content); return content; } /** * Sets the content for this entry */ public Content setContent(Element value) { FOMFactory factory = (FOMFactory)this.getOMFactory(); Content content = factory.newContent(); content.setValueElement(value); setContentElement(content); return content; } /** * Sets the content for this entry * * @throws MimeTypeParseException */ public Content setContent(Element element, String mediaType) { try { if (MimeTypeHelper.isText(mediaType)) throw new IllegalArgumentException(); FOMFactory factory = (FOMFactory)this.getOMFactory(); Content content = factory.newContent(new MimeType(mediaType)); content.setValueElement(element); setContentElement(content); return content; } catch (javax.activation.MimeTypeParseException e) { throw new org.apache.abdera.util.MimeTypeParseException(e); } } /** * Sets the content for this entry * * @throws MimeTypeParseException */ public Content setContent(DataHandler dataHandler) { return setContent(dataHandler, dataHandler.getContentType()); } /** * Sets the content for this entry * * @throws MimeTypeParseException */ public Content setContent(DataHandler dataHandler, String mediatype) { if (MimeTypeHelper.isText(mediatype)) { try { return setContent(dataHandler.getInputStream(), mediatype); } catch (IOException e) { throw new RuntimeException(e); } } else { FOMFactory factory = (FOMFactory)this.getOMFactory(); Content content = factory.newContent(Content.Type.MEDIA); content.setDataHandler(dataHandler); if (mediatype != null) content.setMimeType(mediatype); setContentElement(content); return content; } } /** * Sets the content for this entry */ public Content setContent(InputStream in) { InputStreamDataSource ds = new InputStreamDataSource(in); DataHandler dh = new DataHandler(ds); Content content = setContent(dh); return content; } /** * Sets the content for this entry */ public Content setContent(InputStream in, String mediatype) { if (MimeTypeHelper.isText(mediatype)) { try { StringBuilder buf = new StringBuilder(); String charset = MimeTypeHelper.getCharset(mediatype); Document doc = this.getDocument(); charset = charset != null ? charset : doc != null ? doc.getCharset() : null; charset = charset != null ? charset : "UTF-8"; InputStreamReader isr = new InputStreamReader(in, charset); char[] data = new char[500]; int r = -1; while ((r = isr.read(data)) != -1) { buf.append(data, 0, r); } return setContent(buf.toString(), mediatype); } catch (IOException e) { throw new RuntimeException(e); } } else { InputStreamDataSource ds = new InputStreamDataSource(in, mediatype); DataHandler dh = new DataHandler(ds); return setContent(dh, mediatype); } } /** * Sets the content for this entry * * @throws MimeTypeParseException */ public Content setContent(String value, String mediatype) { try { FOMFactory factory = (FOMFactory)this.getOMFactory(); Content content = factory.newContent(new MimeType(mediatype)); content.setValue(value); content.setMimeType(mediatype); setContentElement(content); return content; } catch (javax.activation.MimeTypeParseException e) { throw new org.apache.abdera.util.MimeTypeParseException(e); } } /** * Sets the content for this entry * * @throws MimeTypeParseException * @throws IRISyntaxException */ public Content setContent(IRI uri, String mediatype) { try { FOMFactory factory = (FOMFactory)this.getOMFactory(); Content content = factory.newContent(new MimeType(mediatype)); content.setSrc(uri.toString()); setContentElement(content); return content; } catch (javax.activation.MimeTypeParseException e) { throw new org.apache.abdera.util.MimeTypeParseException(e); } } public List<Person> getContributors() { return _getChildrenAsSet(CONTRIBUTOR); } public Entry addContributor(Person person) { complete(); addChild((OMElement)person); return this; } public Person addContributor(String name) { complete(); FOMFactory fomfactory = (FOMFactory)this.getOMFactory(); Person person = fomfactory.newContributor(this); person.setName(name); return person; } public Person addContributor(String name, String email, String uri) { complete(); FOMFactory fomfactory = (FOMFactory)this.getOMFactory(); Person person = fomfactory.newContributor(this); person.setName(name); person.setEmail(email); person.setUri(uri); return person; } public IRIElement getIdElement() { return (IRIElement)getFirstChildWithName(ID); } public Entry setIdElement(IRIElement id) { complete(); if (id != null) _setChild(ID, (OMElement)id); else _removeChildren(ID, false); return this; } public IRI getId() { IRIElement id = getIdElement(); return (id != null) ? id.getValue() : null; } public IRIElement setId(String value) { return setId(value, false); } public IRIElement newId() { return setId(this.getFactory().newUuidUri(), false); } public IRIElement setId(String value, boolean normalize) { complete(); if (value == null) { _removeChildren(ID, false); return null; } IRIElement id = getIdElement(); if (id != null) { if (normalize) id.setNormalizedValue(value); else id.setValue(value); return id; } else { FOMFactory fomfactory = (FOMFactory)getOMFactory(); IRIElement iri = fomfactory.newID(this); iri.setValue((normalize) ? IRI.normalizeString(value) : value); return iri; } } public List<Link> getLinks() { return _getChildrenAsSet(LINK); } public List<Link> getLinks(String rel) { return FOMHelper.getLinks(this, rel); } public List<Link> getLinks(String... rels) { return FOMHelper.getLinks(this, rels); } public Entry addLink(Link link) { complete(); addChild((OMElement)link); return this; } public Link addLink(String href) { complete(); return addLink(href, null); } public Link addLink(String href, String rel) { complete(); FOMFactory fomfactory = (FOMFactory)getOMFactory(); Link link = fomfactory.newLink(this); link.setHref(href); if (rel != null) link.setRel(rel); return link; } public Link addLink(String href, String rel, String type, String title, String hreflang, long length) { complete(); FOMFactory fomfactory = (FOMFactory)getOMFactory(); Link link = fomfactory.newLink(this); link.setHref(href); link.setRel(rel); link.setMimeType(type); link.setTitle(title); link.setHrefLang(hreflang); link.setLength(length); return link; } public DateTime getPublishedElement() { return (DateTime)getFirstChildWithName(PUBLISHED); } public Entry setPublishedElement(DateTime dateTime) { complete(); if (dateTime != null) _setChild(PUBLISHED, (OMElement)dateTime); else _removeChildren(PUBLISHED, false); return this; } public Date getPublished() { DateTime dte = getPublishedElement(); return (dte != null) ? dte.getDate() : null; } private DateTime setPublished(AtomDate value) { complete(); if (value == null) { _removeChildren(PUBLISHED, false); return null; } DateTime dte = getPublishedElement(); if (dte != null) { dte.setValue(value); return dte; } else { FOMFactory fomfactory = (FOMFactory)getOMFactory(); DateTime dt = fomfactory.newPublished(this); dt.setValue(value); return dt; } } public DateTime setPublished(Date value) { return setPublished((value != null) ? AtomDate.valueOf(value) : null); } public DateTime setPublished(String value) { return setPublished((value != null) ? AtomDate.valueOf(value) : null); } public Text getRightsElement() { return getTextElement(RIGHTS); } public Entry setRightsElement(Text text) { complete(); setTextElement(RIGHTS, text, false); return this; } public Text setRights(String value) { complete(); FOMFactory factory = (FOMFactory)this.getOMFactory(); Text text = factory.newRights(); text.setValue(value); setRightsElement(text); return text; } public Text setRightsAsHtml(String value) { return setRights(value, Text.Type.HTML); } public Text setRightsAsXhtml(String value) { return setRights(value, Text.Type.XHTML); } public Text setRights(String value, Text.Type type) { FOMFactory factory = (FOMFactory)this.getOMFactory(); Text text = factory.newRights(type); text.setValue(value); setRightsElement(text); return text; } public Text setRights(Div value) { FOMFactory factory = (FOMFactory)this.getOMFactory(); Text text = factory.newRights(Text.Type.XHTML); text.setValueElement(value); setRightsElement(text); return text; } public String getRights() { return getText(RIGHTS); } public Source getSource() { return (Source)getFirstChildWithName(SOURCE); } public Entry setSource(Source source) { complete(); if (source != null) { if (source instanceof Feed) source = ((Feed)source).getAsSource(); _setChild(SOURCE, (OMElement)source); } else { _removeChildren(SOURCE, false); } return this; } public Text getSummaryElement() { return getTextElement(SUMMARY); } public Entry setSummaryElement(Text text) { complete(); setTextElement(SUMMARY, text, false); return this; } public Text setSummary(String value) { complete(); FOMFactory factory = (FOMFactory)this.getOMFactory(); Text text = factory.newSummary(); text.setValue(value); setSummaryElement(text); return text; } public Text setSummaryAsHtml(String value) { return setSummary(value, Text.Type.HTML); } public Text setSummaryAsXhtml(String value) { return setSummary(value, Text.Type.XHTML); } public Text setSummary(String value, Text.Type type) { FOMFactory factory = (FOMFactory)this.getOMFactory(); Text text = factory.newSummary(type); text.setValue(value); setSummaryElement(text); return text; } public Text setSummary(Div value) { FOMFactory factory = (FOMFactory)this.getOMFactory(); Text text = factory.newSummary(Text.Type.XHTML); text.setValueElement(value); setSummaryElement(text); return text; } public String getSummary() { return getText(SUMMARY); } public Text getTitleElement() { return getTextElement(TITLE); } public Entry setTitleElement(Text title) { complete(); setTextElement(TITLE, title, false); return this; } public Text setTitle(String value) { complete(); FOMFactory factory = (FOMFactory)this.getOMFactory(); Text text = factory.newTitle(); text.setValue(value); setTitleElement(text); return text; } public Text setTitleAsHtml(String value) { return setTitle(value, Text.Type.HTML); } public Text setTitleAsXhtml(String value) { return setTitle(value, Text.Type.XHTML); } public Text setTitle(String value, Text.Type type) { FOMFactory factory = (FOMFactory)this.getOMFactory(); Text text = factory.newTitle(type); text.setValue(value); setTitleElement(text); return text; } public Text setTitle(Div value) { FOMFactory factory = (FOMFactory)this.getOMFactory(); Text text = factory.newTitle(Text.Type.XHTML); text.setValueElement(value); setTitleElement(text); return text; } public String getTitle() { return getText(TITLE); } public DateTime getUpdatedElement() { return (DateTime)getFirstChildWithName(UPDATED); } public Entry setUpdatedElement(DateTime updated) { complete(); if (updated != null) _setChild(UPDATED, (OMElement)updated); else _removeChildren(UPDATED, false); return this; } public Date getUpdated() { DateTime dte = getUpdatedElement(); return (dte != null) ? dte.getDate() : null; } private DateTime setUpdated(AtomDate value) { complete(); if (value == null) { _removeChildren(UPDATED, false); return null; } DateTime dte = getUpdatedElement(); if (dte != null) { dte.setValue(value); return dte; } else { FOMFactory fomfactory = (FOMFactory)getOMFactory(); DateTime dt = fomfactory.newUpdated(this); dt.setValue(value); return dt; } } public DateTime setUpdated(Date value) { return setUpdated((value != null) ? AtomDate.valueOf(value) : null); } public DateTime setUpdated(String value) { return setUpdated((value != null) ? AtomDate.valueOf(value) : null); } public DateTime getEditedElement() { DateTime dt = (DateTime)getFirstChildWithName(EDITED); if (dt == null) dt = (DateTime)getFirstChildWithName(PRE_RFC_EDITED); return dt; } public void setEditedElement(DateTime updated) { complete(); declareNamespace(APP_NS, "app"); _removeChildren(PRE_RFC_EDITED, false); if (updated != null) _setChild(EDITED, (OMElement)updated); else _removeChildren(EDITED, false); } public Date getEdited() { DateTime dte = getEditedElement(); return (dte != null) ? dte.getDate() : null; } private DateTime setEdited(AtomDate value) { complete(); declareNamespace(APP_NS, "app"); if (value == null) { _removeChildren(PRE_RFC_EDITED, false); _removeChildren(EDITED, false); return null; } DateTime dte = getEditedElement(); if (dte != null) { dte.setValue(value); return dte; } else { FOMFactory fomfactory = (FOMFactory)getOMFactory(); DateTime dt = fomfactory.newEdited(this); dt.setValue(value); return dt; } } public DateTime setEdited(Date value) { return setEdited((value != null) ? AtomDate.valueOf(value) : null); } public DateTime setEdited(String value) { return setUpdated((value != null) ? AtomDate.valueOf(value) : null); } public Control getControl(boolean create) { Control control = getControl(); if (control == null && create) { control = getFactory().newControl(); setControl(control); } return control; } public Control getControl() { Control control = (Control)getFirstChildWithName(CONTROL); if (control == null) control = (Control)getFirstChildWithName(PRE_RFC_CONTROL); return control; } public Entry setControl(Control control) { complete(); _removeChildren(PRE_RFC_CONTROL, true); if (control != null) _setChild(CONTROL, (OMElement)control); else _removeChildren(CONTROL, false); return this; } public Link getLink(String rel) { List<Link> links = getLinks(rel); Link link = null; if (links.size() > 0) link = links.get(0); return link; } public Link getAlternateLink() { return getLink(Link.REL_ALTERNATE); } public Link getEnclosureLink() { return getLink(Link.REL_ENCLOSURE); } public Link getEditLink() { return getLink(Link.REL_EDIT); } public Link getSelfLink() { return getLink(Link.REL_SELF); } public Link getEditMediaLink() { return getLink(Link.REL_EDIT_MEDIA); } public IRI getLinkResolvedHref(String rel) { Link link = getLink(rel); return (link != null) ? link.getResolvedHref() : null; } public IRI getAlternateLinkResolvedHref() { Link link = getAlternateLink(); return (link != null) ? link.getResolvedHref() : null; } public IRI getEnclosureLinkResolvedHref() { Link link = getEnclosureLink(); return (link != null) ? link.getResolvedHref() : null; } public IRI getEditLinkResolvedHref() { Link link = getEditLink(); return (link != null) ? link.getResolvedHref() : null; } public IRI getEditMediaLinkResolvedHref() { Link link = getEditMediaLink(); return (link != null) ? link.getResolvedHref() : null; } public IRI getSelfLinkResolvedHref() { Link link = getSelfLink(); return (link != null) ? link.getResolvedHref() : null; } public String getContent() { Content content = getContentElement(); return (content != null) ? content.getValue() : null; } public InputStream getContentStream() throws IOException { Content content = getContentElement(); DataHandler dh = content.getDataHandler(); return dh.getInputStream(); } public IRI getContentSrc() { Content content = getContentElement(); return (content != null) ? content.getResolvedSrc() : null; } public Type getContentType() { Content content = getContentElement(); return (content != null) ? content.getContentType() : null; } public Text.Type getRightsType() { Text text = getRightsElement(); return (text != null) ? text.getTextType() : null; } public Text.Type getSummaryType() { Text text = getSummaryElement(); return (text != null) ? text.getTextType() : null; } public Text.Type getTitleType() { Text text = getTitleElement(); return (text != null) ? text.getTextType() : null; } public MimeType getContentMimeType() { Content content = getContentElement(); return (content != null) ? content.getMimeType() : null; } public Link getAlternateLink(String type, String hreflang) { return selectLink(getLinks(Link.REL_ALTERNATE), type, hreflang); } public IRI getAlternateLinkResolvedHref(String type, String hreflang) { Link link = getAlternateLink(type, hreflang); return (link != null) ? link.getResolvedHref() : null; } public Link getEditMediaLink(String type, String hreflang) { return selectLink(getLinks(Link.REL_EDIT_MEDIA), type, hreflang); } public IRI getEditMediaLinkResolvedHref(String type, String hreflang) { Link link = getEditMediaLink(type, hreflang); return (link != null) ? link.getResolvedHref() : null; } public Entry setDraft(boolean draft) { complete(); Control control = getControl(); if (control == null && draft) { control = ((FOMFactory)getOMFactory()).newControl(this); } if (control != null) control.setDraft(draft); return this; } /** * Returns true if this entry is a draft */ public boolean isDraft() { Control control = getControl(); return (control != null) ? control.isDraft() : false; } public Control addControl() { complete(); Control control = getControl(); if (control == null) { control = ((FOMFactory)getOMFactory()).newControl(this); } return control; } }
7,462
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMWriterOptions.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.parser.stax; import org.apache.abdera.util.AbstractWriterOptions; public class FOMWriterOptions extends AbstractWriterOptions { }
7,463
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMStAXFilter.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.parser.stax; import java.util.Map; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.apache.abdera.filter.ParseFilter; import org.apache.abdera.parser.ParseException; import org.apache.abdera.parser.ParserOptions; import org.apache.axiom.om.OMContainer; import org.apache.axiom.util.stax.wrapper.XMLStreamReaderWrapper; /** * {@link XMLStreamReader} wrapper that implements the various filters and transformations that can * be configured using {@link ParserFilter}. * <p> * The design of Apache Axiom is based on the assumption that no filtering or transformation is done * inside the builder. Among other things, this assumption ensures that * {@link OMContainer#getXMLStreamReaderWithoutCaching()} produces consistent results. One may argue * that for Abdera this is less important because * {@link OMContainer#getXMLStreamReaderWithoutCaching()} is not exposed by the Abdera API. However, * attempting to do filtering and transformation in the builder results in strong coupling between * Abdera and Axiom because {@link FOMBuilder} would depend on the internal implementation details * of the Axiom builder. To avoid this we do all filtering/transformation upfront. */ class FOMStAXFilter extends XMLStreamReaderWrapper { private final ParserOptions parserOptions; private boolean ignoreWhitespace = false; private boolean ignoreComments = false; private boolean ignorePI = false; private int depthInSkipElement; private int altEventType; private QName altQName; private String altText; private int[] attributeMap; private int attributeCount; FOMStAXFilter(XMLStreamReader parent, ParserOptions parserOptions) { super(parent); this.parserOptions = parserOptions; if (parserOptions != null) { ParseFilter parseFilter = parserOptions.getParseFilter(); if (parseFilter != null) { ignoreWhitespace = parseFilter.getIgnoreWhitespace(); ignoreComments = parseFilter.getIgnoreComments(); ignorePI = parseFilter.getIgnoreProcessingInstructions(); attributeMap = new int[8]; } } resetEvent(); } private void resetEvent() { altEventType = -1; altQName = null; altText = null; attributeCount = -1; } private void translateQName() { if (parserOptions.isQNameAliasMappingEnabled()) { Map<QName,QName> map = parserOptions.getQNameAliasMap(); if (map != null) { altQName = map.get(super.getName()); } } } private void mapAttributes() { attributeCount = 0; int orgAttCount = super.getAttributeCount(); if (orgAttCount > 0) { QName elementQName = super.getName(); ParseFilter filter = parserOptions.getParseFilter(); for (int i=0; i<orgAttCount; i++) { if (filter.acceptable(elementQName, super.getAttributeName(i))) { if (attributeCount == attributeMap.length) { int[] newAttributeMap = new int[attributeMap.length*2]; System.arraycopy(attributeMap, 0, newAttributeMap, 0, attributeMap.length); attributeMap = newAttributeMap; } attributeMap[attributeCount++] = i; } } } } @Override public int next() throws XMLStreamException { resetEvent(); while (true) { int eventType = super.next(); if (depthInSkipElement > 0) { switch (eventType) { case START_ELEMENT: depthInSkipElement++; break; case END_ELEMENT: depthInSkipElement--; break; } } else { switch (eventType) { case DTD: // Current StAX cursor model implementations inconsistently handle DTDs. // Woodstox, for instance, does not provide a means of getting to the complete // doctype declaration (which is actually valid according to the spec, which // is broken). The StAX reference impl returns the complete doctype declaration // despite the fact that doing so is apparently against the spec. We can get // to the complete declaration in Woodstox if we want to use their proprietary // extension APIs. It's unclear how other Stax impls handle this. So.. for now, // we're just going to ignore the DTD. The DTD will still be processed as far // as entities are concerned, but we will not be able to reserialize the parsed // document with the DTD. Since very few folks actually use DTD's in feeds // right now (and we should likely be encouraging folks not to do so), this // shouldn't be that big of a problem continue; case START_ELEMENT: ParseFilter filter = parserOptions.getParseFilter(); if (filter != null && !filter.acceptable(super.getName())) { depthInSkipElement = 1; continue; } translateQName(); if (attributeMap != null) { mapAttributes(); } break; case END_ELEMENT: translateQName(); break; case SPACE: if (ignoreWhitespace) { continue; } break; case COMMENT: if (ignoreComments) { continue; } break; case PROCESSING_INSTRUCTION: if (ignorePI) { continue; } break; case CHARACTERS: case CDATA: if (ignoreWhitespace && isWhiteSpace()) { continue; } break; case ENTITY_REFERENCE: String val = parserOptions.resolveEntity(getLocalName()); if (val == null) { throw new ParseException("Unresolved undeclared entity: " + getLocalName()); } else { altEventType = CHARACTERS; altText = val; } break; } return altEventType != -1 ? altEventType : eventType; } } } @Override public int getEventType() { return altEventType != -1 ? altEventType : super.getEventType(); } @Override public String getText() { return altText != null ? altText : super.getText(); } @Override public String getNamespaceURI() { return altQName != null ? altQName.getNamespaceURI() : super.getNamespaceURI(); } @Override public String getLocalName() { return altQName != null ? altQName.getLocalPart() : super.getLocalName(); } @Override public QName getName() { return altQName != null ? altQName : super.getName(); } @Override public int getAttributeCount() { return attributeCount != -1 ? attributeCount : super.getAttributeCount(); } @Override public String getAttributeNamespace(int index) { return attributeCount != -1 ? super.getAttributeNamespace(attributeMap[index]) : super.getAttributeNamespace(index); } @Override public String getAttributeLocalName(int index) { return attributeCount != -1 ? super.getAttributeLocalName(attributeMap[index]) : super.getAttributeLocalName(index); } @Override public String getAttributePrefix(int index) { return attributeCount != -1 ? super.getAttributePrefix(attributeMap[index]) : super.getAttributePrefix(index); } @Override public QName getAttributeName(int index) { return attributeCount != -1 ? super.getAttributeName(attributeMap[index]) : super.getAttributeName(index); } @Override public String getAttributeType(int index) { return attributeCount != -1 ? super.getAttributeType(attributeMap[index]) : super.getAttributeType(index); } @Override public String getAttributeValue(int index) { return attributeCount != -1 ? super.getAttributeValue(attributeMap[index]) : super.getAttributeValue(index); } }
7,464
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMException.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.parser.stax; import org.apache.abdera.parser.ParseException; public class FOMException extends ParseException { private static final long serialVersionUID = 7631230122836829559L; public FOMException() { super(); } public FOMException(String message) { super(message); } public FOMException(String message, Throwable cause) { super(message, cause); } public FOMException(Throwable cause) { super(cause); } }
7,465
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMContent.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.parser.stax; import javax.activation.DataHandler; import javax.activation.MimeType; import javax.activation.URLDataSource; import javax.xml.namespace.QName; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.text.Localizer; import org.apache.abdera.model.Content; import org.apache.abdera.model.Div; import org.apache.abdera.model.Element; import org.apache.abdera.model.ElementWrapper; import org.apache.abdera.util.Constants; import org.apache.axiom.attachments.ByteArrayDataSource; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMNode; import org.apache.axiom.om.OMXMLParserWrapper; import org.apache.axiom.util.base64.Base64Utils; @SuppressWarnings("unchecked") public class FOMContent extends FOMExtensibleElement implements Content { private static final long serialVersionUID = -5499917654824498563L; protected Type type = Type.TEXT; protected FOMContent(String name, OMNamespace namespace, Type type, OMContainer parent, OMFactory factory) throws OMException { super(name, namespace, parent, factory); init(type); } protected FOMContent(QName qname, Type type, OMContainer parent, OMFactory factory) { super(qname, parent, factory); init(type); } protected FOMContent(String localName, Type type, OMContainer parent, OMFactory factory, OMXMLParserWrapper builder) { super(localName, parent, factory, builder); init(type); } protected FOMContent(Type type, OMContainer parent, OMFactory factory) throws OMException { super(CONTENT, parent, factory); init(type); } private void init(Type type) { this.type = type; if (Type.TEXT.equals(type)) setAttributeValue(TYPE, "text"); else if (Type.HTML.equals(type)) setAttributeValue(TYPE, "html"); else if (Type.XHTML.equals(type)) setAttributeValue(TYPE, "xhtml"); else if (Type.XML.equals(type)) setAttributeValue(TYPE, "application/xml"); else { removeAttribute(TYPE); } } public final Type getContentType() { return type; } public Content setContentType(Type type) { complete(); init(type); return this; } public <T extends Element> T getValueElement() { FOMFactory factory = (FOMFactory)getFactory(); return (T)factory.getElementWrapper((Element)this.getFirstElement()); } public <T extends Element> Content setValueElement(T value) { complete(); if (value != null) { if (this.getFirstElement() != null) this.getFirstElement().discard(); MimeType mtype = this.getMimeType(); if (mtype == null) { String mt = getFactory().getMimeType(value); if (mt != null) { setMimeType(mt); mtype = getMimeType(); } } if (value instanceof Div && !type.equals(Content.Type.XML)) init(Content.Type.XHTML); else { if (mtype == null) { init(Content.Type.XML); } } OMElement el = (OMElement)(value instanceof ElementWrapper ? ((ElementWrapper)value).getInternal() : value); removeChildren(); addChild(el); } else { _removeAllChildren(); } return this; } public MimeType getMimeType() { MimeType type = null; String mimeType = getAttributeValue(TYPE); if (mimeType != null) { try { type = new MimeType(mimeType); } catch (Exception e) { } } return type; } public Content setMimeType(String type) { complete(); try { if (type != null) setAttributeValue(TYPE, (new MimeType(type)).toString()); else removeAttribute(TYPE); } catch (javax.activation.MimeTypeParseException e) { throw new org.apache.abdera.util.MimeTypeParseException(e); } return this; } public IRI getSrc() { return _getUriValue(getAttributeValue(SRC)); } public IRI getResolvedSrc() { return _resolve(getResolvedBaseUri(), getSrc()); } public Content setSrc(String src) { complete(); if (src != null) setAttributeValue(SRC, (new IRI(src)).toString()); else removeAttribute(SRC); return this; } public DataHandler getDataHandler() { if (!Type.MEDIA.equals(type)) throw new UnsupportedOperationException(Localizer.get("DATA.HANDLER.NOT.SUPPORTED")); MimeType type = getMimeType(); java.net.URL src = null; try { src = getSrc().toURL(); } catch (Exception e) { } DataHandler dh = null; if (src == null) { dh = new DataHandler(new ByteArrayDataSource( Base64Utils.decode(getText()), (type != null) ? type.toString() : null)); } else { dh = new DataHandler(new URLDataSource(src)); } return dh; } public Content setDataHandler(DataHandler dataHandler) { complete(); if (!Type.MEDIA.equals(type)) throw new IllegalArgumentException(); if (dataHandler.getContentType() != null) { try { setMimeType(dataHandler.getContentType()); } catch (Exception e) { } } _removeAllChildren(); addChild(getOMFactory().createOMText(dataHandler, true)); return this; } public String getValue() { String val = null; if (Type.TEXT.equals(type)) { val = getText(); } else if (Type.HTML.equals(type)) { val = getText(); } else if (Type.XHTML.equals(type)) { FOMDiv div = (FOMDiv)this.getFirstChildWithName(Constants.DIV); if (div != null) val = div.getInternalValue(); } else if (Type.XML.equals(type)) { OMElement el = this.getFirstElement(); if (el != null) val = el.toString(); } else if (Type.MEDIA.equals(type)) { val = getText(); } return val; } public <T extends Element> T setText(Content.Type type, String value) { complete(); init(type); if (value != null) { OMNode child = this.getFirstOMChild(); while (child != null) { if (child.getType() == OMNode.TEXT_NODE) { child.detach(); } child = child.getNextOMSibling(); } getOMFactory().createOMText(this, value); } else _removeAllChildren(); return (T)this; } public <T extends Element> T setText(String value) { return (T)setText(Content.Type.TEXT, value); } public Content setValue(String value) { complete(); if (value != null) removeAttribute(SRC); if (value != null) { if (Type.TEXT.equals(type)) { _removeAllChildren(); setText(type, value); } else if (Type.HTML.equals(type)) { _removeAllChildren(); setText(type, value); } else if (Type.XHTML.equals(type)) { IRI baseUri = null; Element element = null; value = "<div xmlns=\"" + XHTML_NS + "\">" + value + "</div>"; try { baseUri = getResolvedBaseUri(); element = _parse(value, baseUri); } catch (Exception e) { } if (element != null && element instanceof Div) setValueElement((Div)element); } else if (Type.XML.equals(type)) { IRI baseUri = null; Element element = null; try { baseUri = getResolvedBaseUri(); element = _parse(value, baseUri); } catch (Exception e) { } if (element != null) setValueElement(element); try { if (getMimeType() == null) setMimeType("application/xml"); } catch (Exception e) { } } else if (Type.MEDIA.equals(type)) { _removeAllChildren(); setText(type, value); try { if (getMimeType() == null) setMimeType("text/plain"); } catch (Exception e) { } } } else { _removeAllChildren(); } return this; } public String getWrappedValue() { if (Type.XHTML.equals(type)) { return this.getFirstChildWithName(Constants.DIV).toString(); } else { return getText(); } } public Content setWrappedValue(String wrappedValue) { complete(); if (Type.XHTML.equals(type)) { IRI baseUri = null; Element element = null; try { baseUri = getResolvedBaseUri(); element = _parse(wrappedValue, baseUri); } catch (Exception e) { } if (element != null && element instanceof Div) setValueElement((Div)element); } else { ((Element)this).setText(wrappedValue); } return this; } @Override public IRI getBaseUri() { if (Type.XHTML.equals(type)) { Element el = getValueElement(); if (el != null) { if (el.getAttributeValue(BASE) != null) { if (getAttributeValue(BASE) != null) return super.getBaseUri().resolve(el.getAttributeValue(BASE)); else return _getUriValue(el.getAttributeValue(BASE)); } } } return super.getBaseUri(); } @Override public IRI getResolvedBaseUri() { if (Type.XHTML.equals(type)) { Element el = getValueElement(); if (el != null) { if (el.getAttributeValue(BASE) != null) { return super.getResolvedBaseUri().resolve(el.getAttributeValue(BASE)); } } } return super.getResolvedBaseUri(); } @Override public String getLanguage() { if (Type.XHTML.equals(type)) { Element el = getValueElement(); if (el.getAttributeValue(LANG) != null) return el.getAttributeValue(LANG); } return super.getLanguage(); } @Override public Object clone() { FOMContent content = (FOMContent)super.clone(); content.type = this.type; return content; } }
7,466
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMCategory.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.parser.stax; import javax.xml.namespace.QName; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Category; import org.apache.abdera.model.Element; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMXMLParserWrapper; public class FOMCategory extends FOMExtensibleElement implements Category { private static final long serialVersionUID = -4313042828936786803L; protected FOMCategory(String name, OMNamespace namespace, OMContainer parent, OMFactory factory) throws OMException { super(name, namespace, parent, factory); } protected FOMCategory(QName qname, OMContainer parent, OMFactory factory) { super(qname, parent, factory); } protected FOMCategory(String localName, OMContainer parent, OMFactory factory, OMXMLParserWrapper builder) { super(localName, parent, factory, builder); } protected FOMCategory(OMContainer parent, OMFactory factory) { super(CATEGORY, parent, factory); } public String getTerm() { return getAttributeValue(TERM); } public Category setTerm(String term) { complete(); if (term != null) setAttributeValue(TERM, term); else removeAttribute(TERM); return this; } public IRI getScheme() { String value = getAttributeValue(SCHEME); return (value != null) ? new IRI(value) : null; } public Category setScheme(String scheme) { complete(); if (scheme != null) setAttributeValue(SCHEME, new IRI(scheme).toString()); else removeAttribute(SCHEME); return this; } public String getLabel() { return getAttributeValue(LABEL); } public Category setLabel(String label) { complete(); if (label != null) setAttributeValue(LABEL, label); else removeAttribute(LABEL); return this; } public String getValue() { return getText(); } public void setValue(String value) { complete(); if (value != null) ((Element)this).setText(value); else _removeAllChildren(); } }
7,467
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMDocument.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.parser.stax; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.activation.MimeType; import javax.xml.stream.XMLStreamException; import org.apache.abdera.factory.Factory; 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.ElementWrapper; import org.apache.abdera.util.EntityTag; import org.apache.abdera.util.XmlUtil; import org.apache.abdera.util.XmlUtil.XMLVersion; import org.apache.abdera.writer.Writer; import org.apache.abdera.writer.WriterOptions; import org.apache.axiom.om.OMComment; import org.apache.axiom.om.OMDocType; import org.apache.axiom.om.OMDocument; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNode; import org.apache.axiom.om.OMOutputFormat; import org.apache.axiom.om.OMProcessingInstruction; import org.apache.axiom.om.OMXMLParserWrapper; import org.apache.axiom.om.impl.llom.OMDocumentImpl; @SuppressWarnings("unchecked") public class FOMDocument<T extends Element> extends OMDocumentImpl implements Document<T> { private static final long serialVersionUID = -3255339511063344662L; protected IRI base = null; protected MimeType contentType = null; protected Date lastModified = null; protected EntityTag etag = null; protected String language = null; protected String slug = null; protected boolean preserve = true; public FOMDocument() { super(new FOMFactory()); } protected FOMDocument(OMFactory factory) { super(factory); } protected FOMDocument(OMXMLParserWrapper parserWrapper, OMFactory factory) { super(parserWrapper, factory); } protected FOMDocument(OMXMLParserWrapper parserWrapper) { super(parserWrapper, new FOMFactory()); } public T getRoot() { FOMFactory factory = (FOMFactory)getFactory(); return (T)factory.getElementWrapper((T)this.getOMDocumentElement()); } public Document<T> setRoot(T root) { if (root instanceof OMElement) { this.setOMDocumentElement((OMElement)root); } else if (root instanceof ElementWrapper) { this.setOMDocumentElement((OMElement)((ElementWrapper)root).getInternal()); } return this; } public IRI getBaseUri() { return base; } public Document<T> setBaseUri(String base) { this.base = new IRI(base); return this; } public void writeTo(OutputStream out, WriterOptions options) throws IOException { Writer writer = this.getFactory().getAbdera().getWriter(); writer.writeTo(this, out, options); } public void writeTo(java.io.Writer out, WriterOptions options) throws IOException { Writer writer = this.getFactory().getAbdera().getWriter(); writer.writeTo(this, out, options); } public void writeTo(Writer writer, OutputStream out) throws IOException { writer.writeTo(this, out); } public void writeTo(Writer writer, java.io.Writer out) throws IOException { writer.writeTo(this, out); } public void writeTo(Writer writer, OutputStream out, WriterOptions options) throws IOException { writer.writeTo(this, out, options); } public void writeTo(Writer writer, java.io.Writer out, WriterOptions options) throws IOException { writer.writeTo(this, out, options); } public void writeTo(OutputStream out) throws IOException { String charset = getCharset(); if (charset == null) charset = "UTF-8"; Writer writer = getFactory().getAbdera().getWriter(); writeTo(writer, new OutputStreamWriter(out, charset)); } public void writeTo(java.io.Writer writer) throws IOException { Writer out = getFactory().getAbdera().getWriter(); if (!(out instanceof FOMWriter)) { out.writeTo(this, writer); } else { try { OMOutputFormat outputFormat = new OMOutputFormat(); if (this.getCharsetEncoding() != null) outputFormat.setCharSetEncoding(this.getCharsetEncoding()); this.serialize(writer, outputFormat); } catch (XMLStreamException e) { throw new FOMException(e); } } } public MimeType getContentType() { return contentType; } public Document<T> setContentType(String contentType) { try { this.contentType = new MimeType(contentType); if (this.contentType.getParameter("charset") != null) setCharset(this.contentType.getParameter("charset")); } catch (javax.activation.MimeTypeParseException e) { throw new org.apache.abdera.util.MimeTypeParseException(e); } return this; } public Date getLastModified() { return this.lastModified; } public Document<T> setLastModified(Date lastModified) { this.lastModified = lastModified; return this; } public Object clone() { Document<T> doc = ((FOMFactory)getOMFactory()).newDocument(); OMDocument omdoc = (OMDocument)doc; for (Iterator i = getChildren(); i.hasNext();) { OMNode node = (OMNode)i.next(); switch (node.getType()) { case OMNode.COMMENT_NODE: OMComment comment = (OMComment)node; getOMFactory().createOMComment(omdoc, comment.getValue()); break; // TODO: Decide what to do with this code; it will no longer work in Axiom 1.2.14 (because of AXIOM-437). // On the other hand, since we filter out DTDs, this code is never triggered. // case OMNode.DTD_NODE: // OMDocType doctype = (OMDocType)node; // factory.createOMDocType(omdoc, doctype.getValue()); // break; case OMNode.ELEMENT_NODE: Element el = (Element)node; omdoc.addChild((OMNode)el.clone()); break; case OMNode.PI_NODE: OMProcessingInstruction pi = (OMProcessingInstruction)node; getOMFactory().createOMProcessingInstruction(omdoc, pi.getTarget(), pi.getValue()); break; } } return doc; } public String getCharset() { String enc = this.getXMLEncoding(); return enc == null ? "utf-8" : enc; } public Document<T> setCharset(String charset) { this.setXMLEncoding(charset); this.setCharsetEncoding(charset); return this; } public Factory getFactory() { return (Factory)this.getOMFactory(); } public String[] getProcessingInstruction(String target) { List<String> values = new ArrayList<String>(); for (Iterator i = getChildren(); i.hasNext();) { OMNode node = (OMNode)i.next(); if (node.getType() == OMNode.PI_NODE) { OMProcessingInstruction pi = (OMProcessingInstruction)node; if (pi.getTarget().equalsIgnoreCase(target)) values.add(pi.getValue()); } } return values.toArray(new String[values.size()]); } public Document<T> addProcessingInstruction(String target, String value) { OMProcessingInstruction pi = this.getOMFactory().createOMProcessingInstruction(null, target, value); if (this.getOMDocumentElement() != null) { this.getOMDocumentElement().insertSiblingBefore(pi); } else { this.addChild(pi); } return this; } public Document<T> addStylesheet(String href, String media) { if (media == null) { addProcessingInstruction("xml-stylesheet", "href=\"" + href + "\""); } else { addProcessingInstruction("xml-stylesheet", "href=\"" + href + "\" media=\"" + media + "\""); } return this; } public <X extends Base> X addComment(String value) { OMComment comment = this.getOMFactory().createOMComment(null, value); if (this.getOMDocumentElement() != null) { this.getOMDocumentElement().insertSiblingBefore(comment); } else { this.addChild(comment); } return (X)this; } public EntityTag getEntityTag() { return etag; } public Document<T> setEntityTag(EntityTag tag) { this.etag = tag; return this; } public Document<T> setEntityTag(String tag) { this.etag = new EntityTag(tag); return this; } public String getLanguage() { return language; } public Lang getLanguageTag() { String lang = getLanguage(); return (lang != null) ? new Lang(lang) : null; } public Document<T> setLanguage(String lang) { this.language = lang; return this; } public String getSlug() { return slug; } public Document<T> setSlug(String slug) { this.slug = slug; return this; } public boolean getMustPreserveWhitespace() { return preserve; } public Document<T> setMustPreserveWhitespace(boolean preserve) { this.preserve = preserve; return this; } public XMLVersion getXmlVersion() { return XmlUtil.getVersion(super.getXMLVersion()); } public WriterOptions getDefaultWriterOptions() { return new FOMWriter().getDefaultWriterOptions(); } /** * Ensure that the underlying streams are fully parsed. We might eventually need to find a more efficient way of * doing this, but for now, calling toString() will ensure that this particular object is fully parsed and ready to * be modified. */ public <X extends Base> X complete() { if (!isComplete() && getRoot() != null) getRoot().complete(); return (X)this; } public void writeTo(String writer, OutputStream out) throws IOException { writeTo(getFactory().getAbdera().getWriterFactory().getWriter(writer), out); } public void writeTo(String writer, java.io.Writer out) throws IOException { writeTo(getFactory().getAbdera().getWriterFactory().getWriter(writer), out); } public void writeTo(String writer, OutputStream out, WriterOptions options) throws IOException { writeTo(getFactory().getAbdera().getWriterFactory().getWriter(writer), out, options); } public void writeTo(String writer, java.io.Writer out, WriterOptions options) throws IOException { writeTo(getFactory().getAbdera().getWriterFactory().getWriter(writer), out, options); } public String toFormattedString() { try { ByteArrayOutputStream out = new ByteArrayOutputStream(); writeTo("prettyxml", out); return new String(out.toByteArray(), "UTF-8"); } catch (Exception e) { return toString(); } } }
7,468
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMParser.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.parser.stax; import java.io.InputStream; import java.io.Reader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import org.apache.abdera.Abdera; import org.apache.abdera.factory.Factory; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.i18n.text.Localizer; import org.apache.abdera.i18n.text.io.CompressionUtil; 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.parser.stax.util.FOMSniffingInputStream; import org.apache.abdera.parser.stax.util.FOMXmlRestrictedCharReader; import org.apache.abdera.util.AbstractParser; import org.apache.axiom.om.OMDocument; import org.apache.axiom.om.util.StAXParserConfiguration; import org.apache.axiom.om.util.StAXUtils; import org.apache.axiom.util.stax.dialect.StAXDialect; public class FOMParser extends AbstractParser implements Parser { private static final StAXParserConfiguration ABDERA_PARSER_CONFIGURATION = new StAXParserConfiguration() { public XMLInputFactory configure(XMLInputFactory factory, StAXDialect dialect) { factory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.FALSE); return factory; } // This is used in log statements inside Axiom @Override public String toString() { return "ABDERA"; } }; public FOMParser() { super(); } public FOMParser(Abdera abdera) { super(abdera); } private FOMFactory getFomFactory(ParserOptions options) { FOMFactory factory = (options != null && options.getFactory() != null) ? (FOMFactory)options.getFactory() : null; if (factory == null) { Factory f = getFactory(); factory = (f instanceof FOMFactory) ? (FOMFactory)f : new FOMFactory(); } return factory; } private <T extends Element> Document<T> getDocument(FOMBuilder builder, IRI base, ParserOptions options) throws ParseException { Document<T> document = builder.getFomDocument(); try { if (base != null) document.setBaseUri(base.toString()); if (options != null && options.getCharset() != null) ((OMDocument)document).setCharsetEncoding(options.getCharset()); if (options != null) document.setMustPreserveWhitespace(options.getMustPreserveWhitespace()); } catch (Exception e) { if (!(e instanceof ParseException)) e = new ParseException(e); throw (ParseException)e; } return document; } public <T extends Element> Document<T> parse(InputStream in, String base, ParserOptions options) throws ParseException { if (in == null) throw new IllegalArgumentException(Localizer.get("INPUTSTREAM.NOT.NULL")); try { if (options == null) options = getDefaultParserOptions(); if (options.getCompressionCodecs() != null) { in = CompressionUtil.getDecodingInputStream(in, options.getCompressionCodecs()); } String charset = options.getCharset(); if (charset == null && options.getAutodetectCharset()) { FOMSniffingInputStream sin = (in instanceof FOMSniffingInputStream) ? (FOMSniffingInputStream)in : new FOMSniffingInputStream(in); charset = sin.getEncoding(); if (charset != null) options.setCharset(charset); in = sin; } if (options.getFilterRestrictedCharacters()) { Reader rdr = (charset == null) ? new FOMXmlRestrictedCharReader(in, options.getFilterRestrictedCharacterReplacement()) : new FOMXmlRestrictedCharReader(in, charset, options.getFilterRestrictedCharacterReplacement()); return parse(StAXUtils.createXMLStreamReader(rdr), base, options); } else { XMLStreamReader xmlreader = (charset == null) ? createXMLStreamReader(in) : createXMLStreamReader(in, charset); return parse(xmlreader, base, options); } } catch (Exception e) { if (!(e instanceof ParseException)) e = new ParseException(e); throw (ParseException)e; } } public <T extends Element> Document<T> parse(Reader in, String base, ParserOptions options) throws ParseException { if (in == null) throw new IllegalArgumentException(Localizer.get("READER.NOT.NULL")); try { if (options == null) options = getDefaultParserOptions(); if (options.getFilterRestrictedCharacters() && !(in instanceof FOMXmlRestrictedCharReader)) { in = new FOMXmlRestrictedCharReader(in, options.getFilterRestrictedCharacterReplacement()); } // return parse(StAXUtils.createXMLStreamReader(in), base, options); return parse(createXMLStreamReader(in), base, options); } catch (Exception e) { if (!(e instanceof ParseException)) e = new ParseException(e); throw (ParseException)e; } } public static XMLStreamReader createXMLStreamReader(InputStream in, String encoding) throws XMLStreamException { return StAXUtils.createXMLStreamReader(ABDERA_PARSER_CONFIGURATION, in, encoding); } public static XMLStreamReader createXMLStreamReader(InputStream in) throws XMLStreamException { return StAXUtils.createXMLStreamReader(ABDERA_PARSER_CONFIGURATION, in); } private XMLStreamReader createXMLStreamReader(Reader in) throws XMLStreamException { return StAXUtils.createXMLStreamReader(ABDERA_PARSER_CONFIGURATION, in); } public <T extends Element> Document<T> parse(XMLStreamReader reader, String base, ParserOptions options) throws ParseException { try { FOMBuilder builder = new FOMBuilder(getFomFactory(options), reader, options); return getDocument(builder, base != null ? new IRI(base) : null, options); } catch (Exception e) { if (!(e instanceof ParseException)) e = new ParseException(e); throw (ParseException)e; } } @Override protected ParserOptions initDefaultParserOptions() { return new FOMParserOptions(getFactory()); } }
7,469
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMDiv.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.parser.stax; import java.io.StringWriter; import java.util.Iterator; import javax.xml.namespace.QName; import javax.xml.stream.XMLOutputFactory; import javax.xml.stream.XMLStreamWriter; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Div; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMNode; import org.apache.axiom.om.OMXMLParserWrapper; public class FOMDiv extends FOMExtensibleElement implements Div { private static final long serialVersionUID = -2319449893405850433L; protected FOMDiv(String name, OMNamespace namespace, OMContainer parent, OMFactory factory) throws OMException { super(name, namespace, parent, factory); } protected FOMDiv(QName qname, OMContainer parent, OMFactory factory) throws OMException { super(qname, parent, factory); } protected FOMDiv(String localName, OMContainer parent, OMFactory factory, OMXMLParserWrapper builder) throws OMException { super(localName, parent, factory, builder); } public String[] getXhtmlClass() { String _class = getAttributeValue(CLASS); String[] classes = null; if (_class != null) { classes = _class.split(" "); } return classes; } public String getId() { return getAttributeValue(AID); } public String getTitle() { return getAttributeValue(ATITLE); } public Div setId(String id) { complete(); if (id != null) setAttributeValue(AID, id); else removeAttribute(AID); return this; } public Div setTitle(String title) { complete(); if (title != null) setAttributeValue(ATITLE, title); else removeAttribute(ATITLE); return this; } public Div setXhtmlClass(String[] classes) { complete(); if (classes != null) { StringBuilder val = new StringBuilder(); for (String s : classes) { if (s.length() > 0) val.append(" "); val.append(s); } setAttributeValue(CLASS, val.toString()); } else removeAttribute(CLASS); return this; } public String getValue() { return getInternalValue(); } public void setValue(String value) { complete(); _removeAllChildren(); if (value != null) { IRI baseUri = null; value = "<div xmlns=\"" + XHTML_NS + "\">" + value + "</div>"; OMElement element = null; try { baseUri = getResolvedBaseUri(); element = (OMElement)_parse(value, baseUri); } catch (Exception e) { } for (Iterator<?> i = element.getChildren(); i.hasNext();) { this.addChild((OMNode)i.next()); } } } protected String getInternalValue() { try { StringWriter out = new StringWriter(); XMLStreamWriter writer = XMLOutputFactory.newInstance().createXMLStreamWriter(out); writer.writeStartElement(""); for (Iterator<?> nodes = this.getChildren(); nodes.hasNext();) { OMNode node = (OMNode)nodes.next(); node.serialize(writer); } writer.writeEndElement(); return out.getBuffer().toString().substring(2); } catch (Exception e) { } return ""; } }
7,470
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMXPath.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.parser.stax; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.namespace.QName; import org.apache.abdera.Abdera; import org.apache.abdera.model.Base; import org.apache.abdera.model.ElementWrapper; import org.apache.abdera.parser.stax.util.ResolveFunction; import org.apache.abdera.util.AbstractXPath; import org.apache.abdera.xpath.XPathException; import org.apache.axiom.om.OMAttribute; import org.apache.axiom.om.xpath.DocumentNavigator; import org.jaxen.BaseXPath; import org.jaxen.Function; import org.jaxen.FunctionContext; import org.jaxen.JaxenException; import org.jaxen.SimpleFunctionContext; import org.jaxen.SimpleVariableContext; import org.jaxen.VariableContext; import org.jaxen.XPath; @SuppressWarnings("unchecked") public class FOMXPath extends AbstractXPath { private final Map<QName, Function> functions; private final Map<QName, Object> variables; public FOMXPath(Abdera abdera) { this(null, null, null); } protected FOMXPath(Map<String, String> defaultNamespaces) { this(defaultNamespaces, null, null); } protected FOMXPath(Map<String, String> defaultNamespaces, Map<QName, Function> defaultFunctions, Map<QName, Object> defaultVariables) { super(defaultNamespaces); functions = (defaultFunctions != null) ? defaultFunctions : initDefaultFunctions(); variables = (defaultVariables != null) ? defaultVariables : initDefaultVariables(); } protected Map<String, String> initDefaultNamespaces() { Map<String, String> namespaces = super.initDefaultNamespaces(); namespaces.put("abdera", "http://abdera.apache.org"); return namespaces; } private Map<QName, Function> initDefaultFunctions() { Map<QName, Function> functions = new HashMap<QName, Function>(); functions.put(ResolveFunction.QNAME, new ResolveFunction()); return functions; } private Map<QName, Object> initDefaultVariables() { Map<QName, Object> variables = new HashMap<QName, Object>(); return variables; } public static XPath getXPath(String path) throws JaxenException { return getXPath(path, null); } private static FunctionContext getFunctionContext(Map<QName, Function> functions, SimpleFunctionContext context) { if (context == null) context = new SimpleFunctionContext(); for (QName qname : functions.keySet()) { Function function = functions.get(qname); context.registerFunction(qname.getNamespaceURI(), qname.getLocalPart(), function); } return context; } private static VariableContext getVariableContext(Map<QName, Object> variables, SimpleVariableContext context) { if (context == null) context = new SimpleVariableContext(); for (QName qname : variables.keySet()) { Object value = variables.get(qname); context.setVariableValue(qname.getNamespaceURI(), qname.getLocalPart(), value); } return context; } public static XPath getXPath(String path, Map<String, String> namespaces, Map<QName, Function> functions, Map<QName, Object> variables) throws JaxenException { DocumentNavigator nav = new DocumentNavigator(); XPath contextpath = new BaseXPath(path, nav); if (namespaces != null) { for (Map.Entry<String, String> entry : namespaces.entrySet()) { contextpath.addNamespace(entry.getKey(), entry.getValue()); } } if (functions != null) { contextpath.setFunctionContext(getFunctionContext(functions, (SimpleFunctionContext)contextpath .getFunctionContext())); } if (variables != null) contextpath.setVariableContext(getVariableContext(variables, (SimpleVariableContext)contextpath .getVariableContext())); return contextpath; } public static XPath getXPath(String path, Map<String, String> namespaces) throws JaxenException { return getXPath(path, namespaces, null, null); } public List selectNodes(String path, Base base, Map<String, String> namespaces, Map<QName, Function> functions, Map<QName, Object> variables) throws XPathException { try { base = getElementWrapped(base); List nodes = new ArrayList(); XPath xpath = getXPath(path, namespaces, functions, variables); List results = xpath.selectNodes(base); for (Object obj : results) { if (obj instanceof OMAttribute) { nodes.add(new FOMAttribute((OMAttribute)obj)); } else { nodes.add(obj); } } return nodes; } catch (JaxenException e) { throw new XPathException(e); } } public List selectNodes(String path, Base base, Map<String, String> namespaces) throws XPathException { return selectNodes(path, base, namespaces, functions, variables); } public Object selectSingleNode(String path, Base base, Map<String, String> namespaces, Map<QName, Function> functions, Map<QName, Object> variables) throws XPathException { try { base = getElementWrapped(base); XPath xpath = getXPath(path, namespaces, functions, variables); Object obj = xpath.selectSingleNode(base); if (obj instanceof OMAttribute) obj = new FOMAttribute((OMAttribute)obj); return obj; } catch (JaxenException e) { throw new XPathException(e); } } public Object selectSingleNode(String path, Base base, Map<String, String> namespaces) throws XPathException { return selectSingleNode(path, base, namespaces, functions, variables); } public Object evaluate(String path, Base base, Map<String, String> namespaces, Map<QName, Function> functions, Map<QName, Object> variables) throws XPathException { try { base = getElementWrapped(base); XPath xpath = getXPath(path, namespaces, functions, variables); return xpath.evaluate(base); } catch (JaxenException e) { throw new XPathException(e); } } public Object evaluate(String path, Base base, Map<String, String> namespaces) throws XPathException { return evaluate(path, base, namespaces, functions, variables); } public String valueOf(String path, Base base, Map<String, String> namespaces, Map<QName, Function> functions, Map<QName, Object> variables) throws XPathException { try { base = getElementWrapped(base); XPath xpath = getXPath(path, namespaces, functions, variables); return xpath.stringValueOf(base); } catch (JaxenException e) { throw new XPathException(e); } } public String valueOf(String path, Base base, Map<String, String> namespaces) throws XPathException { return valueOf(path, base, namespaces, functions, variables); } public boolean booleanValueOf(String path, Base base, Map<String, String> namespaces, Map<QName, Function> functions, Map<QName, Object> variables) throws XPathException { try { base = getElementWrapped(base); XPath xpath = getXPath(path, namespaces, functions, variables); return xpath.booleanValueOf(base); } catch (JaxenException e) { throw new XPathException(e); } } public boolean booleanValueOf(String path, Base base, Map<String, String> namespaces) throws XPathException { return booleanValueOf(path, base, namespaces, functions, variables); } public Number numericValueOf(String path, Base base, Map<String, String> namespaces, Map<QName, Function> functions, Map<QName, Object> variables) throws XPathException { try { base = getElementWrapped(base); XPath xpath = getXPath(path, namespaces, functions, variables); return xpath.numberValueOf(base); } catch (JaxenException e) { throw new XPathException(e); } } public Number numericValueOf(String path, Base base, Map<String, String> namespaces) throws XPathException { return numericValueOf(path, base, namespaces, functions, variables); } public Map<QName, Function> getDefaultFunctions() { return new HashMap<QName, Function>(functions); } public synchronized void setDefaultFunctions(Map<QName, Function> functions) { this.functions.clear(); this.functions.putAll(functions); } public Map<QName, Object> getDefaultVariables() { return new HashMap<QName, Object>(variables); } public synchronized void setDefaultVariables(Map<QName, Object> variables) { this.variables.clear(); this.variables.putAll(variables); } private Base getElementWrapped(Base base) { if (base instanceof ElementWrapper) { base = ((ElementWrapper)base).getInternal(); } return base; } }
7,471
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMParserFactory.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.parser.stax; import java.util.HashMap; import java.util.Map; import org.apache.abdera.Abdera; import org.apache.abdera.parser.NamedParser; import org.apache.abdera.parser.Parser; import org.apache.abdera.parser.ParserFactory; import org.apache.abdera.util.AbstractParser; @SuppressWarnings("unchecked") public class FOMParserFactory implements ParserFactory { private final Abdera abdera; private final Map<String, NamedParser> parsers; public FOMParserFactory() { this(new Abdera()); } public FOMParserFactory(Abdera abdera) { this.abdera = abdera; Map<String, NamedParser> p = getAbdera().getConfiguration().getNamedParsers(); this.parsers = (p != null) ? p : new HashMap<String, NamedParser>(); } protected Abdera getAbdera() { return abdera; } public <T extends Parser> T getParser() { return (T)getAbdera().getParser(); } public <T extends Parser> T getParser(String name) { Parser parser = (T)((name != null) ? getParsers().get(name.toLowerCase()) : getParser()); if (parser instanceof AbstractParser) { ((AbstractParser)parser).setAbdera(abdera); } return (T)parser; } private Map<String, NamedParser> getParsers() { return parsers; } }
7,472
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMMultipartCollection.java
package org.apache.abdera.parser.stax; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import javax.activation.MimeType; import javax.xml.namespace.QName; import org.apache.abdera.model.Collection; import org.apache.abdera.model.Element; import org.apache.abdera.util.MimeTypeHelper; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMXMLParserWrapper; public class FOMMultipartCollection extends FOMCollection { protected FOMMultipartCollection(QName qname, OMContainer parent, OMFactory factory) { super(qname, parent, factory); } protected FOMMultipartCollection(String localName, OMContainer parent, OMFactory factory, OMXMLParserWrapper builder) { super(localName, parent, factory, builder); } protected FOMMultipartCollection(OMContainer parent, OMFactory factory) { super(COLLECTION, parent, factory); } public boolean acceptsMultipart(String mediaType) { Map<String, String> accept = getAcceptMultiparted(); if (accept.size() == 0) accept = Collections.singletonMap("application/atom+xml;type=entry", null); for (Map.Entry<String, String> entry : accept.entrySet()) { if (MimeTypeHelper.isMatch(entry.getKey(), mediaType) && entry.getValue() != null && entry.getValue().equals(LN_ALTERNATE_MULTIPART_RELATED)) return true; } return false; } public boolean acceptsMultipart(MimeType mediaType) { return accepts(mediaType.toString()); } public Map<String, String> getAcceptMultiparted() { Map<String, String> accept = new HashMap<String, String>(); Iterator<?> i = getChildrenWithName(ACCEPT); if (i == null || !i.hasNext()) i = getChildrenWithName(PRE_RFC_ACCEPT); while (i.hasNext()) { Element e = (Element)i.next(); String t = e.getText(); if (t != null) { if (e.getAttributeValue(ALTERNATE) != null && e.getAttributeValue(ALTERNATE).trim().length() > 0) { accept.put(t.trim(), e.getAttributeValue(ALTERNATE)); } else { accept.put(t.trim(), null); } } } return accept; } public Collection setAccept(String mediaRange, String alternate) { return setAccept(Collections.singletonMap(mediaRange, alternate)); } public Collection setAccept(Map<String, String> mediaRanges) { complete(); if (mediaRanges != null && mediaRanges.size() > 0) { _removeChildren(ACCEPT, true); _removeChildren(PRE_RFC_ACCEPT, true); if (mediaRanges.size() == 1 && mediaRanges.keySet().iterator().next().equals("")) { addExtension(ACCEPT); } else { for (Map.Entry<String, String> entry : mediaRanges.entrySet()) { if (entry.getKey().equalsIgnoreCase("entry")) { addSimpleExtension(ACCEPT, "application/atom+xml;type=entry"); } else { try { Element accept = addSimpleExtension(ACCEPT, new MimeType(entry.getKey()).toString()); if (entry.getValue() != null) { accept.setAttributeValue(ALTERNATE, entry.getValue()); } } catch (javax.activation.MimeTypeParseException e) { throw new org.apache.abdera.util.MimeTypeParseException(e); } } } } } else { _removeChildren(ACCEPT, true); _removeChildren(PRE_RFC_ACCEPT, true); } return this; } public Collection addAccepts(String mediaRange, String alternate) { return addAccepts(Collections.singletonMap(mediaRange, alternate)); } public Collection addAccepts(Map<String, String> mediaRanges) { complete(); if (mediaRanges != null) { for (Map.Entry<String, String> entry : mediaRanges.entrySet()) { if (!accepts(entry.getKey())) { try { Element accept = addSimpleExtension(ACCEPT, new MimeType(entry.getKey()).toString()); if (entry.getValue() != null) { accept.setAttributeValue(ALTERNATE, entry.getValue()); } } catch (Exception e) { } } } } return this; } }
7,473
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMFeed.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.parser.stax; import java.util.Arrays; import java.util.Comparator; import java.util.Date; import java.util.Iterator; import java.util.List; import javax.xml.namespace.QName; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Entry; import org.apache.abdera.model.Feed; import org.apache.abdera.model.Source; import org.apache.abdera.util.Constants; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMNode; import org.apache.axiom.om.OMXMLParserWrapper; public class FOMFeed extends FOMSource implements Feed { private static final long serialVersionUID = 4552921210185524535L; public FOMFeed() { super(Constants.FEED, new FOMDocument<Feed>(), new FOMFactory()); } protected FOMFeed(String name, OMNamespace namespace, OMContainer parent, OMFactory factory) throws OMException { super(name, namespace, parent, factory); } protected FOMFeed(QName qname, OMContainer parent, OMFactory factory) { super(qname, parent, factory); } protected FOMFeed(String localName, OMContainer parent, OMFactory factory, OMXMLParserWrapper builder) { super(localName, parent, factory, builder); } protected FOMFeed(OMContainer parent, OMFactory factory) throws OMException { super(FEED, parent, factory); } public List<Entry> getEntries() { return _getChildrenAsSet(ENTRY); } public Feed addEntry(Entry entry) { complete(); addChild((OMElement)entry); return this; } public Entry addEntry() { complete(); FOMFactory fomfactory = (FOMFactory)getOMFactory(); return fomfactory.newEntry(this); } public Feed insertEntry(Entry entry) { complete(); OMElement el = getFirstChildWithName(ENTRY); if (el == null) { addEntry(entry); } else { el.insertSiblingBefore((OMElement)entry); } return this; } public Entry insertEntry() { complete(); FOMFactory fomfactory = (FOMFactory)getOMFactory(); Entry entry = fomfactory.newEntry((Feed)null); insertEntry(entry); return entry; } public Source getAsSource() { FOMSource source = (FOMSource)((FOMFactory)getOMFactory()).newSource(null); for (Iterator<?> i = this.getChildElements(); i.hasNext();) { FOMElement child = (FOMElement)i.next(); if (!child.getQName().equals(ENTRY)) { source.addChild((OMNode)child.clone()); } } try { if (this.getBaseUri() != null) { source.setBaseUri(this.getBaseUri()); } } catch (Exception e) { } return source; } @Override public void addChild(OMNode node) { if (isComplete() && node instanceof OMElement && !(node instanceof Entry)) { OMElement el = this.getFirstChildWithName(ENTRY); if (el != null) { el.insertSiblingBefore(node); return; } } super.addChild(node); } public Feed sortEntriesByUpdated(boolean new_first) { complete(); sortEntries(new UpdatedComparator(new_first)); return this; } public Feed sortEntriesByEdited(boolean new_first) { complete(); sortEntries(new EditedComparator(new_first)); return this; } public Feed sortEntries(Comparator<Entry> comparator) { complete(); if (comparator == null) return this; List<Entry> entries = this.getEntries(); Entry[] a = entries.toArray(new Entry[entries.size()]); Arrays.sort(a, comparator); for (Entry e : entries) { e.discard(); } for (Entry e : a) { addEntry(e); } return this; } private static class EditedComparator implements Comparator<Entry> { private boolean new_first = true; EditedComparator(boolean new_first) { this.new_first = new_first; } public int compare(Entry o1, Entry o2) { Date d1 = o1.getEdited(); Date d2 = o2.getEdited(); if (d1 == null) d1 = o1.getUpdated(); if (d2 == null) d2 = o2.getUpdated(); if (d1 == null && d2 == null) return 0; if (d1 == null && d2 != null) return -1; if (d1 != null && d2 == null) return 1; int r = d1.compareTo(d2); return (new_first) ? -r : r; } }; private static class UpdatedComparator implements Comparator<Entry> { private boolean new_first = true; UpdatedComparator(boolean new_first) { this.new_first = new_first; } public int compare(Entry o1, Entry o2) { Date d1 = o1.getUpdated(); Date d2 = o2.getUpdated(); if (d1 == null && d2 == null) return 0; if (d1 == null && d2 != null) return -1; if (d1 != null && d2 == null) return 1; int r = d1.compareTo(d2); return (new_first) ? -r : r; } }; public Entry getEntry(String id) { if (id == null) return null; List<Entry> l = getEntries(); for (Entry e : l) { IRI eid = e.getId(); if (eid != null && eid.equals(new IRI(id))) return e; } return null; } }
7,474
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMWriter.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.parser.stax; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import org.apache.abdera.Abdera; import org.apache.abdera.model.Base; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.util.AbstractWriter; import org.apache.abdera.util.Constants; import org.apache.abdera.util.MimeTypeHelper; import org.apache.abdera.writer.WriterOptions; public class FOMWriter extends AbstractWriter implements org.apache.abdera.writer.NamedWriter { public FOMWriter() { } public FOMWriter(Abdera abdera) { } @SuppressWarnings("unchecked") public void writeTo(Base base, OutputStream out, WriterOptions options) throws IOException { out = getCompressedOutputStream(out, options); String charset = options.getCharset(); if (charset == null) { if (base instanceof Document) charset = ((Document)base).getCharset(); else if (base instanceof Element) { Document doc = ((Element)base).getDocument(); if (doc != null) charset = doc.getCharset(); } if (charset == null) charset = "UTF-8"; } else { Document doc = null; if (base instanceof Document) doc = (Document)base; else if (base instanceof Element) doc = ((Element)base).getDocument(); if (doc != null) doc.setCharset(charset); } base.writeTo(new OutputStreamWriter(out, charset)); finishCompressedOutputStream(out, options); if (options.getAutoClose()) out.close(); } public void writeTo(Base base, Writer out, WriterOptions options) throws IOException { base.writeTo(out); if (options.getAutoClose()) out.close(); } public Object write(Base base, WriterOptions options) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); writeTo(base, out, options); return out.toString(); } public String getName() { return "default"; } public String[] getOutputFormats() { return new String[] {Constants.ATOM_MEDIA_TYPE, Constants.APP_MEDIA_TYPE, Constants.CAT_MEDIA_TYPE, Constants.XML_MEDIA_TYPE}; } public boolean outputsFormat(String mediatype) { return MimeTypeHelper.isMatch(mediatype, Constants.ATOM_MEDIA_TYPE) || MimeTypeHelper .isMatch(mediatype, Constants.APP_MEDIA_TYPE) || MimeTypeHelper.isMatch(mediatype, Constants.CAT_MEDIA_TYPE) || MimeTypeHelper.isMatch(mediatype, Constants.XML_MEDIA_TYPE); } @Override protected WriterOptions initDefaultWriterOptions() { return new FOMWriterOptions(); } }
7,475
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMComment.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.parser.stax; import org.apache.abdera.factory.Factory; import org.apache.abdera.model.Base; import org.apache.abdera.model.Comment; import org.apache.abdera.model.Element; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.impl.llom.OMCommentImpl; @SuppressWarnings("unchecked") public class FOMComment extends OMCommentImpl implements Comment { public FOMComment(OMContainer parent, String contentText, OMFactory factory, boolean fromBuilder) { super(parent, contentText, factory, fromBuilder); } public String getText() { return super.getValue(); } public Comment setText(String text) { super.setValue(text); return this; } public <T extends Base> T getParentElement() { T parent = (T)super.getParent(); return (T)((parent instanceof Element) ? getWrapped((Element)parent) : parent); } protected Element getWrapped(Element internal) { if (internal == null) return null; FOMFactory factory = (FOMFactory)getFactory(); return factory.getElementWrapper(internal); } public Factory getFactory() { return (Factory)this.getOMFactory(); } public String toString() { java.io.CharArrayWriter w = new java.io.CharArrayWriter(); try { super.serialize(w); } catch (Exception e) { } return w.toString(); } }
7,476
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMService.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.parser.stax; import java.util.ArrayList; import java.util.List; import javax.activation.MimeType; import javax.xml.namespace.QName; import org.apache.abdera.model.Collection; import org.apache.abdera.model.Service; import org.apache.abdera.model.Workspace; import org.apache.abdera.util.Constants; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMXMLParserWrapper; @SuppressWarnings("deprecation") public class FOMService extends FOMExtensibleElement implements Service { private static final long serialVersionUID = 7982751563668891240L; public FOMService() { super(Constants.SERVICE, new FOMDocument<Service>(), new FOMFactory()); declareAtomNs(); } protected FOMService(String name, OMNamespace namespace, OMContainer parent, OMFactory factory) throws OMException { super(name, namespace, parent, factory); declareAtomNs(); } protected FOMService(QName qname, OMContainer parent, OMFactory factory) { super(qname, parent, factory); declareAtomNs(); } protected FOMService(String localName, OMContainer parent, OMFactory factory, OMXMLParserWrapper builder) { super(localName, parent, factory, builder); } protected FOMService(OMContainer parent, OMFactory factory) throws OMException { super(SERVICE, parent, factory); declareAtomNs(); } private void declareAtomNs() { declareDefaultNamespace(APP_NS); declareNamespace(ATOM_NS, "atom"); } public List<Workspace> getWorkspaces() { List<Workspace> list = _getChildrenAsSet(WORKSPACE); if (list == null || list.size() == 0) list = _getChildrenAsSet(PRE_RFC_WORKSPACE); return list; } public Workspace getWorkspace(String title) { List<Workspace> workspaces = getWorkspaces(); Workspace workspace = null; for (Workspace w : workspaces) { if (w.getTitle().equals(title)) { workspace = w; break; } } return workspace; } public Service addWorkspace(Workspace workspace) { complete(); addChild((OMElement)workspace); return this; } public Workspace addWorkspace(String title) { complete(); FOMFactory fomfactory = (FOMFactory)getOMFactory(); Workspace workspace = fomfactory.newWorkspace(this); workspace.setTitle(title); return workspace; } public Collection getCollection(String workspace, String collection) { Collection col = null; Workspace w = getWorkspace(workspace); if (w != null) { col = w.getCollection(collection); } return col; } public Collection getCollectionThatAccepts(MimeType... types) { Collection collection = null; for (Workspace workspace : getWorkspaces()) { collection = workspace.getCollectionThatAccepts(types); if (collection != null) break; } return collection; } public Collection getCollectionThatAccepts(String... types) { Collection collection = null; for (Workspace workspace : getWorkspaces()) { collection = workspace.getCollectionThatAccepts(types); if (collection != null) break; } return collection; } public List<Collection> getCollectionsThatAccept(MimeType... types) { List<Collection> collections = new ArrayList<Collection>(); for (Workspace workspace : getWorkspaces()) { List<Collection> colls = workspace.getCollectionsThatAccept(types); collections.addAll(colls); } return collections; } public List<Collection> getCollectionsThatAccept(String... types) { List<Collection> collections = new ArrayList<Collection>(); for (Workspace workspace : getWorkspaces()) { List<Collection> colls = workspace.getCollectionsThatAccept(types); collections.addAll(colls); } return collections; } }
7,477
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMText.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.parser.stax; import javax.xml.namespace.QName; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Div; import org.apache.abdera.model.Element; import org.apache.abdera.model.Text; import org.apache.abdera.util.Constants; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMNode; import org.apache.axiom.om.OMXMLParserWrapper; @SuppressWarnings("unchecked") public class FOMText extends FOMElement implements Text { private static final long serialVersionUID = 5177795905116574120L; protected Type type = Type.TEXT; protected FOMText(Type type, String name, OMNamespace namespace, OMContainer parent, OMFactory factory) throws OMException { super(name, namespace, parent, factory); init(type); } protected FOMText(Type type, QName qname, OMContainer parent, OMFactory factory) throws OMException { super(qname, parent, factory); init(type); } protected FOMText(Type type, String localName, OMContainer parent, OMFactory factory, OMXMLParserWrapper builder) throws OMException { super(localName, parent, factory, builder); init(type); } private void init(Type type) { this.type = type; if (Type.TEXT.equals(type)) setAttributeValue(TYPE, "text"); else if (Type.HTML.equals(type)) setAttributeValue(TYPE, "html"); else if (Type.XHTML.equals(type)) setAttributeValue(TYPE, "xhtml"); else removeAttribute(TYPE); } public final Type getTextType() { return type; } public Text setTextType(Type type) { complete(); init(type); return this; } public Div getValueElement() { return (Div)this.getFirstChildWithName(Constants.DIV); } public Text setValueElement(Div value) { complete(); if (value != null) { if (this.getFirstChildWithName(Constants.DIV) != null) this.getFirstChildWithName(Constants.DIV).discard(); init(Text.Type.XHTML); removeChildren(); addChild((OMElement)value); } else _removeAllChildren(); return this; } public String getValue() { String val = null; if (Type.TEXT.equals(type)) { val = getText(); } else if (Type.HTML.equals(type)) { val = getText(); } else if (Type.XHTML.equals(type)) { FOMDiv div = (FOMDiv)this.getFirstChildWithName(Constants.DIV); val = (div != null) ? div.getInternalValue() : null; } return val; } public <T extends Element> T setText(String value) { return (T)setText(Text.Type.TEXT, value); } public <T extends Element> T setText(Text.Type type, String value) { complete(); init(type); if (value != null) { OMNode child = this.getFirstOMChild(); while (child != null) { if (child.getType() == OMNode.TEXT_NODE) { child.detach(); } child = child.getNextOMSibling(); } getOMFactory().createOMText(this, value); } else _removeAllChildren(); return (T)this; } public Text setValue(String value) { complete(); if (value != null) { if (Type.TEXT.equals(type)) { setText(type, value); } else if (Type.HTML.equals(type)) { setText(type, value); } else if (Type.XHTML.equals(type)) { IRI baseUri = null; value = "<div xmlns=\"" + XHTML_NS + "\">" + value + "</div>"; Element element = null; try { baseUri = getResolvedBaseUri(); element = _parse(value, baseUri); } catch (Exception e) { } if (element != null && element instanceof Div) setValueElement((Div)element); } } else _removeAllChildren(); return this; } public String getWrappedValue() { if (Type.XHTML.equals(type)) { return this.getFirstChildWithName(Constants.DIV).toString(); } else { return getValue(); } } public Text setWrappedValue(String wrappedValue) { complete(); if (Type.XHTML.equals(type)) { IRI baseUri = null; Element element = null; try { baseUri = getResolvedBaseUri(); element = _parse(wrappedValue, baseUri); } catch (Exception e) { } if (element != null && element instanceof Div) setValueElement((Div)element); } else { setValue(wrappedValue); } return this; } @Override public IRI getBaseUri() { if (Type.XHTML.equals(type)) { Element el = getValueElement(); if (el != null) { if (el.getAttributeValue(BASE) != null) { if (getAttributeValue(BASE) != null) return super.getBaseUri().resolve(el.getAttributeValue(BASE)); else return _getUriValue(el.getAttributeValue(BASE)); } } } return super.getBaseUri(); } @Override public IRI getResolvedBaseUri() { if (Type.XHTML.equals(type)) { Element el = getValueElement(); if (el != null) { if (el.getAttributeValue(BASE) != null) { return super.getResolvedBaseUri().resolve(el.getAttributeValue(BASE)); } } } return super.getResolvedBaseUri(); } @Override public String getLanguage() { if (Type.XHTML.equals(type)) { Element el = getValueElement(); if (el != null && el.getAttributeValue(LANG) != null) return el.getAttributeValue(LANG); } return super.getLanguage(); } @Override public Object clone() { FOMText text = (FOMText)super.clone(); text.type = type; return text; } }
7,478
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMUnsupportedTextTypeException.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.parser.stax; import org.apache.abdera.i18n.text.Localizer; public class FOMUnsupportedTextTypeException extends FOMException { private static final long serialVersionUID = 4156893310308105899L; public FOMUnsupportedTextTypeException(String message) { super(Localizer.sprintf("UNSUPPORTED.TEXT.TYPE", message)); } }
7,479
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMWriterFactory.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.parser.stax; import java.util.HashMap; import java.util.Map; import org.apache.abdera.Abdera; import org.apache.abdera.i18n.text.Localizer; import org.apache.abdera.writer.NamedWriter; import org.apache.abdera.writer.StreamWriter; import org.apache.abdera.writer.Writer; import org.apache.abdera.writer.WriterFactory; @SuppressWarnings("unchecked") public class FOMWriterFactory implements WriterFactory { private final Abdera abdera; private final Map<String, NamedWriter> writers; private final Map<String, Class<? extends StreamWriter>> streamwriters; public FOMWriterFactory() { this(new Abdera()); } public FOMWriterFactory(Abdera abdera) { this.abdera = abdera; Map<String, NamedWriter> w = getAbdera().getConfiguration().getNamedWriters(); writers = (w != null) ? w : new HashMap<String, NamedWriter>(); Map<String, Class<? extends StreamWriter>> s = getAbdera().getConfiguration().getStreamWriters(); streamwriters = (s != null) ? s : new HashMap<String, Class<? extends StreamWriter>>(); } protected Abdera getAbdera() { return abdera; } public <T extends Writer> T getWriter() { return (T)getAbdera().getWriter(); } public <T extends Writer> T getWriter(String name) { return (T)((name != null) ? getWriters().get(name.toLowerCase()) : getWriter()); } public <T extends Writer> T getWriterByMediaType(String mediatype) { Map<String, NamedWriter> writers = getWriters(); for (NamedWriter writer : writers.values()) { if (writer.outputsFormat(mediatype)) return (T)writer; } return null; } private Map<String, NamedWriter> getWriters() { return writers; } private Map<String, Class<? extends StreamWriter>> getStreamWriters() { return streamwriters; } public <T extends StreamWriter> T newStreamWriter() { return (T)getAbdera().newStreamWriter(); } public <T extends StreamWriter> T newStreamWriter(String name) { Class<? extends StreamWriter> _class = getStreamWriters().get(name); StreamWriter sw = null; if (_class != null) { try { sw = _class.newInstance(); } catch (Exception e) { throw new RuntimeException(Localizer.sprintf("IMPLEMENTATION.NOT.AVAILABLE", "StreamWriter"), e); } } return (T)sw; } }
7,480
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMLink.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.parser.stax; import java.util.HashMap; import java.util.Map; import javax.activation.MimeType; import javax.xml.namespace.QName; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Element; import org.apache.abdera.model.Link; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMXMLParserWrapper; public class FOMLink extends FOMExtensibleElement implements Link { private static final long serialVersionUID = 2239772197929910635L; protected FOMLink(String name, OMNamespace namespace, OMContainer parent, OMFactory factory) throws OMException { super(name, namespace, parent, factory); } protected FOMLink(OMContainer parent, OMFactory factory) throws OMException { super(LINK, parent, factory); } protected FOMLink(QName qname, OMContainer parent, OMFactory factory) throws OMException { super(qname, parent, factory); } protected FOMLink(String localName, OMContainer parent, OMFactory factory, OMXMLParserWrapper builder) throws OMException { super(localName, parent, factory, builder); } public IRI getHref() { return _getUriValue(getAttributeValue(HREF)); } public IRI getResolvedHref() { return _resolve(getResolvedBaseUri(), getHref()); } public Link setHref(String href) { complete(); if (href != null) setAttributeValue(HREF, (new IRI(href)).toString()); else removeAttribute(HREF); return this; } public String getRel() { return getAttributeValue(REL); } public Link setRel(String rel) { complete(); setAttributeValue(REL, rel); return this; } public MimeType getMimeType() { try { String type = getAttributeValue(TYPE); return (type != null) ? new MimeType(type) : null; } catch (javax.activation.MimeTypeParseException e) { throw new org.apache.abdera.util.MimeTypeParseException(e); } } public void setMimeType(MimeType type) { complete(); setAttributeValue(TYPE, (type != null) ? type.toString() : null); } public Link setMimeType(String type) { complete(); try { if (type != null) setAttributeValue(TYPE, (new MimeType(type)).toString()); else removeAttribute(TYPE); } catch (javax.activation.MimeTypeParseException e) { throw new org.apache.abdera.util.MimeTypeParseException(e); } return this; } public String getHrefLang() { return getAttributeValue(HREFLANG); } public Link setHrefLang(String lang) { complete(); if (lang != null) setAttributeValue(HREFLANG, lang); else removeAttribute(HREFLANG); return this; } public String getTitle() { return getAttributeValue(ATITLE); } public Link setTitle(String title) { complete(); if (title != null) setAttributeValue(ATITLE, title); else removeAttribute(ATITLE); return this; } public long getLength() { String l = getAttributeValue(LENGTH); return (l != null) ? Long.valueOf(l) : -1; } public Link setLength(long length) { complete(); if (length > -1) setAttributeValue(LENGTH, (length >= 0) ? String.valueOf(length) : "0"); else removeAttribute(LENGTH); return this; } private static final Map<String, String> REL_EQUIVS = new HashMap<String, String>(); static { REL_EQUIVS.put(REL_ALTERNATE_IANA, REL_ALTERNATE); REL_EQUIVS.put(REL_CURRENT_IANA, REL_CURRENT); REL_EQUIVS.put(REL_ENCLOSURE_IANA, REL_ENCLOSURE); REL_EQUIVS.put(REL_FIRST_IANA, REL_FIRST); REL_EQUIVS.put(REL_LAST_IANA, REL_LAST); REL_EQUIVS.put(REL_NEXT_IANA, REL_NEXT); REL_EQUIVS.put(REL_PAYMENT_IANA, REL_PAYMENT); REL_EQUIVS.put(REL_PREVIOUS_IANA, REL_PREVIOUS); REL_EQUIVS.put(REL_RELATED_IANA, REL_RELATED); REL_EQUIVS.put(REL_SELF_IANA, REL_SELF); REL_EQUIVS.put(REL_VIA_IANA, REL_VIA); REL_EQUIVS.put(REL_REPLIES_IANA, REL_REPLIES); REL_EQUIVS.put(REL_LICENSE_IANA, REL_LICENSE); REL_EQUIVS.put(REL_EDIT_IANA, REL_EDIT); REL_EQUIVS.put(REL_EDIT_MEDIA_IANA, REL_EDIT_MEDIA); REL_EQUIVS.put(REL_SERVICE_IANA, REL_SERVICE); } public static final String getRelEquiv(String val) { try { val = IRI.normalizeString(val); } catch (Exception e) { } String rel = REL_EQUIVS.get(val); return (rel != null) ? rel : val; } public String getValue() { return getText(); } public void setValue(String value) { complete(); if (value != null) ((Element)this).setText(value); else _removeAllChildren(); } }
7,481
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/FOMCategories.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.parser.stax; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.QName; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Categories; import org.apache.abdera.model.Category; import org.apache.abdera.parser.stax.util.FOMHelper; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMException; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.OMNamespace; import org.apache.axiom.om.OMXMLParserWrapper; public class FOMCategories extends FOMExtensibleElement implements Categories { private static final long serialVersionUID = 5480273546375102411L; public FOMCategories() { super(CATEGORIES, new FOMDocument<Categories>(), new FOMFactory()); init(); } protected FOMCategories(String name, OMNamespace namespace, OMContainer parent, OMFactory factory) throws OMException { super(name, namespace, parent, factory); init(); } protected FOMCategories(QName qname, OMContainer parent, OMFactory factory) { super(qname, parent, factory); init(); } protected FOMCategories(String localName, OMContainer parent, OMFactory factory, OMXMLParserWrapper builder) { super(localName, parent, factory, builder); } protected FOMCategories(OMContainer parent, OMFactory factory) throws OMException { super(CATEGORIES, parent, factory); init(); } private void init() { this.declareNamespace(ATOM_NS, "atom"); } public Categories addCategory(Category category) { complete(); addChild((OMElement)category); return this; } public Category addCategory(String term) { complete(); FOMFactory factory = (FOMFactory)this.getOMFactory(); Category category = factory.newCategory(this); category.setTerm(term); return category; } public Category addCategory(String scheme, String term, String label) { complete(); FOMFactory factory = (FOMFactory)this.getOMFactory(); Category category = factory.newCategory(this); category.setTerm(term); category.setScheme(scheme); category.setLabel(label); return category; } public List<Category> getCategories() { return _getChildrenAsSet(CATEGORY); } public List<Category> getCategories(String scheme) { return FOMHelper.getCategories(this, scheme); } private List<Category> copyCategoriesWithScheme(List<Category> cats) { List<Category> newcats = new ArrayList<Category>(); IRI scheme = getScheme(); for (Category cat : cats) { Category newcat = (Category)cat.clone(); if (newcat.getScheme() == null && scheme != null) newcat.setScheme(scheme.toString()); newcats.add(newcat); } return newcats; } public List<Category> getCategoriesWithScheme() { return copyCategoriesWithScheme(getCategories()); } public List<Category> getCategoriesWithScheme(String scheme) { return copyCategoriesWithScheme(getCategories(scheme)); } public IRI getScheme() { String value = getAttributeValue(SCHEME); return (value != null) ? new IRI(value) : null; } public boolean isFixed() { String value = getAttributeValue(FIXED); return (value != null && value.equals(YES)); } public Categories setFixed(boolean fixed) { complete(); if (fixed && !isFixed()) setAttributeValue(FIXED, YES); else if (!fixed && isFixed()) removeAttribute(FIXED); return this; } public Categories setScheme(String scheme) { complete(); if (scheme != null) setAttributeValue(SCHEME, new IRI(scheme).toString()); else removeAttribute(SCHEME); return this; } public IRI getHref() { return _getUriValue(getAttributeValue(HREF)); } public IRI getResolvedHref() { return _resolve(getResolvedBaseUri(), getHref()); } public Categories setHref(String href) { complete(); if (href != null) setAttributeValue(HREF, (new IRI(href)).toString()); else removeAttribute(HREF); return this; } public boolean contains(String term) { return contains(term, null); } public boolean contains(String term, String scheme) { List<Category> categories = getCategories(); IRI catscheme = getScheme(); IRI uri = (scheme != null) ? new IRI(scheme) : catscheme; for (Category category : categories) { String t = category.getTerm(); IRI s = (category.getScheme() != null) ? category.getScheme() : catscheme; if (t.equals(term) && ((uri != null) ? uri.equals(s) : s == null)) return true; } return false; } public boolean isOutOfLine() { boolean answer = false; try { answer = getHref() != null; } catch (Exception e) { } return answer; } }
7,482
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/util/FOMXmlVersionInputStream.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.parser.stax.util; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import org.apache.abdera.i18n.text.io.PeekAheadInputStream; /** * Will attempt to autodetect the character encoding from the stream This will preserve the BOM if it exists */ public class FOMXmlVersionInputStream extends FilterInputStream { private String version = null; public FOMXmlVersionInputStream(InputStream in) { super(new PeekAheadInputStream(in, 4)); try { version = detectVersion(); } catch (IOException e) { } } public String getVersion() { return version; } private String detectVersion() throws IOException { String version = "1.0"; PeekAheadInputStream pin = (PeekAheadInputStream)this.in; try { byte[] p = new byte[200]; pin.peek(p); XMLStreamReader xmlreader = XMLInputFactory.newInstance().createXMLStreamReader(new java.io.ByteArrayInputStream(p)); String v = xmlreader.getVersion(); if (v != null) version = v; } catch (Exception e) { } return version; } }
7,483
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/util/ResolveFunction.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.parser.stax.util; import java.util.ArrayList; import java.util.List; import javax.xml.namespace.QName; import org.apache.abdera.i18n.iri.IRI; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.axiom.om.OMAttribute; import org.apache.axiom.om.OMContainer; import org.apache.axiom.om.OMNode; import org.jaxen.Context; import org.jaxen.Function; import org.jaxen.FunctionCallException; import org.jaxen.Navigator; import org.jaxen.function.StringFunction; public class ResolveFunction implements Function { public static final QName QNAME = new QName("http://abdera.apache.org", "resolve"); @SuppressWarnings("unchecked") public Object call(Context context, List args) throws FunctionCallException { List<String> results = new ArrayList<String>(); if (args.isEmpty()) return null; Navigator navigator = context.getNavigator(); for (Object obj : args) { if (obj instanceof List) { for (Object o : (List)obj) { try { String value = StringFunction.evaluate(o, navigator); IRI resolved = null; IRI baseUri = null; if (o instanceof OMNode) { OMNode node = (OMNode)o; OMContainer el = node.getParent(); if (el instanceof Document) { Document<Element> doc = (Document<Element>)el; baseUri = doc.getBaseUri(); } else if (el instanceof Element) { Element element = (Element)el; baseUri = element.getBaseUri(); } } else if (o instanceof OMAttribute) { OMAttribute attr = (OMAttribute)o; Element element = (Element)context.getNavigator().getParentNode(attr); baseUri = element.getBaseUri(); } if (baseUri != null) { resolved = baseUri.resolve(value); results.add(resolved.toString()); } } catch (Exception e) { } } } else { // nothing to do } } if (results.size() == 1) { return results.get(0); } else if (results.size() > 1) { return results; } else return null; } }
7,484
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/util/FOMXmlVersionReader.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.parser.stax.util; import java.io.IOException; import java.io.PushbackReader; import java.io.Reader; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; public class FOMXmlVersionReader extends PushbackReader { private String version = null; public FOMXmlVersionReader(Reader in) { super(in, 200); try { version = detectVersion(); } catch (IOException e) { } } public String getVersion() { return version; } private String detectVersion() throws IOException { String version = "1.0"; try { char[] p = new char[200]; int r = read(p); XMLStreamReader xmlreader = XMLInputFactory.newInstance().createXMLStreamReader(new java.io.CharArrayReader(p)); String v = xmlreader.getVersion(); if (v != null) version = v; unread(p, 0, r); } catch (Exception e) { } return version; } }
7,485
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/util/PrettyWriter.java
package org.apache.abdera.parser.stax.util; /* * 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. */ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import javax.xml.namespace.NamespaceContext; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.apache.abdera.model.Base; import org.apache.abdera.model.Document; import org.apache.abdera.model.Element; import org.apache.abdera.model.ElementWrapper; import org.apache.abdera.util.AbstractNamedWriter; import org.apache.abdera.util.AbstractWriterOptions; import org.apache.abdera.writer.NamedWriter; import org.apache.abdera.writer.WriterOptions; import org.apache.axiom.om.OMDocument; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.util.StAXUtils; @SuppressWarnings("unchecked") public class PrettyWriter extends AbstractNamedWriter implements NamedWriter { private static final String[] FORMATS = {"application/atom+xml", "application/atomserv+xml", "application/xml"}; public PrettyWriter() { super("PrettyXML", FORMATS); } public Object write(Base base, WriterOptions options) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); writeTo(base, out, options); return out.toString(); } public void writeTo(Base base, OutputStream out, WriterOptions options) throws IOException { out = getCompressedOutputStream(out, options); String charset = options.getCharset() != null ? options.getCharset() : "UTF-8"; writeTo(base, new OutputStreamWriter(out, charset), options); finishCompressedOutputStream(out, options); if (options.getAutoClose()) out.close(); } public void writeTo(Base base, Writer out, WriterOptions options) throws IOException { try { XMLStreamWriter w = StAXUtils.createXMLStreamWriter(out); XMLStreamWriter pw = new PrettyStreamWriter(w); OMElement om = (base instanceof Document) ? getOMElement(((Document)base).getRoot()) : (OMElement)base; String charset = options.getCharset(); if (om.getParent() != null && om.getParent() instanceof OMDocument) { OMDocument doc = (OMDocument)om.getParent(); pw.writeStartDocument(charset != null ? charset : doc.getCharsetEncoding(), doc.getXMLVersion()); } om.serialize(pw); pw.writeEndDocument(); if (options.getAutoClose()) out.close(); } catch (XMLStreamException e) { throw new RuntimeException(e); } } private OMElement getOMElement(Element el) { if (el instanceof ElementWrapper) { return getOMElement(((ElementWrapper)el).getInternal()); } else return (OMElement)el; } private static class PrettyStreamWriter implements XMLStreamWriter { private static final int INDENT = 2; private XMLStreamWriter internal = null; private int depth = 0; private boolean prev_was_end_element = false; public PrettyStreamWriter(XMLStreamWriter writer) { this.internal = writer; } public void close() throws XMLStreamException { internal.close(); } public void flush() throws XMLStreamException { internal.flush(); } public NamespaceContext getNamespaceContext() { return internal.getNamespaceContext(); } public String getPrefix(String arg0) throws XMLStreamException { return internal.getPrefix(arg0); } public Object getProperty(String arg0) throws IllegalArgumentException { return internal.getProperty(arg0); } public void setDefaultNamespace(String arg0) throws XMLStreamException { internal.setDefaultNamespace(arg0); } public void setNamespaceContext(NamespaceContext arg0) throws XMLStreamException { internal.setNamespaceContext(arg0); } public void setPrefix(String arg0, String arg1) throws XMLStreamException { internal.setPrefix(arg0, arg1); } public void writeAttribute(String arg0, String arg1) throws XMLStreamException { internal.writeAttribute(arg0, arg1); prev_was_end_element = false; } public void writeAttribute(String arg0, String arg1, String arg2) throws XMLStreamException { internal.writeAttribute(arg0, arg1, arg2); prev_was_end_element = false; } public void writeAttribute(String arg0, String arg1, String arg2, String arg3) throws XMLStreamException { internal.writeAttribute(arg0, arg1, arg2, arg3); prev_was_end_element = false; } public void writeCData(String arg0) throws XMLStreamException { internal.writeCData(arg0); prev_was_end_element = false; } public void writeCharacters(String arg0) throws XMLStreamException { internal.writeCharacters(arg0); prev_was_end_element = false; } public void writeCharacters(char[] arg0, int arg1, int arg2) throws XMLStreamException { internal.writeCharacters(arg0, arg1, arg2); prev_was_end_element = false; } public void writeComment(String arg0) throws XMLStreamException { writeIndent(); internal.writeComment(arg0); prev_was_end_element = true; } public void writeDTD(String arg0) throws XMLStreamException { internal.writeDTD(arg0); prev_was_end_element = true; } public void writeDefaultNamespace(String arg0) throws XMLStreamException { internal.writeDefaultNamespace(arg0); prev_was_end_element = false; } public void writeEmptyElement(String arg0) throws XMLStreamException { writeIndent(); internal.writeEmptyElement(arg0); prev_was_end_element = true; } public void writeEmptyElement(String arg0, String arg1) throws XMLStreamException { writeIndent(); internal.writeEmptyElement(arg0, arg1); prev_was_end_element = true; } public void writeEmptyElement(String arg0, String arg1, String arg2) throws XMLStreamException { writeIndent(); internal.writeEmptyElement(arg0, arg1, arg2); prev_was_end_element = true; } public void writeEndDocument() throws XMLStreamException { internal.writeEndDocument(); prev_was_end_element = false; } public void writeEndElement() throws XMLStreamException { depth--; if (prev_was_end_element) writeIndent(); internal.writeEndElement(); prev_was_end_element = true; } public void writeEntityRef(String arg0) throws XMLStreamException { internal.writeEntityRef(arg0); prev_was_end_element = false; } public void writeNamespace(String arg0, String arg1) throws XMLStreamException { internal.writeNamespace(arg0, arg1); prev_was_end_element = false; } public void writeProcessingInstruction(String arg0) throws XMLStreamException { writeIndent(); internal.writeProcessingInstruction(arg0); prev_was_end_element = true; } public void writeProcessingInstruction(String arg0, String arg1) throws XMLStreamException { writeIndent(); internal.writeProcessingInstruction(arg0, arg1); prev_was_end_element = true; } public void writeStartDocument() throws XMLStreamException { internal.writeStartDocument(); prev_was_end_element = false; } public void writeStartDocument(String arg0) throws XMLStreamException { internal.writeStartDocument(arg0); prev_was_end_element = false; } public void writeStartDocument(String arg0, String arg1) throws XMLStreamException { internal.writeStartDocument(arg0, arg1); prev_was_end_element = false; } public void writeStartElement(String arg0) throws XMLStreamException { writeIndent(); depth++; internal.writeStartElement(arg0); prev_was_end_element = false; } public void writeStartElement(String arg0, String arg1) throws XMLStreamException { writeIndent(); depth++; internal.writeStartElement(arg0, arg1); prev_was_end_element = false; } public void writeStartElement(String arg0, String arg1, String arg2) throws XMLStreamException { writeIndent(); depth++; internal.writeStartElement(arg0, arg1, arg2); prev_was_end_element = false; } private void writeIndent() throws XMLStreamException { internal.writeCharacters("\n"); char[] spaces = getSpaces(); internal.writeCharacters(spaces, 0, spaces.length); } private char[] getSpaces() { char[] spaces = new char[INDENT * depth]; java.util.Arrays.fill(spaces, ' '); return spaces; } } @Override protected WriterOptions initDefaultWriterOptions() { return new AbstractWriterOptions() { }; } }
7,486
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/util/FOMSniffingInputStream.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.parser.stax.util; import java.io.IOException; import java.io.InputStream; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import org.apache.abdera.i18n.text.io.CharsetSniffingInputStream; import org.apache.abdera.i18n.text.io.PeekAheadInputStream; /** * Will attempt to autodetect the character encoding from the stream This will preserve the BOM if it exists. */ public class FOMSniffingInputStream extends CharsetSniffingInputStream { public FOMSniffingInputStream(InputStream in) { super(in); } protected String detectEncoding() throws IOException { String charset = super.detectEncoding(); PeekAheadInputStream pin = getInternal(); try { byte[] p = new byte[200]; pin.peek(p); XMLStreamReader xmlreader = XMLInputFactory.newInstance().createXMLStreamReader(new java.io.ByteArrayInputStream(p)); String cs = xmlreader.getCharacterEncodingScheme(); if (cs != null) charset = cs; } catch (Exception e) { } return charset; } }
7,487
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/util/FOMList.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.parser.stax.util; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.ListIterator; /** * Implements an ElementSet around an internal buffered iterator. Here's the rationale: Axiom parses incrementally. * Using the iterators provided by Axiom, we can walk a set of elements while preserving the incremental parsing model, * however, if we went with just java.util.Iterator, we'd lose the ability to do things like feed.getEntries().get(0), * or use the new Java5 style iterators for (Entry e : feed.getEntries()). However, using a regular java.util.List also * isn't a great option because it means we have to iterate through all of the elements before returning back to the * caller. This gives us a hybrid approach. We create an internal iterator, then create a List from that, the iterator * is consumed as the list is used. The List itself is unmodifiable. */ @SuppressWarnings("unchecked") public class FOMList<T> extends java.util.AbstractCollection<T> implements List<T> { private final Iterator<T> i; private final List<T> buffer = new ArrayList<T>(); public FOMList(Iterator<T> i) { this.i = i; } public List<T> getAsList() { buffer(-1); return java.util.Collections.unmodifiableList(buffer); } private boolean finished() { return !i.hasNext(); } private int buffered() { return buffer.size() - 1; } private int buffer(int n) { if (i.hasNext()) { int read = 0; while (i.hasNext() && (read++ < n || n == -1)) { buffer.add(i.next()); } } return buffered(); } public T get(int index) { int n = buffered(); if (index > n && (index > buffer(index - n))) throw new ArrayIndexOutOfBoundsException(index); return (T)buffer.get(index); } public int size() { return buffer(-1) + 1; } public Iterator<T> iterator() { return new BufferIterator<T>(this); } private Iterator<T> iterator(int index) { return new BufferIterator<T>(this, index); } public boolean add(T o) { throw new UnsupportedOperationException(); } public void add(int index, T element) { throw new UnsupportedOperationException(); } public boolean addAll(Collection c) { throw new UnsupportedOperationException(); } public boolean addAll(int index, Collection c) { throw new UnsupportedOperationException(); } public void clear() { throw new UnsupportedOperationException(); } public boolean contains(Object o) { buffer(-1); return buffer.contains(o); } public boolean containsAll(Collection c) { for (Object o : c) if (contains(o)) return true; return false; } public int indexOf(Object o) { buffer(-1); return buffer.indexOf(o); } public boolean isEmpty() { buffer(-1); return buffer.isEmpty(); } public int lastIndexOf(Object o) { buffer(-1); return buffer.lastIndexOf(o); } public ListIterator<T> listIterator() { return (ListIterator<T>)iterator(); } public ListIterator<T> listIterator(int index) { return (ListIterator<T>)iterator(index); } public boolean remove(Object o) { throw new UnsupportedOperationException(); } public T remove(int index) { throw new UnsupportedOperationException(); } public boolean removeAll(Collection c) { throw new UnsupportedOperationException(); } public boolean retainAll(Collection c) { throw new UnsupportedOperationException(); } public T set(int index, T element) { throw new UnsupportedOperationException(); } public List<T> subList(int fromIndex, int toIndex) { buffer(-1); return Collections.unmodifiableList(buffer.subList(fromIndex, toIndex)); } public Object[] toArray() { buffer(-1); return buffer.toArray(); } public Object[] toArray(Object[] a) { buffer(-1); return buffer.toArray(a); } private class BufferIterator<M> implements ListIterator<M> { private FOMList set = null; private int counter = 0; BufferIterator(FOMList set) { this.set = set; } BufferIterator(FOMList set, int index) { this.set = set; this.counter = index; } public boolean hasNext() { return (!set.finished()) || (set.finished() && counter < buffer.size()); } public M next() { return (M)set.get(counter++); } public void remove() { throw new UnsupportedOperationException(); } public void add(M o) { throw new UnsupportedOperationException(); } public boolean hasPrevious() { return counter > 0; } public int nextIndex() { if (hasNext()) return counter + 1; else return buffer.size(); } public M previous() { return (M)set.get(--counter); } public int previousIndex() { if (hasPrevious()) return counter - 1; else return -1; } public void set(M o) { throw new UnsupportedOperationException(); } } }
7,488
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/util/FOMHelper.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.parser.stax.util; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.abdera.model.Category; import org.apache.abdera.model.Element; import org.apache.abdera.model.Link; import org.apache.abdera.util.Constants; import org.apache.axiom.util.UIDGenerator; @SuppressWarnings("unchecked") public class FOMHelper implements Constants { public static List<Category> getCategories(Element element, String scheme) { Iterator i = new FOMElementIterator(element, Category.class, SCHEME, scheme, null); return new FOMList<Category>(i); } public static List<Link> getLinks(Element element, String rel) { Iterator i = new FOMLinkIterator(element, Link.class, REL, rel, Link.REL_ALTERNATE); return new FOMList<Link>(i); } public static List<Link> getLinks(Element element, String... rels) { List<Link> links = new ArrayList<Link>(); for (String rel : rels) { List<Link> l = getLinks(element, rel); links.addAll(l); } return links; } public static String generateUuid() { return UIDGenerator.generateURNString(); } }
7,489
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/util/FOMLinkIterator.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.parser.stax.util; import javax.xml.namespace.QName; import org.apache.abdera.model.Element; import org.apache.abdera.model.Link; import org.apache.abdera.parser.stax.FOMLink; public class FOMLinkIterator extends FOMElementIterator { public FOMLinkIterator(Element parent, Class<?> _class, QName attribute, String value, String defaultValue) { super(parent, _class, attribute, value != null ? FOMLink.getRelEquiv(value) : Link.REL_ALTERNATE, defaultValue); } public FOMLinkIterator(Element parent, Class<?> _class) { super(parent, _class); } protected boolean isMatch(Element el) { if (attribute != null) { String val = FOMLink.getRelEquiv(el.getAttributeValue(attribute)); return ((val == null && value == null) || (val == null && value != null && value .equalsIgnoreCase(defaultValue)) || (val != null && val.equalsIgnoreCase(value))); } return true; } }
7,490
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/util/FOMXmlRestrictedCharReader.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.parser.stax.util; import java.io.InputStream; import java.io.Reader; import java.io.UnsupportedEncodingException; import org.apache.abdera.util.XmlRestrictedCharReader; import org.apache.abdera.util.XmlUtil; public final class FOMXmlRestrictedCharReader extends XmlRestrictedCharReader { public FOMXmlRestrictedCharReader(Reader in) { this(new FOMXmlVersionReader(in)); } public FOMXmlRestrictedCharReader(FOMXmlVersionReader in) { super(in, XmlUtil.getVersion(in.getVersion())); } public FOMXmlRestrictedCharReader(Reader in, char replacement) { this(new FOMXmlVersionReader(in), replacement); } public FOMXmlRestrictedCharReader(FOMXmlVersionReader in, char replacement) { super(in, XmlUtil.getVersion(in.getVersion()), replacement); } public FOMXmlRestrictedCharReader(InputStream in) { this(new FOMXmlVersionInputStream(in)); } public FOMXmlRestrictedCharReader(FOMXmlVersionInputStream in) { super(in, XmlUtil.getVersion(in.getVersion())); } public FOMXmlRestrictedCharReader(InputStream in, char replacement) { this(new FOMXmlVersionInputStream(in), replacement); } public FOMXmlRestrictedCharReader(FOMXmlVersionInputStream in, char replacement) { super(in, XmlUtil.getVersion(in.getVersion()), replacement); } public FOMXmlRestrictedCharReader(InputStream in, String charset) throws UnsupportedEncodingException { this(new FOMXmlVersionInputStream(in), charset); } public FOMXmlRestrictedCharReader(FOMXmlVersionInputStream in, String charset) throws UnsupportedEncodingException { super(in, charset, XmlUtil.getVersion(in.getVersion())); } public FOMXmlRestrictedCharReader(InputStream in, String charset, char replacement) throws UnsupportedEncodingException { this(new FOMXmlVersionInputStream(in), charset, replacement); } public FOMXmlRestrictedCharReader(FOMXmlVersionInputStream in, String charset, char replacement) throws UnsupportedEncodingException { super(in, charset, XmlUtil.getVersion(in.getVersion()), replacement); } }
7,491
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/util/FOMElementIterator.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.parser.stax.util; import javax.xml.namespace.QName; import org.apache.abdera.model.Element; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMNode; import org.apache.axiom.om.impl.traverse.OMFilterIterator; @SuppressWarnings("unchecked") public class FOMElementIterator extends OMFilterIterator { /** * Field givenQName */ protected QName attribute = null; protected String value = null; protected String defaultValue = null; protected Class _class = null; /** * Constructor OMChildrenQNameIterator. * * @param parent * @param givenQName */ public FOMElementIterator(Element parent, Class _class) { super(((OMElement)parent).getChildren()); this._class = _class; } public FOMElementIterator(Element parent, Class _class, QName attribute, String value, String defaultValue) { this(parent, _class); this.attribute = attribute; this.value = value; this.defaultValue = defaultValue; } @Override protected boolean matches(OMNode node) { return ((_class != null && _class.isAssignableFrom(node.getClass())) || _class == null) && isMatch((Element)node); } protected boolean isMatch(Element el) { if (attribute != null) { String val = el.getAttributeValue(attribute); return ((val == null && value == null) || (val == null && value != null && value.equals(defaultValue)) || (val != null && val .equals(value))); } return true; } }
7,492
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/util/FOMExtensionIterator.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.parser.stax.util; import org.apache.abdera.model.Element; import org.apache.abdera.parser.stax.FOMFactory; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMNode; import org.apache.axiom.om.impl.traverse.OMFilterIterator; import javax.xml.namespace.QName; public class FOMExtensionIterator extends OMFilterIterator { /** * Field givenQName */ private String namespace = null; private String extns = null; private FOMFactory factory = null; /** * Constructor OMChildrenQNameIterator. * * @param parent * @param givenQName */ public FOMExtensionIterator(OMElement parent) { super(parent.getChildren()); this.namespace = parent.getQName().getNamespaceURI(); this.factory = (FOMFactory)parent.getOMFactory(); } public FOMExtensionIterator(OMElement parent, String extns) { this(parent); this.extns = extns; } @Override public Object next() { return factory.getElementWrapper((Element)super.next()); } @Override protected boolean matches(OMNode node) { return (node instanceof OMElement) && (isQNamesMatch(((OMElement)node).getQName(), this.namespace)); } private boolean isQNamesMatch(QName elementQName, String namespace) { String elns = elementQName == null ? "" : elementQName.getNamespaceURI(); boolean namespaceURIMatch = (namespace == null) || (namespace == "") || elns.equals(namespace); if (!namespaceURIMatch && extns != null && !elns.equals(extns)) return false; else return !namespaceURIMatch; } }
7,493
0
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax
Create_ds/abdera/parser/src/main/java/org/apache/abdera/parser/stax/util/FOMElementIteratorWrapper.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.parser.stax.util; import java.util.Iterator; import org.apache.abdera.model.Element; import org.apache.abdera.parser.stax.FOMFactory; @SuppressWarnings("unchecked") public class FOMElementIteratorWrapper implements Iterator { private final Iterator<?> iterator; private final FOMFactory factory; public FOMElementIteratorWrapper(FOMFactory factory, Iterator<?> iterator) { this.iterator = iterator; this.factory = factory; } public boolean hasNext() { return iterator.hasNext(); } public Object next() { return factory.getElementWrapper((Element)iterator.next()); } public void remove() { iterator.remove(); } }
7,494
0
Create_ds/abdera/extensions/serializer/src/test/java/org/apache/abdera/test/ext
Create_ds/abdera/extensions/serializer/src/test/java/org/apache/abdera/test/ext/serializer/SerializerTest.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.ext.serializer; import static org.junit.Assert.assertEquals; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.Calendar; import java.util.Date; import org.apache.abdera.Abdera; import org.apache.abdera.ext.serializer.ConventionSerializationContext; import org.apache.abdera.ext.serializer.annotation.Author; import org.apache.abdera.ext.serializer.annotation.ID; import org.apache.abdera.ext.serializer.annotation.Link; import org.apache.abdera.ext.serializer.annotation.Published; import org.apache.abdera.ext.serializer.annotation.Summary; import org.apache.abdera.ext.serializer.annotation.Title; import org.apache.abdera.ext.serializer.annotation.Updated; import org.apache.abdera.ext.serializer.impl.EntrySerializer; import org.apache.abdera.model.Document; import org.apache.abdera.model.Entry; import org.apache.abdera.writer.StreamWriter; import org.junit.Test; public class SerializerTest { static Date date_now = new Date(); static Calendar cal_now = Calendar.getInstance(); @Test public void testSimple() throws Exception { Abdera abdera = Abdera.getInstance(); StreamWriter sw = abdera.newStreamWriter(); ByteArrayOutputStream out = new ByteArrayOutputStream(); sw.setOutputStream(out).setAutoIndent(true); ConventionSerializationContext c = new ConventionSerializationContext(sw); c.setSerializer(MyEntry.class, new EntrySerializer()); sw.startDocument(); c.serialize(new MyEntry()); sw.endDocument(); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); Document<Entry> doc = abdera.getParser().parse(in); Entry entry = doc.getRoot(); assertEquals("tag:example.org,2008:foo", entry.getId().toString()); assertEquals("This is the title", entry.getTitle()); assertEquals(date_now, entry.getUpdated()); assertEquals(cal_now.getTime(), entry.getPublished()); assertEquals("James", entry.getAuthor().getName()); assertEquals("this is the summary", entry.getSummary()); assertEquals("http://example.org/foo", entry.getAlternateLink().getResolvedHref().toString()); } public static class MyEntry { public String getId() { return "tag:example.org,2008:foo"; } public String getTitle() { return "This is the title"; } public String getAuthor() { return "James"; } public Date getUpdated() { return date_now; } public Calendar getPublished() { return cal_now; } public String getSummary() { return "this is the summary"; } public String getLink() { return "http://example.org/foo"; } } @Test public void testAnnotated() throws Exception { Abdera abdera = Abdera.getInstance(); StreamWriter sw = abdera.newStreamWriter(); ByteArrayOutputStream out = new ByteArrayOutputStream(); sw.setOutputStream(out).setAutoIndent(true); ConventionSerializationContext c = new ConventionSerializationContext(sw); sw.startDocument(); c.serialize(new MyAnnotatedEntry()); sw.endDocument(); ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray()); Document<Entry> doc = abdera.getParser().parse(in); Entry entry = doc.getRoot(); assertEquals("tag:example.org,2008:foo", entry.getId().toString()); assertEquals("This is the title", entry.getTitle()); assertEquals(date_now, entry.getUpdated()); assertEquals(date_now, entry.getPublished()); assertEquals("James", entry.getAuthor().getName()); assertEquals("this is the summary", entry.getSummary()); assertEquals("http://example.org/foo", entry.getAlternateLink().getResolvedHref().toString()); } @org.apache.abdera.ext.serializer.annotation.Entry public static class MyAnnotatedEntry { @ID public String getFoo() { return "tag:example.org,2008:foo"; } @Title public String getBar() { return "This is the title"; } @Author public String getBaz() { return "James"; } @Updated @Published public Date getLastModified() { return date_now; } @Summary public String getText() { return "this is the summary"; } @Link public String getUri() { return "http://example.org/foo"; } } }
7,495
0
Create_ds/abdera/extensions/serializer/src/test/java/org/apache/abdera/test/ext
Create_ds/abdera/extensions/serializer/src/test/java/org/apache/abdera/test/ext/serializer/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.ext.serializer; import org.junit.internal.TextListener; import org.junit.runner.JUnitCore; public class TestSuite { public static void main(String[] args) { JUnitCore runner = new JUnitCore(); runner.addListener(new TextListener(System.out)); runner.run(SerializerTest.class); } }
7,496
0
Create_ds/abdera/extensions/serializer/src/main/java/org/apache/abdera/ext
Create_ds/abdera/extensions/serializer/src/main/java/org/apache/abdera/ext/serializer/DefaultSerializationContext.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.ext.serializer; import java.util.Map; import org.apache.abdera.Abdera; import org.apache.abdera.util.Discover; import org.apache.abdera.writer.StreamWriter; @SuppressWarnings("unchecked") public class DefaultSerializationContext extends AbstractSerializationContext { private static final long serialVersionUID = 740460842415905883L; private final Iterable<SerializerProvider> providers; public DefaultSerializationContext(StreamWriter streamWriter) { super(streamWriter); providers = loadConverterProviders(); initSerializers(); } public DefaultSerializationContext(Abdera abdera, StreamWriter streamWriter) { super(abdera, streamWriter); providers = loadConverterProviders(); initSerializers(); } private void initSerializers() { Iterable<SerializerProvider> providers = getConverterProviders(); for (SerializerProvider provider : providers) { for (Map.Entry<Class, Serializer> entry : provider) { setSerializer(entry.getKey(), entry.getValue()); } } } /** * Returns the listing of registered ConverterProvider implementations */ public Iterable<SerializerProvider> getConverterProviders() { return providers; // return providers != null ? // providers.toArray( // new SerializerProvider[providers.size()]) : // new SerializerProvider[0]; } protected static synchronized Iterable<SerializerProvider> loadConverterProviders() { Iterable<SerializerProvider> providers = Discover.locate("org.apache.abdera.converter.ConverterProvider"); // ServiceUtil.loadimpls( // "META-INF/services/org.apache.abdera.converter.ConverterProvider"); return providers; } }
7,497
0
Create_ds/abdera/extensions/serializer/src/main/java/org/apache/abdera/ext
Create_ds/abdera/extensions/serializer/src/main/java/org/apache/abdera/ext/serializer/Conventions.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.ext.serializer; import java.io.Serializable; import java.lang.annotation.Annotation; import java.lang.reflect.AccessibleObject; public interface Conventions extends Serializable, Cloneable, Iterable<Class<? extends Annotation>> { void setConvention(Class<? extends Annotation> annotationType); void setConvention(String pattern, Class<? extends Annotation> annotationType); Class<? extends Annotation> matchConvention(AccessibleObject accessor); Class<? extends Annotation> matchConvention(AccessibleObject accessor, Class<? extends Annotation> expect); boolean isMatch(AccessibleObject accessor, Class<? extends Annotation> expect); Conventions clone(); }
7,498
0
Create_ds/abdera/extensions/serializer/src/main/java/org/apache/abdera/ext
Create_ds/abdera/extensions/serializer/src/main/java/org/apache/abdera/ext/serializer/ObjectResponseContext.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.ext.serializer; import java.io.IOException; import java.lang.reflect.AccessibleObject; import java.util.Calendar; import java.util.Date; import org.apache.abdera.Abdera; import org.apache.abdera.ext.serializer.annotation.EntityTag; import org.apache.abdera.ext.serializer.annotation.LastModified; import org.apache.abdera.ext.serializer.annotation.MediaType; import org.apache.abdera.model.AtomDate; import org.apache.abdera.protocol.server.context.StreamWriterResponseContext; import org.apache.abdera.writer.StreamWriter; public class ObjectResponseContext extends StreamWriterResponseContext { private final Object object; private final ObjectContext objectContext; private final Conventions conventions; private final Class<? extends SerializationContext> context; public ObjectResponseContext(Object object, Abdera abdera, String encoding, String sw) { this(object, null, null, abdera, encoding, sw); } public ObjectResponseContext(Object object, Class<? extends SerializationContext> context, Conventions conventions, Abdera abdera, String encoding, String sw) { super(abdera, encoding, sw); this.object = object; this.objectContext = new ObjectContext(object); this.conventions = conventions != null ? conventions : new DefaultConventions(); this.context = context != null ? context : ConventionSerializationContext.class; init(); } public ObjectResponseContext(Object object, Abdera abdera, String encoding) { this(object, null, null, abdera, encoding, null); } public ObjectResponseContext(Object object, Class<? extends SerializationContext> context, Conventions conventions, Abdera abdera, String encoding) { this(object, context, conventions, abdera, encoding, null); } public ObjectResponseContext(Object object, Abdera abdera) { this(object, null, null, abdera, null, null); } public ObjectResponseContext(Object object, Class<? extends SerializationContext> context, Conventions conventions, Abdera abdera) { this(object, context, null, abdera, null, null); } private void init() { setContentType(getObjectContentType()); setEntityTag(getObjectEntityTag()); setLastModified(getObjectLastModified()); } private Date getObjectLastModified() { Date date = null; AccessibleObject accessor = objectContext.getAccessor(LastModified.class, conventions); if (accessor != null) { Object value = BaseSerializer.eval(accessor, object); date = getDate(value); } return date; } private Date getDate(Object value) { Date date = null; if (value == null) return null; if (value instanceof Date) { date = (Date)value; } else if (value instanceof Calendar) { date = ((Calendar)value).getTime(); } else if (value instanceof Long) { date = new Date(((Long)value).longValue()); } else if (value instanceof String) { date = AtomDate.parse((String)value); } else { date = AtomDate.parse(value.toString()); } return date; } private String getObjectEntityTag() { String etag = null; AccessibleObject accessor = objectContext.getAccessor(EntityTag.class, conventions); if (accessor != null) { Object value = BaseSerializer.eval(accessor, object); etag = value != null ? BaseSerializer.toString(value) : null; } return etag; } private String getObjectContentType() { String ctype = null; AccessibleObject accessor = objectContext.getAccessor(MediaType.class, conventions); if (accessor != null) { Object value = BaseSerializer.eval(accessor, object); ctype = value != null ? BaseSerializer.toString(value) : null; } if (ctype == null) { MediaType content_type = objectContext.getAnnotation(MediaType.class); if (content_type != null && !content_type.value().equals(BaseSerializer.DEFAULT)) { ctype = content_type.value(); } } return ctype; } @Override protected void writeTo(StreamWriter sw) throws IOException { SerializationContext context = newSerializationContext(getAbdera(), conventions, sw); sw.startDocument(); context.serialize(object, objectContext); sw.endDocument(); } private SerializationContext newSerializationContext(Abdera abdera, Conventions conventions, StreamWriter sw) { try { return context.getConstructor(Abdera.class, Conventions.class, StreamWriter.class).newInstance(abdera, conventions, sw); } catch (Exception e) { throw new RuntimeException(e); } } }
7,499