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/extensions/media/src/main/java/org/apache/abdera/ext | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext/media/MediaRating.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.media;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.Element;
import org.apache.abdera.model.ElementWrapper;
import org.apache.abdera.i18n.iri.IRI;
public class MediaRating extends ElementWrapper {
public MediaRating(Element internal) {
super(internal);
}
public MediaRating(Factory factory) {
super(factory, MediaConstants.RATING);
}
public IRI getScheme() {
String scheme = getAttributeValue("scheme");
return (scheme != null) ? new IRI(scheme) : null;
}
public void setScheme(String scheme) {
setAttributeValue("scheme", (new IRI(scheme)).toString());
}
public void setAdult(boolean adult) {
try {
setScheme("urn:simple");
setText(adult ? "adult" : "nonadult");
} catch (Exception e) {
}
}
public boolean isAdult() {
String scheme = getAttributeValue("scheme");
String text = getText();
return scheme.equals("urn:simple") && "adult".equalsIgnoreCase(text);
}
}
| 7,700 |
0 | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext/media/MediaAdult.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.media;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.Element;
import org.apache.abdera.model.ElementWrapper;
/**
* @deprecated Use MediaRating instead
*/
public class MediaAdult extends ElementWrapper {
protected MediaAdult(Element internal) {
super(internal);
}
public MediaAdult(Factory factory) {
super(factory, MediaConstants.ADULT);
}
}
| 7,701 |
0 | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext/media/MediaExtensionFactory.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.media;
import org.apache.abdera.util.AbstractExtensionFactory;
public final class MediaExtensionFactory extends AbstractExtensionFactory implements MediaConstants {
@SuppressWarnings("deprecation")
public MediaExtensionFactory() {
super(MediaConstants.MEDIA_NS);
addImpl(ADULT, MediaAdult.class);
addImpl(CATEGORY, MediaCategory.class);
addImpl(CONTENT, MediaContent.class);
addImpl(COPYRIGHT, MediaCopyright.class);
addImpl(CREDIT, MediaCredit.class);
addImpl(DESCRIPTION, MediaDescription.class);
addImpl(GROUP, MediaGroup.class);
addImpl(HASH, MediaHash.class);
addImpl(KEYWORDS, MediaKeywords.class);
addImpl(PLAYER, MediaPlayer.class);
addImpl(RATING, MediaRating.class);
addImpl(RESTRICTION, MediaRestriction.class);
addImpl(TEXT, MediaText.class);
addImpl(THUMBNAIL, MediaThumbnail.class);
addImpl(TITLE, MediaTitle.class);
}
}
| 7,702 |
0 | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext/media/MediaConstants.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.media;
import javax.xml.namespace.QName;
public interface MediaConstants {
public enum Type {
PLAIN, HTML
}
public enum Algo {
SHA1, MD5
}
public enum Relationship {
ALLOW, DENY
}
public enum RestrictionType {
COUNTRY, URI
}
public enum Medium {
IMAGE, AUDIO, VIDEO, DOCUMENT, EXECUTABLE
}
public enum Expression {
FULL, SAMPLE, NONSTOP
}
public static final String MEDIA_NS = "http://search.yahoo.com/mrss/";
public static final String MEDIA_PREFIX = "media";
public static final String LN_GROUP = "group";
public static final String LN_CONTENT = "content";
public static final String LN_ADULT = "adult";
public static final String LN_RATING = "rating";
public static final String LN_TITLE = "title";
public static final String LN_DESCRIPTION = "description";
public static final String LN_KEYWORDS = "keywords";
public static final String LN_THUMBNAIL = "thumbnail";
public static final String LN_CATEGORY = "category";
public static final String LN_HASH = "hash";
public static final String LN_PLAYER = "player";
public static final String LN_CREDIT = "credit";
public static final String LN_COPYRIGHT = "copyright";
public static final String LN_TEXT = "text";
public static final String LN_RESTRICTION = "restriction";
public static final QName GROUP = new QName(MEDIA_NS, LN_GROUP, MEDIA_PREFIX);
public static final QName CONTENT = new QName(MEDIA_NS, LN_CONTENT, MEDIA_PREFIX);
public static final QName ADULT = new QName(MEDIA_NS, LN_ADULT, MEDIA_PREFIX);
public static final QName RATING = new QName(MEDIA_NS, LN_RATING, MEDIA_PREFIX);
public static final QName TITLE = new QName(MEDIA_NS, LN_TITLE, MEDIA_PREFIX);
public static final QName DESCRIPTION = new QName(MEDIA_NS, LN_DESCRIPTION, MEDIA_PREFIX);
public static final QName KEYWORDS = new QName(MEDIA_NS, LN_KEYWORDS, MEDIA_PREFIX);
public static final QName THUMBNAIL = new QName(MEDIA_NS, LN_THUMBNAIL, MEDIA_PREFIX);
public static final QName CATEGORY = new QName(MEDIA_NS, LN_CATEGORY, MEDIA_PREFIX);
public static final QName HASH = new QName(MEDIA_NS, LN_HASH, MEDIA_PREFIX);
public static final QName PLAYER = new QName(MEDIA_NS, LN_PLAYER, MEDIA_PREFIX);
public static final QName CREDIT = new QName(MEDIA_NS, LN_CREDIT, MEDIA_PREFIX);
public static final QName COPYRIGHT = new QName(MEDIA_NS, LN_COPYRIGHT, MEDIA_PREFIX);
public static final QName TEXT = new QName(MEDIA_NS, LN_TEXT, MEDIA_PREFIX);
public static final QName RESTRICTION = new QName(MEDIA_NS, LN_RESTRICTION, MEDIA_PREFIX);
}
| 7,703 |
0 | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext/media/MediaText.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.media;
import javax.xml.namespace.QName;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.Element;
import org.apache.abdera.model.ElementWrapper;
public class MediaText extends ElementWrapper {
public MediaText(Element internal) {
super(internal);
}
public MediaText(Factory factory) {
super(factory, MediaConstants.TEXT);
}
public void setType(MediaConstants.Type type) {
switch (type) {
case PLAIN:
setAttributeValue("type", "plain");
break;
case HTML:
setAttributeValue("type", "html");
break;
default:
removeAttribute(new QName("type"));
}
}
public MediaConstants.Type getType() {
String type = getAttributeValue("type");
return (type != null) ? MediaConstants.Type.valueOf(type.toUpperCase()) : null;
}
public String getLang() {
return getAttributeValue("lang");
}
public void setLang(String lang) {
if (lang != null)
setAttributeValue("lang", lang);
else
removeAttribute(new QName("lang"));
}
public String getStart() {
return getAttributeValue("start");
}
public void setStart(String start) {
if (start != null)
setAttributeValue("start", start);
else
removeAttribute(new QName("start"));
}
public String getEnd() {
return getAttributeValue("end");
}
public void setEnd(String end) {
if (end != null)
setAttributeValue("end", end);
else
removeAttribute(new QName("end"));
}
}
| 7,704 |
0 | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext/media/MediaCategory.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.media;
import javax.xml.namespace.QName;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.Element;
import org.apache.abdera.model.ElementWrapper;
import org.apache.abdera.i18n.iri.IRI;
public class MediaCategory extends ElementWrapper {
public MediaCategory(Element internal) {
super(internal);
}
public MediaCategory(Factory factory) {
super(factory, MediaConstants.CATEGORY);
}
public IRI getScheme() {
String scheme = getAttributeValue("scheme");
return (scheme != null) ? new IRI(scheme) : null;
}
public void setScheme(String scheme) {
if (scheme != null)
setAttributeValue("scheme", (new IRI(scheme)).toString());
else
removeAttribute(new QName("scheme"));
}
public String getLabel() {
return getAttributeValue("label");
}
public void setLabel(String label) {
if (label != null)
setAttributeValue("label", label);
else
removeAttribute(new QName("label"));
}
}
| 7,705 |
0 | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext/media/MediaDescription.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.media;
import javax.xml.namespace.QName;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.Element;
import org.apache.abdera.model.ElementWrapper;
public class MediaDescription extends ElementWrapper {
public MediaDescription(Element internal) {
super(internal);
}
public MediaDescription(Factory factory) {
super(factory, MediaConstants.DESCRIPTION);
}
public void setType(MediaConstants.Type type) {
switch (type) {
case PLAIN:
setAttributeValue("type", "plain");
break;
case HTML:
setAttributeValue("type", "html");
break;
default:
removeAttribute(new QName("type"));
}
}
public MediaConstants.Type getType() {
String type = getAttributeValue("type");
return (type != null) ? MediaConstants.Type.valueOf(type.toUpperCase()) : null;
}
}
| 7,706 |
0 | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext/media/MediaRestriction.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.media;
import javax.xml.namespace.QName;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.Element;
import org.apache.abdera.model.ElementWrapper;
public class MediaRestriction extends ElementWrapper {
public MediaRestriction(Element internal) {
super(internal);
}
public MediaRestriction(Factory factory) {
super(factory, MediaConstants.RESTRICTION);
}
public void setRelationship(MediaConstants.Relationship type) {
switch (type) {
case ALLOW:
setAttributeValue("relationship", "allow");
break;
case DENY:
setAttributeValue("relationship", "deny");
break;
default:
removeAttribute(new QName("relationship"));
}
}
public MediaConstants.Relationship getRelationship() {
String rel = getAttributeValue("relationship");
return (rel != null) ? MediaConstants.Relationship.valueOf(rel.toUpperCase()) : null;
}
public void setType(MediaConstants.RestrictionType type) {
switch (type) {
case COUNTRY:
setAttributeValue("type", "country");
break;
case URI:
setAttributeValue("type", "uri");
break;
default:
removeAttribute(new QName("type"));
}
}
public MediaConstants.RestrictionType getType() {
String type = getAttributeValue("type");
return (type != null) ? MediaConstants.RestrictionType.valueOf(type.toUpperCase()) : null;
}
}
| 7,707 |
0 | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext/media/MediaContent.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.media;
import javax.activation.MimeType;
import javax.xml.namespace.QName;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.Element;
import org.apache.abdera.model.ExtensibleElementWrapper;
import org.apache.abdera.i18n.iri.IRI;
public class MediaContent extends ExtensibleElementWrapper {
public MediaContent(Element internal) {
super(internal);
}
public MediaContent(Factory factory) {
super(factory, MediaConstants.CONTENT);
}
public IRI getUrl() {
String url = getAttributeValue("url");
return (url != null) ? new IRI(url) : null;
}
public void setUrl(String url) {
if (url != null)
setAttributeValue("url", (new IRI(url)).toString());
else
removeAttribute(new QName("url"));
}
public long getFilesize() {
String size = getAttributeValue("filesize");
return (size != null) ? Long.parseLong(size) : -1;
}
public void setFilesize(long size) {
if (size > -1)
setAttributeValue("filesize", String.valueOf(size));
else
removeAttribute(new QName("filesize"));
}
public MimeType getType() {
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 setType(String type) {
if (type != null)
setAttributeValue("type", type);
else
removeAttribute(new QName(type));
}
public MediaConstants.Medium getMedium() {
String medium = getAttributeValue("medium");
return (medium != null) ? MediaConstants.Medium.valueOf(medium.toUpperCase()) : null;
}
public void setMedium(MediaConstants.Medium medium) {
if (medium != null)
setAttributeValue("medium", medium.name().toLowerCase());
else
removeAttribute(new QName("medium"));
}
public boolean isDefault() {
String def = getAttributeValue("isDefault");
return (def != null) ? def.equalsIgnoreCase("true") : false;
}
public MediaConstants.Expression getExpression() {
String exp = getAttributeValue("expression");
return (exp != null) ? MediaConstants.Expression.valueOf(exp.toUpperCase()) : null;
}
public void setExpression(MediaConstants.Expression exp) {
if (exp != null)
setAttributeValue("expression", exp.name().toLowerCase());
else
removeAttribute(new QName("expression"));
}
public int getBitrate() {
String bitrate = getAttributeValue("bitrate");
return (bitrate != null) ? Integer.parseInt(bitrate) : -1;
}
public void setBitrate(int bitrate) {
if (bitrate > -1)
setAttributeValue("bitrate", String.valueOf(bitrate));
else
removeAttribute(new QName("bitrate"));
}
public int getFramerate() {
String framerate = getAttributeValue("framerate");
return (framerate != null) ? Integer.parseInt(framerate) : -1;
}
public void setFramerate(int framerate) {
if (framerate > -1)
setAttributeValue("framerate", String.valueOf(framerate));
else
removeAttribute(new QName("framerate"));
}
public double getSamplingRate() {
String rate = getAttributeValue("samplingrate");
return (rate != null) ? Double.parseDouble(rate) : -1;
}
public void setSamplingRate(double samplingrate) {
if (samplingrate > Double.parseDouble("-1"))
setAttributeValue("samplingrate", String.valueOf(samplingrate));
else
removeAttribute(new QName("samplingrate"));
}
public int getChannels() {
String c = getAttributeValue("channels");
return (c != null) ? Integer.parseInt(c) : -1;
}
public void setChannels(int channels) {
if (channels > -1)
setAttributeValue("channels", String.valueOf(channels));
else
removeAttribute(new QName("channels"));
}
public int getDuration() {
String c = getAttributeValue("duration");
return (c != null) ? Integer.parseInt(c) : -1;
}
public void setDuration(int duration) {
if (duration > -1)
setAttributeValue("duration", String.valueOf(duration));
else
removeAttribute(new QName("duration"));
}
public int getWidth() {
String width = getAttributeValue("width");
return (width != null) ? Integer.parseInt(width) : -1;
}
public void setWidth(int width) {
if (width > -1) {
setAttributeValue("width", String.valueOf(width));
} else {
removeAttribute(new QName("width"));
}
}
public int getHeight() {
String height = getAttributeValue("height");
return (height != null) ? Integer.parseInt(height) : -1;
}
public void setHeight(int height) {
if (height > -1) {
setAttributeValue("height", String.valueOf(height));
} else {
removeAttribute(new QName("height"));
}
}
public String getLang() {
return getAttributeValue("lang");
}
public void setLang(String lang) {
if (lang != null)
setAttributeValue("lang", lang);
else
removeAttribute(new QName("lang"));
}
}
| 7,708 |
0 | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext/media/MediaCredit.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.media;
import javax.xml.namespace.QName;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.Element;
import org.apache.abdera.model.ElementWrapper;
import org.apache.abdera.i18n.iri.IRI;
public class MediaCredit extends ElementWrapper {
public MediaCredit(Element internal) {
super(internal);
}
public MediaCredit(Factory factory) {
super(factory, MediaConstants.CREDIT);
}
public IRI getScheme() {
String scheme = getAttributeValue("scheme");
return (scheme != null) ? new IRI(scheme) : null;
}
public void setScheme(String scheme) {
if (scheme != null)
setAttributeValue("scheme", (new IRI(scheme)).toString());
else
removeAttribute(new QName("scheme"));
}
public String getRole() {
return getAttributeValue("role");
}
public void setRole(String role) {
if (role != null)
setAttributeValue("role", role);
else
removeAttribute(new QName("role"));
}
}
| 7,709 |
0 | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext/media/MediaHash.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.media;
import javax.xml.namespace.QName;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.Element;
import org.apache.abdera.model.ElementWrapper;
public class MediaHash extends ElementWrapper {
public MediaHash(Element internal) {
super(internal);
}
public MediaHash(Factory factory) {
super(factory, MediaConstants.HASH);
}
public MediaConstants.Algo getAlgorithm() {
String algo = getAttributeValue("algo");
if (algo == null)
return null;
if (algo.equalsIgnoreCase("sha-1"))
return MediaConstants.Algo.SHA1;
if (algo.equalsIgnoreCase("md5"))
return MediaConstants.Algo.MD5;
return null;
}
public void setAlgorithm(MediaConstants.Algo algorithm) {
switch (algorithm) {
case SHA1:
setAttributeValue("algo", "sha-1");
break;
case MD5:
setAttributeValue("algo", "md5");
break;
default:
removeAttribute(new QName("algo"));
}
}
// TODO: Helper methods for calculating the hash
}
| 7,710 |
0 | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext | Create_ds/abdera/extensions/media/src/main/java/org/apache/abdera/ext/media/MediaKeywords.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.media;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.Element;
import org.apache.abdera.model.ElementWrapper;
public class MediaKeywords extends ElementWrapper {
public MediaKeywords(Element internal) {
super(internal);
}
public MediaKeywords(Factory factory) {
super(factory, MediaConstants.KEYWORDS);
}
}
| 7,711 |
0 | Create_ds/abdera/adapters/hibernate/src/test/java/org/apache/abdera/protocol/server/adapters | Create_ds/abdera/adapters/hibernate/src/test/java/org/apache/abdera/protocol/server/adapters/hibernate/DummyData.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.adapters.hibernate;
import java.util.Date;
public class DummyData {
public DummyData(){}
private String id;
private String author;
private String title;
private String content;
private Date updated;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
}
| 7,712 |
0 | Create_ds/abdera/adapters/hibernate/src/test/java/org/apache/abdera/protocol/server/adapters | Create_ds/abdera/adapters/hibernate/src/test/java/org/apache/abdera/protocol/server/adapters/hibernate/HibernateCollectionAdapterTest.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.adapters.hibernate;
import java.util.Date;
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.protocol.Response.ResponseType;
import org.apache.abdera.protocol.client.AbderaClient;
import org.apache.abdera.protocol.client.ClientResponse;
import org.apache.abdera.protocol.server.ServiceManager;
import org.apache.abdera.protocol.server.provider.basic.BasicProvider;
import org.apache.abdera.protocol.server.servlet.AbderaServlet;
import org.apache.abdera.util.Constants;
import org.apache.abdera.util.MimeTypeHelper;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;
import static org.junit.Assert.*;
public class HibernateCollectionAdapterTest {
private static Server server;
private static Abdera abdera = Abdera.getInstance();
private static AbderaClient client = new AbderaClient();
@BeforeClass
public static void setUp() throws Exception {
if (server == null) {
server = new Server(9002);
Context context = new Context(server, "/", Context.SESSIONS);
ServletHolder servletHolder = new ServletHolder(new AbderaServlet());
servletHolder.setInitParameter(ServiceManager.PROVIDER, BasicProvider.class.getName());
context.addServlet(servletHolder, "/*");
server.start();
}
}
@AfterClass
public static void tearDown() throws Exception {
server.stop();
}
@Test
public void testGetFeed() {
ClientResponse resp = client.get("http://localhost:9002/hibernate");
assertNotNull(resp);
assertEquals(ResponseType.SUCCESS, resp.getType());
assertTrue(MimeTypeHelper.isMatch(resp.getContentType().toString(), Constants.ATOM_MEDIA_TYPE));
Document<Feed> doc = resp.getDocument();
Feed feed = doc.getRoot();
assertEquals("http://localhost:9002/hibernate", feed.getId().toString());
assertEquals("david", feed.getAuthor().getName());
assertEquals(0, feed.getEntries().size());
resp.release();
}
@Test
public void testCreateEntry() {
Entry entry = abdera.newEntry();
entry.setId("foo");
entry.setTitle("test entry");
entry.setContent("Test Content");
entry.addLink("http://example.org");
entry.setUpdated(new Date());
entry.addAuthor("david");
ClientResponse resp = client.post("http://localhost:9002/hibernate", entry);
assertNotNull(resp);
assertEquals(ResponseType.SUCCESS, resp.getType());
assertEquals(201, resp.getStatus());
assertEquals("http://localhost:9002/hibernate/foo", resp.getLocation().toString());
resp = client.get("http://localhost:9002/hibernate");
Document<Feed> feed_doc = resp.getDocument();
Feed feed = feed_doc.getRoot();
assertEquals(feed.getEntries().size(), 1);
resp.release();
}
@Test
public void testUpdateEntry() {
ClientResponse resp = client.get("http://localhost:9002/hibernate/foo");
Document<Entry> doc = resp.getDocument();
Entry entry = (Entry) doc.getRoot().clone();
entry.setTitle("This is the modified title");
resp.release();
resp = client.put("http://localhost:9002/hibernate/foo", entry);
assertEquals(ResponseType.SUCCESS, resp.getType());
assertEquals(200, resp.getStatus());
resp.release();
resp = client.get("http://localhost:9002/hibernate/foo");
doc = resp.getDocument();
entry = doc.getRoot();
assertEquals("This is the modified title", entry.getTitle());
resp.release();
resp = client.get("http://localhost:9002/hibernate");
Document<Feed> feed_doc = resp.getDocument();
Feed feed = feed_doc.getRoot();
assertEquals(1, feed.getEntries().size());
resp.release();
}
@Test
public void testDeleteEntry() {
ClientResponse resp = client.delete("http://localhost:9002/hibernate/foo");
assertEquals(ResponseType.SUCCESS, resp.getType());
resp.release();
resp = client.get("http://localhost:9002/hibernate");
Document<Feed> feed_doc = resp.getDocument();
Feed feed = feed_doc.getRoot();
assertEquals(0, feed.getEntries().size());
resp.release();
}
}
| 7,713 |
0 | Create_ds/abdera/adapters/hibernate/src/test/java/org/apache/abdera/protocol/server/adapters | Create_ds/abdera/adapters/hibernate/src/test/java/org/apache/abdera/protocol/server/adapters/hibernate/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.protocol.server.adapters.hibernate;
import org.junit.internal.runners.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(HibernateCollectionAdapterTest.class);
}
}
| 7,714 |
0 | Create_ds/abdera/adapters/hibernate/src/main/java/org/apache/abdera/protocol/server/adapters | Create_ds/abdera/adapters/hibernate/src/main/java/org/apache/abdera/protocol/server/adapters/hibernate/AtomEntryResultTransformer.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.adapters.hibernate;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.List;
import org.apache.abdera.Abdera;
import org.apache.abdera.ext.serializer.ConventionSerializationContext;
import org.apache.abdera.ext.serializer.impl.EntrySerializer;
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.ParseException;
import org.apache.abdera.protocol.server.ProviderHelper;
import org.apache.abdera.writer.StreamWriter;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.transform.ResultTransformer;
/**
* Converts Hibernate results into an Atom document using the Abdera Java Object Serializer
*/
public class AtomEntryResultTransformer implements ResultTransformer {
private static Log logger = LogFactory.getLog(AtomEntryResultTransformer.class);
private String feedId;
private Abdera abdera;
private Feed feed;
public AtomEntryResultTransformer(String feedId, Abdera abdera, Feed feed) {
this.feedId = feedId;
this.abdera = abdera;
this.feed = feed;
}
public List transformList(List collection) {
return collection;
}
public Object transformTuple(Object[] tuple, String[] aliases) {
try {
if (tuple.length == 1) {
StreamWriter sw = abdera.newStreamWriter();
ByteArrayOutputStream out = new ByteArrayOutputStream();
sw.setOutputStream(out).setAutoIndent(true);
ConventionSerializationContext c =
new ConventionSerializationContext(sw);
c.setSerializer(tuple[0].getClass(), new EntrySerializer());
sw.startDocument();
c.serialize(tuple[0]);
sw.endDocument();
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Document<Entry> doc = abdera.getParser().parse(in);
Entry entry = doc.getRoot();
if (ProviderHelper.getEditUriFromEntry(entry) == null) {
entry.addLink(entry.getId().toString(), "edit");
}
entry.setId(feedId + "/" + entry.getId().toString());
entry.getEditLink().setHref(entry.getId().toString());
if (feed != null) {
feed.addEntry(entry);
}
return entry;
} else {
return tuple;
}
} catch (Exception ex) {
logger.error("error creating an entry with the row data", ex);
throw new ParseException(ex);
}
}
}
| 7,715 |
0 | Create_ds/abdera/adapters/hibernate/src/main/java/org/apache/abdera/protocol/server/adapters | Create_ds/abdera/adapters/hibernate/src/main/java/org/apache/abdera/protocol/server/adapters/hibernate/HibernateCollectionAdapter.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.adapters.hibernate;
import static org.apache.abdera.protocol.server.provider.managed.FeedConfiguration.ENTRY_ELEM_NAME_AUTHOR;
import static org.apache.abdera.protocol.server.provider.managed.FeedConfiguration.ENTRY_ELEM_NAME_CONTENT;
import static org.apache.abdera.protocol.server.provider.managed.FeedConfiguration.ENTRY_ELEM_NAME_ID;
import static org.apache.abdera.protocol.server.provider.managed.FeedConfiguration.ENTRY_ELEM_NAME_TITLE;
import static org.apache.abdera.protocol.server.provider.managed.FeedConfiguration.ENTRY_ELEM_NAME_UPDATED;
import java.io.Serializable;
import java.lang.reflect.Field;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import org.apache.abdera.Abdera;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
import org.apache.abdera.protocol.server.provider.basic.BasicAdapter;
import org.apache.abdera.protocol.server.provider.managed.FeedConfiguration;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import org.hibernate.cfg.Environment;
/**
* An adapter implementation that uses Hibernate and a backend database to store
* Atompub collection entries. As an extension of the BasicAdapter, the adapter
* is intended to be used with the BasicProvider and is configured using an
* /abdera/adapter/*.properties file.
*/
public class HibernateCollectionAdapter extends BasicAdapter {
private static Log logger = LogFactory.getLog(HibernateCollectionAdapter.class);
protected static Configuration hibernateConfig;
protected static SessionFactory sessionFactory;
public static final String HIBERNATE_ANNOTATION_CONFIG = "hibernateAnnotationConfig";
public static final String HIBERNATE_CFG_PATH = "hibernateCfgPath";
public static final String ENTRY_MAPPING_CLASS_NAME = "entryMappingClassName";
public HibernateCollectionAdapter(Abdera abdera, FeedConfiguration config) {
super(abdera, config);
loadHibernateConfiguration();
}
private void loadHibernateConfiguration() {
if (hibernateConfig == null) {
if (config.hasProperty(HIBERNATE_ANNOTATION_CONFIG) &&
config.getProperty(HIBERNATE_ANNOTATION_CONFIG)
.toString().equalsIgnoreCase(Boolean.TRUE.toString())) {
hibernateConfig = new AnnotationConfiguration();
} else {
hibernateConfig = new Configuration();
}
if (config.hasProperty(HIBERNATE_CFG_PATH)) {
hibernateConfig.configure((String) config.getProperty(HIBERNATE_CFG_PATH));
} else {
hibernateConfig.configure();
}
rebuildSessionFactory(hibernateConfig);
}
}
protected SessionFactory getSessionFactory() {
String sfName = hibernateConfig.getProperty(Environment.SESSION_FACTORY_NAME);
if ( sfName != null) {
logger.debug("Looking up SessionFactory in JNDI");
try {
return (SessionFactory) new InitialContext().lookup(sfName);
} catch (NamingException ex) {
throw new RuntimeException(ex);
}
} else if (sessionFactory == null) {
rebuildSessionFactory(hibernateConfig);
}
return sessionFactory;
}
private void rebuildSessionFactory(Configuration cfg) {
logger.debug("Rebuilding the SessionFactory from given Configuration");
if (sessionFactory != null && !sessionFactory.isClosed())
sessionFactory.close();
if (cfg.getProperty(Environment.SESSION_FACTORY_NAME) != null) {
logger.debug("Managing SessionFactory in JNDI");
cfg.buildSessionFactory();
} else {
logger.debug("Holding SessionFactory in static variable");
sessionFactory = cfg.buildSessionFactory();
}
hibernateConfig = cfg;
}
@Override
public Entry createEntry(Entry entry) throws Exception {
Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Serializable entryId = null;
try {
Object mapping = collectMappingObject(entry, null);
entryId = session.save(mapping);
tx.commit();
} catch (Exception ex) {
tx.rollback();
logger.error("error creating a new entry", ex);
} finally {
session.close();
}
return getEntry(entryId);
}
@Override
public boolean deleteEntry(Object entryId) throws Exception {
Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
boolean deleted = false;
try {
Object mapping = session.load(
Class.forName((String) config.getProperty(ENTRY_MAPPING_CLASS_NAME)),
(Serializable) entryId);
if (mapping != null) {
session.delete(mapping);
tx.commit();
}
deleted = true;
} catch (HibernateException ex) {
tx.rollback();
logger.error("error deleting the entry", ex);
} finally {
session.close();
}
return deleted;
}
@Override
public Entry getEntry(Object entryId) throws Exception {
Session session = getSessionFactory().openSession();
Query query = session.getNamedQuery(config.getFeedId() + "-get-entry");
query.setParameter("id", entryId);
query.setResultTransformer(new AtomEntryResultTransformer(
config.getServerConfiguration().getServerUri() + "/" + config.getFeedId(), getAbdera(), null));
Entry entry = (Entry) query.uniqueResult();
session.close();
return entry;
}
@Override
public Feed getFeed() throws Exception {
Session session = getSessionFactory().openSession();
String queryName = config.getFeedId() + "-get-feed";
Query query = session.getNamedQuery(queryName);
Feed feed = createFeed();
query.setResultTransformer(new AtomEntryResultTransformer(
config.getServerConfiguration().getServerUri() + "/" + config.getFeedId(), this.getAbdera(), feed));
query.list();
session.close();
return feed;
}
@Override
public Entry updateEntry(Object entryId, Entry entry) throws Exception {
Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
try {
Object forUpdate = session.load(
Class.forName((String) config.getProperty(ENTRY_MAPPING_CLASS_NAME)),
(Serializable) entryId);
if (forUpdate != null) {
forUpdate = collectMappingObject(entry, forUpdate);
session.update(forUpdate);
tx.commit();
}
} catch (HibernateException ex) {
tx.rollback();
logger.error("error deleting the entry", ex);
} finally {
session.close();
}
return entry;
}
protected Object collectMappingObject(Entry entry, Object forUpdate) throws Exception {
boolean create = false;
Class clazz = Class.forName((String) config.getProperty(ENTRY_MAPPING_CLASS_NAME));
if (forUpdate == null) {
forUpdate = clazz.newInstance();
create = true;
}
for (Field field : clazz.getDeclaredFields()) {
if (create && field.getName().equals(ENTRY_ELEM_NAME_ID)) {
collectField(field, clazz, forUpdate, entry.getId().toString());
} else if (field.getName().equals(ENTRY_ELEM_NAME_AUTHOR)){
collectField(field, clazz, forUpdate, entry.getAuthor().getName());
} else if (field.getName().equals(ENTRY_ELEM_NAME_TITLE)) {
collectField(field, clazz, forUpdate, entry.getTitle());
} else if (field.getName().equals(ENTRY_ELEM_NAME_UPDATED)) {
collectField(field, clazz, forUpdate, entry.getUpdated());
} else if (field.getName().equals(ENTRY_ELEM_NAME_CONTENT)) {
collectField(field, clazz, forUpdate, entry.getContent());
}
}
return forUpdate;
}
protected void collectField(Field field, Class clazz, Object mappingObject, Object entryValue) throws Exception {
clazz.getMethod(getSetter(field.getName()), new Class[]{field.getType()})
.invoke(mappingObject, new Object[]{entryValue});
}
protected String getSetter(String fieldName) {
return "set" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
}
}
| 7,716 |
0 | Create_ds/abdera/adapters/filesystem/src/test/java/org/apache/abdera/protocol/server/test | Create_ds/abdera/adapters/filesystem/src/test/java/org/apache/abdera/protocol/server/test/filesystem/FilesystemTest.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.test.filesystem;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.Date;
import org.apache.abdera.Abdera;
import org.apache.abdera.model.Base;
import org.apache.abdera.model.Collection;
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.model.Workspace;
import org.apache.abdera.protocol.Response.ResponseType;
import org.apache.abdera.protocol.client.AbderaClient;
import org.apache.abdera.protocol.client.ClientResponse;
import org.apache.abdera.protocol.client.RequestOptions;
import org.apache.abdera.protocol.server.ServiceManager;
import org.apache.abdera.protocol.server.provider.basic.BasicProvider;
import org.apache.abdera.protocol.server.servlet.AbderaServlet;
import org.apache.abdera.util.Constants;
import org.apache.abdera.util.MimeTypeHelper;
import org.apache.abdera.writer.Writer;
import org.apache.abdera.writer.WriterFactory;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;
@Ignore
public class FilesystemTest {
private static Server server;
private static Abdera abdera = Abdera.getInstance();
private static AbderaClient client = new AbderaClient();
@BeforeClass
public static void setUp() throws Exception {
if (server == null) {
server = new Server(9002);
Context context = new Context(server, "/", Context.SESSIONS);
ServletHolder servletHolder = new ServletHolder(new AbderaServlet());
servletHolder.setInitParameter(ServiceManager.PROVIDER, BasicProvider.class.getName());
context.addServlet(servletHolder, "/*");
server.start();
}
}
@AfterClass
public static void tearDown() throws Exception {
server.stop();
}
protected void prettyPrint(Base doc) throws IOException {
WriterFactory factory = abdera.getWriterFactory();
Writer writer = factory.getWriter("prettyxml");
writer.writeTo(doc, System.out);
System.out.println();
}
@Test
public void testGetService() {
ClientResponse resp = client.get("http://localhost:9002/");
assertNotNull(resp);
assertEquals(ResponseType.SUCCESS, resp.getType());
assertTrue(MimeTypeHelper.isMatch(resp.getContentType().toString(), Constants.APP_MEDIA_TYPE));
Document<Service> doc = resp.getDocument();
Service service = doc.getRoot();
assertEquals(1, service.getWorkspaces().size());
Workspace workspace = service.getWorkspace("Abdera");
assertEquals(2, workspace.getCollections().size());
Collection collection = workspace.getCollection("Filesystem Feed");
assertNotNull(collection);
assertTrue(collection.acceptsEntry());
assertEquals("http://localhost:9002/fs", collection.getResolvedHref().toString());
}
@Test
public void testGetFeed() {
ClientResponse resp = client.get("http://localhost:9002/fs");
assertNotNull(resp);
assertEquals(ResponseType.SUCCESS, resp.getType());
assertTrue(MimeTypeHelper.isMatch(resp.getContentType().toString(), Constants.ATOM_MEDIA_TYPE));
Document<Feed> doc = resp.getDocument();
Feed feed = doc.getRoot();
assertEquals("http://localhost:9002/fs", feed.getId().toString());
assertEquals("Filesystem Feed", feed.getTitle());
assertEquals("james", feed.getAuthor().getName());
assertEquals(0, feed.getEntries().size());
resp.release();
}
@Test
public void testPostEntry() {
Entry entry = abdera.newEntry();
entry.setId("http://localhost:9002/fs/foo");
entry.setTitle("test entry");
entry.setContent("Test Content");
entry.addLink("http://example.org");
entry.setUpdated(new Date());
entry.addAuthor("James");
ClientResponse resp = client.post("http://localhost:9002/fs", entry);
assertNotNull(resp);
assertEquals(ResponseType.SUCCESS, resp.getType());
assertEquals(201, resp.getStatus());
assertEquals("http://localhost:9002/fs/test_entry", resp.getLocation().toString());
resp = client.get("http://localhost:9002/fs");
Document<Feed> feed_doc = resp.getDocument();
Feed feed = feed_doc.getRoot();
assertEquals(1, feed.getEntries().size());
resp.release();
}
@Test
public void testPostMedia() {
ByteArrayInputStream in = new ByteArrayInputStream(new byte[] {0x01, 0x02, 0x03, 0x04});
RequestOptions options = client.getDefaultRequestOptions();
options.setContentType("application/octet-stream");
ClientResponse resp = client.post("http://localhost:9002/fs", in, options);
assertEquals(ResponseType.CLIENT_ERROR, resp.getType());
assertEquals(415, resp.getStatus());
resp.release();
}
@Test
public void testPutEntry() {
ClientResponse resp = client.get("http://localhost:9002/fs/test_entry");
Document<Entry> doc = resp.getDocument();
Entry entry = (Entry)doc.getRoot().clone();
entry.setTitle("This is the modified title");
resp.release();
resp = client.put("http://localhost:9002/fs/test_entry", entry);
assertEquals(ResponseType.SUCCESS, resp.getType());
assertEquals(200, resp.getStatus());
resp.release();
resp = client.get("http://localhost:9002/fs/test_entry");
doc = resp.getDocument();
entry = doc.getRoot();
assertEquals("This is the modified title", entry.getTitle());
resp.release();
resp = client.get("http://localhost:9002/fs");
Document<Feed> feed_doc = resp.getDocument();
Feed feed = feed_doc.getRoot();
assertEquals(1, feed.getEntries().size());
resp.release();
}
@Test
public void testDeleteEntry() {
ClientResponse resp = client.delete("http://localhost:9002/fs/test_entry");
assertEquals(ResponseType.SUCCESS, resp.getType());
resp.release();
resp = client.get("http://localhost:9002/fs");
Document<Feed> feed_doc = resp.getDocument();
Feed feed = feed_doc.getRoot();
assertEquals(0, feed.getEntries().size());
resp.release();
}
}
| 7,717 |
0 | Create_ds/abdera/adapters/filesystem/src/test/java/org/apache/abdera/protocol/server/test | Create_ds/abdera/adapters/filesystem/src/test/java/org/apache/abdera/protocol/server/test/filesystem/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.protocol.server.test.filesystem;
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(FilesystemTest.class);
}
}
| 7,718 |
0 | Create_ds/abdera/adapters/filesystem/src/main/java/org/apache/abdera/protocol/server/adapters | Create_ds/abdera/adapters/filesystem/src/main/java/org/apache/abdera/protocol/server/adapters/filesystem/FilesystemAdapter.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.adapters.filesystem;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.abdera.Abdera;
import org.apache.abdera.i18n.templates.Template;
import org.apache.abdera.i18n.text.Normalizer;
import org.apache.abdera.i18n.text.Sanitizer;
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.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;
/**
* Simple Filesystem Adapter that uses a local directory to store Atompub collection entries. As an extension of the
* ManagedCollectionAdapter class, the Adapter is intended to be used with implementations of the ManagedProvider and
* are configured using /abdera/adapter/*.properties files. The *.properties file MUST specify the fs.root property to
* specify the root directory used by the Adapter.
*/
public class FilesystemAdapter extends ManagedCollectionAdapter {
private final File root;
private final static FileSorter sorter = new FileSorter();
private final static Template paging_template = new Template("?{-join|&|count,page}");
public FilesystemAdapter(Abdera abdera, FeedConfiguration config) {
super(abdera, config);
this.root = getRoot();
}
private File getRoot() {
try {
String root = (String)config.getProperty("fs.root");
File file = new File(root);
if (!file.exists())
file.mkdirs();
if (!file.isDirectory())
throw new RuntimeException("Root must be a directory");
return file;
} catch (Exception e) {
if (e instanceof RuntimeException)
throw (RuntimeException)e;
throw new RuntimeException(e);
}
}
private Entry getEntry(File entryFile) {
if (!entryFile.exists() || !entryFile.isFile())
throw new RuntimeException();
try {
FileInputStream fis = new FileInputStream(entryFile);
Document<Entry> doc = abdera.getParser().parse(fis);
Entry entry = doc.getRoot();
return entry;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void addPagingLinks(RequestContext request, Feed feed, int currentpage, int count) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("count", count);
params.put("page", currentpage + 1);
String next = paging_template.expand(params);
next = request.getResolvedUri().resolve(next).toString();
feed.addLink(next, "next");
if (currentpage > 0) {
params.put("page", currentpage - 1);
String prev = paging_template.expand(params);
prev = request.getResolvedUri().resolve(prev).toString();
feed.addLink(prev, "previous");
}
params.put("page", 0);
String current = paging_template.expand(params);
current = request.getResolvedUri().resolve(current).toString();
feed.addLink(current, "current");
}
private void getEntries(RequestContext request, Feed feed, File root) {
File[] files = root.listFiles();
Arrays.sort(files, sorter);
int length = ProviderHelper.getPageSize(request, "count", 25);
int offset = ProviderHelper.getOffset(request, "page", length);
String _page = request.getParameter("page");
int page = (_page != null) ? Integer.parseInt(_page) : 0;
addPagingLinks(request, feed, page, length);
if (offset > files.length)
return;
for (int n = offset; n < offset + length && n < files.length; n++) {
File file = files[n];
Entry entry = getEntry(file);
feed.addEntry((Entry)entry.clone());
}
}
public ResponseContext getFeed(RequestContext request) {
Feed feed = abdera.newFeed();
feed.setId(config.getServerConfiguration().getServerUri() + "/" + config.getFeedId());
feed.setTitle(config.getFeedTitle());
feed.addAuthor(config.getFeedAuthor());
feed.addLink(config.getFeedUri());
feed.addLink(config.getFeedUri(), "self");
feed.setUpdated(new Date());
getEntries(request, feed, root);
return ProviderHelper.returnBase(feed.getDocument(), 200, null);
}
public ResponseContext deleteEntry(RequestContext request) {
Target target = request.getTarget();
String key = target.getParameter("entry");
File file = getFile(key, false);
if (file.exists())
file.delete();
return ProviderHelper.nocontent();
}
public ResponseContext getEntry(RequestContext request) {
Target target = request.getTarget();
String key = target.getParameter("entry");
File file = getFile(key, false);
Entry entry = getEntry(file);
if (entry != null)
return ProviderHelper.returnBase(entry.getDocument(), 200, null);
else
return ProviderHelper.notfound(request);
}
public ResponseContext postEntry(RequestContext request) {
if (request.isAtom()) {
try {
Entry entry = (Entry)request.getDocument().getRoot().clone();
String key = createKey(request);
setEditDetail(request, entry, key);
File file = getFile(key);
FileOutputStream out = new FileOutputStream(file);
entry.writeTo(out);
String edit = entry.getEditLinkResolvedHref().toString();
return ProviderHelper.returnBase(entry.getDocument(), 201, null).setLocation(edit);
} catch (Exception e) {
return ProviderHelper.badrequest(request);
}
} else {
return ProviderHelper.notsupported(request);
}
}
private void setEditDetail(RequestContext request, Entry entry, String key) throws IOException {
Target target = request.getTarget();
String feed = target.getParameter("feed");
String id = key;
entry.setEdited(new Date());
Link link = entry.getEditLink();
Map<String, Object> params = new HashMap<String, Object>();
params.put("feed", feed);
params.put("entry", id);
String href = request.absoluteUrlFor("entry", params);
if (link == null) {
entry.addLink(href, "edit");
} else {
link.setHref(href);
}
}
private File getFile(String key) {
return getFile(key, true);
}
private File getFile(String key, boolean post) {
File file = new File(root, key);
if (post && file.exists())
throw new RuntimeException("File exists");
return file;
}
private String createKey(RequestContext request) throws IOException {
String slug = request.getSlug();
if (slug == null) {
slug = ((Entry)request.getDocument().getRoot()).getTitle();
}
return Sanitizer.sanitize(slug, "", true, Normalizer.Form.D);
}
public ResponseContext putEntry(RequestContext request) {
if (request.isAtom()) {
try {
Entry entry = (Entry)request.getDocument().getRoot().clone();
String key = request.getTarget().getParameter("entry");
setEditDetail(request, entry, key);
File file = getFile(key, false);
FileOutputStream out = new FileOutputStream(file);
entry.writeTo(out);
String edit = entry.getEditLinkResolvedHref().toString();
return ProviderHelper.returnBase(entry.getDocument(), 200, null).setLocation(edit);
} catch (Exception e) {
return ProviderHelper.badrequest(request);
}
} else {
return ProviderHelper.notsupported(request);
}
}
private static class FileSorter implements Comparator<File> {
public int compare(File o1, File o2) {
return o1.lastModified() > o2.lastModified() ? -1 : o1.lastModified() < o2.lastModified() ? 1 : 0;
}
}
}
| 7,719 |
0 | Create_ds/abdera/adapters/jdbc/src/main/java/org/apache/abdera/protocol/server/adapters | Create_ds/abdera/adapters/jdbc/src/main/java/org/apache/abdera/protocol/server/adapters/ibatis/IBatisCollectionAdapter.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.adapters.ibatis;
import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamConstants;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.apache.abdera.Abdera;
import org.apache.abdera.model.Content;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
import org.apache.abdera.protocol.server.provider.basic.BasicAdapter;
import org.apache.abdera.protocol.server.provider.managed.FeedConfiguration;
import org.apache.abdera.protocol.server.provider.managed.ServerConfiguration;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
/**
* Adapter that uses IBatis and a database to store Atompub collection entries. As an extension to BasicAdapter, the
* adapter is intended to be used with BasicProvider and is configured using /abdera/adapter/*.properties files.
*/
public class IBatisCollectionAdapter extends BasicAdapter {
// this class needs to be public - so that Adapter Manager can invoke it
// to create an instance of this adapter
public IBatisCollectionAdapter(Abdera abdera, FeedConfiguration config) {
super(abdera, config);
}
protected Map<String, SqlMapClient> sqlMapClients = new HashMap<String, SqlMapClient>();
protected SqlMapClient getSqlMapClient() throws Exception {
String dataSourceId = config.getFeedConfigLocation();
if (sqlMapClients.containsKey(dataSourceId)) {
return sqlMapClients.get(dataSourceId);
} else {
SqlMapClient client =
SqlMapClientBuilder.buildSqlMapClient(config.getAdapterConfiguration().getAdapterConfigAsReader());
sqlMapClients.put(dataSourceId, client);
return client;
}
}
@SuppressWarnings("unchecked")
public Feed getFeed() throws Exception {
SqlMapClient client = getSqlMapClient();
String queryId = config.getFeedId() + "-get-feed";
List<Map<String, Object>> rows = client.queryForList(queryId);
Feed feed = createFeed();
ServerConfiguration serverConfig = config.getServerConfiguration();
if (serverConfig.getFeedNamespacePrefix() != null && serverConfig.getFeedNamespacePrefix().length() > 0) {
feed.declareNS(serverConfig.getFeedNamespace(), serverConfig.getFeedNamespacePrefix());
}
for (Map<String, Object> row : rows)
createEntryFromRow(feed, row);
return feed;
}
@SuppressWarnings("unchecked")
public Entry getEntry(Object entryId) throws Exception {
String queryId = config.getFeedId() + "-get-entry";
SqlMapClient client = getSqlMapClient();
Map<String, Object> row = (Map<String, Object>)client.queryForObject(queryId, entryId);
if (row == null) {
// didn't find the entry.
return null;
}
return createEntryFromRow(null, row);
}
public Entry createEntry(Entry entry) throws Exception {
SqlMapClient client = getSqlMapClient();
String queryId = config.getFeedId() + "-insert-entry";
Object newEntryId = client.insert(queryId, collectColumns(entry));
return getEntry(newEntryId);
}
public Entry updateEntry(Object entryId, Entry entry) throws Exception {
SqlMapClient client = getSqlMapClient();
String queryId = config.getFeedId() + "-update-entry";
return client.update(queryId, collectColumns(entry)) > 0 ? getEntry(entryId) : null;
}
public boolean deleteEntry(Object entryId) throws Exception {
String queryId = config.getFeedId() + "-delete-entry";
SqlMapClient client = getSqlMapClient();
return client.delete(queryId, entryId) > 0;
}
protected Entry createEntryFromRow(Feed feed, Map<String, Object> row) throws Exception {
Entry entry = feed != null ? feed.addEntry() : abdera.newEntry();
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.newDocument();
Element entity = doc.createElement("entity");
doc.appendChild(entity);
for (String columnName : row.keySet()) {
if (row.get(columnName) == null) {
continue;
}
Object value = row.get(columnName);
if (FeedConfiguration.ENTRY_ELEM_NAME_ID.equals(columnName)) {
entry.setId(createEntryIdUri(value.toString()));
} else if (FeedConfiguration.ENTRY_ELEM_NAME_TITLE.equals(columnName)) {
entry.setTitle(value.toString());
} else if (FeedConfiguration.ENTRY_ELEM_NAME_AUTHOR.equals(columnName)) {
entry.addAuthor(value.toString());
} else if (FeedConfiguration.ENTRY_ELEM_NAME_UPDATED.equals(columnName) && value instanceof java.util.Date) {
entry.setUpdated((Date)value);
} else if (FeedConfiguration.ENTRY_ELEM_NAME_LINK.equals(columnName)) {
entry.addLink(value.toString());
} else {
Element node = doc.createElement(columnName);
node.appendChild(doc.createTextNode(value.toString()));
entity.appendChild(node);
}
}
if (entry.getUpdated() == null) {
entry.setUpdated(new Date());
}
if (entry.getAuthor() == null) {
entry.addAuthor(config.getFeedAuthor());
}
if (entry.getTitle() == null) {
entry.setTitle((String)config.getProperty(FeedConfiguration.PROP_ENTRY_TITLE_NAME));
}
entry.setContent(getDocumentAsXml(doc), "text/xml");
addEditLinkToEntry(entry);
return entry;
}
public static String getDocumentAsXml(Document doc) throws TransformerConfigurationException, TransformerException {
DOMSource domSource = new DOMSource(doc);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
java.io.StringWriter sw = new java.io.StringWriter();
StreamResult sr = new StreamResult(sw);
transformer.transform(domSource, sr);
String str = sw.toString();
logger.finest(str);
return str;
}
protected Map<String, Object> collectColumns(Entry entry) throws Exception {
Map<String, Object> columns = new HashMap<String, Object>();
if (entry.getId() != null) {
columns.put(FeedConfiguration.ENTRY_ELEM_NAME_ID, entry.getId().toString());
}
if (entry.getAuthor() != null) {
columns.put(FeedConfiguration.ENTRY_ELEM_NAME_AUTHOR, entry.getAuthor().getText());
}
if (entry.getTitle() != null) {
columns.put(FeedConfiguration.ENTRY_ELEM_NAME_TITLE, entry.getTitle());
}
if (entry.getUpdated() != null) {
columns.put(FeedConfiguration.ENTRY_ELEM_NAME_UPDATED, entry.getUpdated());
}
Content content = entry.getContentElement();
if (content != null) {
String contentStr = content.getValue();
parseContent(contentStr, columns);
}
return columns;
}
static void parseContent(String str, Map<String, Object> columns) throws Exception {
ByteArrayInputStream inStr = new ByteArrayInputStream(str.getBytes());
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader parser = factory.createXMLStreamReader(inStr);
while (true) {
int event = parser.next();
if (event == XMLStreamConstants.END_DOCUMENT) {
parser.close();
break;
}
if (event == XMLStreamConstants.START_ELEMENT) {
String name = parser.getLocalName();
int eventType = parser.next();
if (eventType == XMLStreamConstants.CHARACTERS) {
String value = parser.getText();
columns.put(name, value);
}
}
}
}
}
| 7,720 |
0 | Create_ds/abdera/adapters/jcr/src/test/java/org/apache/abdera | Create_ds/abdera/adapters/jcr/src/test/java/org/apache/abdera/jcr/JcrCollectionAdapterTest.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.jcr;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Repository;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import org.apache.abdera.Abdera;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.i18n.iri.IRI;
import org.apache.abdera.model.Base;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
import org.apache.abdera.model.Person;
import org.apache.abdera.protocol.client.AbderaClient;
import org.apache.abdera.protocol.client.ClientResponse;
import org.apache.abdera.protocol.client.RequestOptions;
import org.apache.abdera.protocol.server.Provider;
import org.apache.abdera.protocol.server.adapters.jcr.JcrCollectionAdapter;
import org.apache.abdera.protocol.server.impl.DefaultProvider;
import org.apache.abdera.protocol.server.impl.SimpleWorkspaceInfo;
import org.apache.abdera.protocol.server.servlet.AbderaServlet;
import org.apache.abdera.writer.Writer;
import org.apache.axiom.testutils.PortAllocator;
import org.apache.jackrabbit.core.TransientRepository;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;
public class JcrCollectionAdapterTest {
private int port;
private Server server;
private DefaultProvider jcrProvider;
private Repository repository;
@Before
public void setUp() throws Exception {
jcrProvider = new DefaultProvider();
repository = new TransientRepository();
JcrCollectionAdapter cp = new JcrCollectionAdapter();
cp.setTitle("My Entries");
cp.setAuthor("Apache Abdera");
cp.setCollectionNodePath("entries");
cp.setRepository(repository);
cp.setCredentials(new SimpleCredentials("username", "pass".toCharArray()));
cp.setHref("feed");
cp.initialize();
SimpleWorkspaceInfo wkspc = new SimpleWorkspaceInfo();
wkspc.setTitle("JCR Workspace");
wkspc.addCollection(cp);
jcrProvider.addWorkspace(wkspc);
initializeJetty();
}
@Test
public void testJCRAdapter() throws Exception {
Abdera abdera = new Abdera();
Factory factory = abdera.getFactory();
AbderaClient client = new AbderaClient(abdera);
String base = "http://localhost:" + port + "/";
// Testing of entry creation
IRI colUri = new IRI(base).resolve("feed");
Entry entry = factory.newEntry();
entry.setTitle("Some Entry");
entry.setUpdated(new Date());
entry.addAuthor("Dan Diephouse");
entry.setId(factory.newUuidUri());
entry.setSummary("This is my entry.");
entry.setContent("This is my entry. It's swell.");
RequestOptions opts = new RequestOptions();
opts.setContentType("application/atom+xml;type=entry");
ClientResponse res = client.post(colUri.toString(), entry, opts);
assertEquals(201, res.getStatus());
// prettyPrint(abdera, res.getDocument());
IRI location = res.getLocation();
assertEquals(base + "feed/Some_Entry", location.toString());
// GET the entry
res = client.get(location.toString());
assertEquals(200, res.getStatus());
// prettyPrint(abdera, res.getDocument());
org.apache.abdera.model.Document<Entry> entry_doc = res.getDocument();
Entry entry2 = entry_doc.getRoot();
assertEquals(entry.getTitle(), entry2.getTitle());
assertEquals(entry.getSummary(), entry2.getSummary());
assertEquals(entry.getContent(), entry2.getContent());
List<Person> authors = entry2.getAuthors();
assertEquals(1, authors.size());
entry = entry2;
entry.setSummary("New Summary");
entry.setContent("New Content");
res = client.put(location.toString(), entry, opts);
assertEquals(204, res.getStatus());
res = client.get(colUri.toString());
org.apache.abdera.model.Document<Feed> feed_doc = res.getDocument();
Feed feed = feed_doc.getRoot();
assertEquals(1, feed.getEntries().size());
// prettyPrint(abdera, feed_doc);
// test 404 not found
res = client.get(location.toString() + "Invalid");
assertEquals(404, res.getStatus());
}
protected void prettyPrint(Abdera abdera, Base doc) throws IOException {
Writer writer = abdera.getWriterFactory().getWriter("prettyxml");
writer.writeTo(doc, System.out);
System.out.println();
}
private void clearJcrRepository() {
try {
Session session = repository.login(new SimpleCredentials("username", "password".toCharArray()));
Node node = session.getRootNode();
for (NodeIterator itr = node.getNodes(); itr.hasNext();) {
Node child = itr.nextNode();
if (!child.getName().equals("jcr:system")) {
child.remove();
}
}
session.save();
session.logout();
} catch (PathNotFoundException t) {
} catch (Throwable t) {
t.printStackTrace();
}
}
private void initializeJetty() throws Exception {
port = PortAllocator.allocatePort();
server = new Server(port);
Context root = new Context(server, "/", Context.NO_SESSIONS);
root.addServlet(new ServletHolder(new AbderaServlet() {
@Override
protected Provider createProvider() {
jcrProvider.init(getAbdera(), getProperties(getServletConfig()));
return jcrProvider;
}
}), "/*");
server.start();
}
@After
public void tearDown() throws Exception {
clearJcrRepository();
if (server != null)
server.stop();
}
}
| 7,721 |
0 | Create_ds/abdera/adapters/jcr/src/main/java/org/apache/abdera/protocol/server/adapters | Create_ds/abdera/adapters/jcr/src/main/java/org/apache/abdera/protocol/server/adapters/jcr/SessionPoolManager.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.adapters.jcr;
import javax.jcr.Credentials;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import org.apache.abdera.protocol.Request;
import org.apache.abdera.protocol.util.AbstractItemManager;
public class SessionPoolManager extends AbstractItemManager<Session> {
private Repository repository;
private Credentials credentials;
public SessionPoolManager(int maxSize, Repository repository, Credentials credentials) {
super(maxSize);
this.repository = repository;
this.credentials = credentials;
}
@Override
protected Session internalNewInstance() {
try {
return repository.login(credentials);
} catch (RepositoryException e) {
throw new RuntimeException(e);
}
}
public Session get(Request request) {
return getInstance();
}
}
| 7,722 |
0 | Create_ds/abdera/adapters/jcr/src/main/java/org/apache/abdera/protocol/server/adapters | Create_ds/abdera/adapters/jcr/src/main/java/org/apache/abdera/protocol/server/adapters/jcr/JcrCollectionAdapter.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.adapters.jcr;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.activation.MimeType;
import javax.jcr.Credentials;
import javax.jcr.ItemExistsException;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.PathNotFoundException;
import javax.jcr.Property;
import javax.jcr.PropertyIterator;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.Value;
import javax.jcr.Workspace;
import org.apache.abdera.Abdera;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.i18n.iri.IRI;
import org.apache.abdera.i18n.text.Sanitizer;
import org.apache.abdera.model.Content;
import org.apache.abdera.model.Element;
import org.apache.abdera.model.Person;
import org.apache.abdera.model.Text;
import org.apache.abdera.model.Content.Type;
import org.apache.abdera.protocol.server.RequestContext;
import org.apache.abdera.protocol.server.ResponseContext;
import org.apache.abdera.protocol.server.RequestContext.Scope;
import org.apache.abdera.protocol.server.context.EmptyResponseContext;
import org.apache.abdera.protocol.server.context.ResponseContextException;
import org.apache.abdera.protocol.server.impl.AbstractEntityCollectionAdapter;
import org.apache.abdera.protocol.util.PoolManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.jackrabbit.api.JackrabbitNodeTypeManager;
/**
* Adapter implementation that uses a JCR Repository to store Atompub collection entries. The adapter is intended to be
* used with the DefaultProvider implementation.
*/
public class JcrCollectionAdapter extends AbstractEntityCollectionAdapter<Node> {
private final static Log log = LogFactory.getLog(JcrCollectionAdapter.class);
private static final String TITLE = "title";
private static final String SUMMARY = "summary";
private static final String UPDATED = "updated";
private static final String AUTHOR = "author";
private static final String AUTHOR_EMAIL = "author.email";
private static final String AUTHOR_LANGUAGE = "author.language";
private static final String AUTHOR_NAME = "author.name";
private static final String CONTENT = "content";
private static final String SESSION_KEY = "jcrSession";
private static final String MEDIA = "media";
private static final String CONTENT_TYPE = "contentType";
private static final String NAMESPACE = "http://abdera.apache.org";
private String collectionNodePath;
private String id;
private String title;
private String author;
private String collectionNodeId;
private Repository repository;
private Credentials credentials;
private int maxActiveSessions = 100;
private PoolManager<Session> sessionPool;
public void setCollectionNodePath(String collectionNodePath) {
this.collectionNodePath = collectionNodePath;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthor(String author) {
this.author = author;
}
/**
* Logs into the repository and posts a node for the collection if one does not exist. Also, this will set up the
* session pool.
*
* @throws RepositoryException
*/
public void initialize() throws Exception {
Session session = repository.login(credentials);
Node collectionNode = null;
try {
collectionNode = session.getRootNode().getNode(collectionNodePath);
} catch (PathNotFoundException e) {
collectionNode = session.getRootNode().addNode(collectionNodePath);
collectionNode.addMixin("mix:referenceable");
session.save();
}
this.collectionNodeId = collectionNode.getUUID();
this.id = "urn:" + collectionNodeId;
Workspace workspace = session.getWorkspace();
// Get the NodeTypeManager from the Workspace.
// Note that it must be cast from the generic JCR NodeTypeManager to the
// Jackrabbit-specific implementation.
JackrabbitNodeTypeManager jntmgr = (JackrabbitNodeTypeManager)workspace.getNodeTypeManager();
if (!jntmgr.hasNodeType("abdera:entry")) {
InputStream in = getClass().getResourceAsStream("/org/apache/abdera/jcr/nodeTypes.xml");
try {
// register the node types and any referenced namespaces
jntmgr.registerNodeTypes(in, JackrabbitNodeTypeManager.TEXT_XML);
} finally {
in.close();
}
}
session.logout();
sessionPool = new SessionPoolManager(maxActiveSessions, repository, credentials);
}
@Override
public void start(RequestContext request) throws ResponseContextException {
try {
Session session = (Session)sessionPool.get(request);
request.setAttribute(Scope.REQUEST, SESSION_KEY, session);
} catch (Exception e) {
throw new ResponseContextException(500, e);
}
}
@Override
public void end(RequestContext request, ResponseContext response) {
// Logout of the JCR session
Session session = getSession(request);
if (session != null) {
try {
sessionPool.release(session);
} catch (Exception e) {
log.warn("Could not return Session to pool!", e);
}
}
}
@Override
public String getContentType(Node entry) {
try {
return getStringOrNull(entry, CONTENT_TYPE);
} catch (ResponseContextException e) {
throw new UnsupportedOperationException();
}
}
@Override
public boolean isMediaEntry(Node entry) throws ResponseContextException {
try {
return entry.hasProperty(MEDIA);
} catch (RepositoryException e) {
throw new ResponseContextException(500, e);
}
}
@Override
public Node postMedia(MimeType mimeType, String slug, InputStream inputStream, RequestContext request)
throws ResponseContextException {
if (slug == null) {
throw new ResponseContextException("A slug header must be supplied.", 500);
}
Node n = postEntry(slug, null, null, new Date(), null, null, request);
try {
n.setProperty(MEDIA, inputStream);
n.setProperty(CONTENT_TYPE, mimeType.toString());
String summary = postSummaryForEntry(n);
if (summary != null) {
n.setProperty(SUMMARY, summary);
}
getSession(request).save();
return n;
} catch (RepositoryException e) {
try {
getSession(request).refresh(false);
} catch (Throwable t) {
log.warn(t);
}
throw new ResponseContextException(500, e);
}
}
/**
* post a summary for an entry. Used when a media entry is postd so you have the chance to post a meaningful summary
* for consumers of the feed.
*
* @param n
* @return
*/
protected String postSummaryForEntry(Node n) {
return null;
}
@Override
public Node postEntry(String title,
IRI id,
String summary,
Date updated,
List<Person> authors,
Content content,
RequestContext request) throws ResponseContextException {
Session session = getSession(request);
try {
Node collectionNode = session.getNodeByUUID(collectionNodeId);
String resourceName = Sanitizer.sanitize(title, "-");
return postEntry(title, summary, updated, authors, content, session, collectionNode, resourceName, 0);
} catch (RepositoryException e) {
try {
session.refresh(false);
} catch (Throwable t) {
log.warn(t);
}
throw new ResponseContextException(500, e);
}
}
protected Node postEntry(String title,
String summary,
Date updated,
List<Person> authors,
Content content,
Session session,
Node collectionNode,
String resourceName,
int num) throws ResponseContextException, RepositoryException {
try {
String name = resourceName;
if (num > 0) {
name = name + "_" + num;
}
Node entry = collectionNode.addNode(name, "abdera:entry");
entry.addMixin("mix:referenceable");
mapEntryToNode(entry, title, summary, updated, authors, content, session);
session.save();
return entry;
} catch (ItemExistsException e) {
return postEntry(title, summary, updated, authors, content, session, collectionNode, resourceName, ++num);
}
}
protected Node mapEntryToNode(Node entry,
String title,
String summary,
Date updated,
List<Person> authors,
Content content,
Session session) throws ResponseContextException, RepositoryException {
if (title == null) {
EmptyResponseContext ctx = new EmptyResponseContext(500);
ctx.setStatusText("Entry title cannot be empty.");
throw new ResponseContextException(ctx);
}
entry.setProperty(TITLE, title);
if (summary != null) {
entry.setProperty(SUMMARY, summary);
}
Calendar upCal = Calendar.getInstance();
upCal.setTime(updated);
entry.setProperty(UPDATED, upCal);
if (authors != null) {
for (Person p : authors) {
Node addNode = entry.addNode(AUTHOR);
addNode.setProperty(AUTHOR_EMAIL, p.getEmail());
addNode.setProperty(AUTHOR_LANGUAGE, p.getLanguage());
addNode.setProperty(AUTHOR_NAME, p.getName());
}
}
if (content != null) {
switch (content.getContentType()) {
case TEXT:
entry.setProperty(CONTENT, content.getText());
entry.setProperty(CONTENT_TYPE, Type.TEXT.toString());
break;
case XHTML:
entry.setProperty(CONTENT, asString(content));
entry.setProperty(CONTENT_TYPE, Type.XHTML.toString());
break;
default:
throw new ResponseContextException("Invalid content element type.", 500);
}
}
if (summary != null) {
entry.setProperty(SUMMARY, summary);
}
return entry;
}
private String asString(Content content2) throws ResponseContextException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
content2.<Element> getFirstChild().writeTo(bos);
} catch (IOException e) {
throw new ResponseContextException(500, e);
}
return new String(bos.toByteArray());
}
protected Session getSession(RequestContext request) {
return (Session)request.getAttribute(Scope.REQUEST, SESSION_KEY);
}
@Override
public void deleteEntry(String resourceName, RequestContext request) throws ResponseContextException {
Session session = getSession(request);
try {
getNode(session, resourceName).remove();
session.save();
} catch (RepositoryException e) {
try {
session.refresh(false);
} catch (Throwable t) {
log.warn(t);
}
throw new ResponseContextException(500, e);
}
}
private Node getNode(Session session, String resourceName) throws ResponseContextException, RepositoryException {
try {
return session.getNodeByUUID(collectionNodeId).getNode(resourceName);
} catch (PathNotFoundException e) {
throw new ResponseContextException(404);
}
}
/** Recursively outputs the contents of the given node. */
public static void dump(Node node) throws RepositoryException {
// First output the node path
System.out.println(node.getPath());
// Skip the virtual (and large!) jcr:system subtree
if (node.getName().equals("jcr:system")) {
return;
}
// Then output the properties
PropertyIterator properties = node.getProperties();
while (properties.hasNext()) {
Property property = properties.nextProperty();
if (property.getDefinition().isMultiple()) {
// A multi-valued property, print all values
Value[] values = property.getValues();
for (int i = 0; i < values.length; i++) {
System.out.println(property.getPath() + " = " + values[i].getString());
}
} else {
// A single-valued property
System.out.println(property.getPath() + " = " + property.getString());
}
}
// Finally output all the child nodes recursively
NodeIterator nodes = node.getNodes();
while (nodes.hasNext()) {
dump(nodes.nextNode());
}
}
@Override
public String getAuthor(RequestContext request) throws ResponseContextException {
return author;
}
@Override
public List<Person> getAuthors(Node entry, RequestContext request) throws ResponseContextException {
try {
ArrayList<Person> authors = new ArrayList<Person>();
for (NodeIterator nodes = entry.getNodes(); nodes.hasNext();) {
Node n = nodes.nextNode();
if (n.getName().equals(AUTHOR)) {
Person author = request.getAbdera().getFactory().newAuthor();
author.setName(getStringOrNull(entry, AUTHOR_NAME));
author.setEmail(getStringOrNull(entry, AUTHOR_EMAIL));
author.setLanguage(getStringOrNull(entry, AUTHOR_LANGUAGE));
authors.add(author);
}
}
return authors;
} catch (RepositoryException e) {
throw new ResponseContextException(500, e);
}
}
@Override
public Object getContent(Node entry, RequestContext request) throws ResponseContextException {
String typeStr = getStringOrNull(entry, CONTENT_TYPE);
Factory factory = Abdera.getInstance().getFactory();
String textContent = getStringOrNull(entry, CONTENT);
Type type = Type.valueOf(typeStr);
Content content = factory.newContent(type);
switch (type) {
case TEXT:
content.setValue(textContent);
return content;
case XHTML:
content.setWrappedValue(textContent);
return content;
default:
}
return null;
}
@Override
public Iterable<Node> getEntries(RequestContext request) throws ResponseContextException {
ArrayList<Node> entries = new ArrayList<Node>();
Session session = getSession(request);
try {
Node n = session.getNodeByUUID(collectionNodeId);
for (NodeIterator nodes = n.getNodes(); nodes.hasNext();) {
entries.add(nodes.nextNode());
}
} catch (RepositoryException e) {
throw new ResponseContextException(500, e);
}
return entries;
}
@Override
public Node getEntry(String resourceName, RequestContext request) throws ResponseContextException {
try {
return getNode(getSession(request), resourceName);
} catch (RepositoryException e) {
throw new ResponseContextException(500, e);
}
}
@Override
public String getId(RequestContext request) {
return id;
}
@Override
public String getId(Node entry) throws ResponseContextException {
try {
return "urn:" + entry.getUUID();
} catch (RepositoryException e) {
throw new ResponseContextException(500, e);
}
}
public String getMediaName(Node entry) throws ResponseContextException {
return getName(entry);
}
public InputStream getMediaStream(Node entry) throws ResponseContextException {
try {
Value value = getValueOrNull(entry, MEDIA);
return (value != null) ? value.getStream() : null;
} catch (RepositoryException e) {
throw new ResponseContextException(500, e);
}
}
@Override
public String getName(Node entry) throws ResponseContextException {
try {
return entry.getName();
} catch (RepositoryException e) {
throw new ResponseContextException(500, e);
}
}
@Override
public Text getSummary(Node entry, RequestContext request) throws ResponseContextException {
Text summary = request.getAbdera().getFactory().newSummary();
summary.setText(getStringOrNull(entry, SUMMARY));
return summary;
}
public String getTitle(RequestContext request) {
return title;
}
@Override
public String getTitle(Node entry) throws ResponseContextException {
return getStringOrNull(entry, TITLE);
}
@Override
public Date getUpdated(Node entry) throws ResponseContextException {
Calendar updated = getDateOrNull(entry, UPDATED);
return (updated != null) ? updated.getTime() : null;
}
@Override
public void putEntry(Node entry,
String title,
Date updated,
List<Person> authors,
String summary,
Content content,
RequestContext request) throws ResponseContextException {
Session session = getSession(request);
try {
mapEntryToNode(entry, title, summary, updated, authors, content, session);
} catch (RepositoryException e) {
throw new ResponseContextException(500, e);
}
}
public static String getStringOrNull(Node node, String propName) throws ResponseContextException {
try {
Value v = getValueOrNull(node, propName);
return (v != null) ? v.getString() : null;
} catch (RepositoryException e) {
throw new ResponseContextException(500, e);
}
}
public ResponseContext getCategories(RequestContext request) {
return null;
}
public static Calendar getDateOrNull(Node node, String propName) throws ResponseContextException {
try {
Value v = getValueOrNull(node, propName);
return (v != null) ? v.getDate() : null;
} catch (RepositoryException e) {
throw new ResponseContextException(500, e);
}
}
public static Value getValueOrNull(Node node, String propName) throws RepositoryException {
return node.hasProperty(propName) ? node.getProperty(propName).getValue() : null;
}
public void setRepository(Repository repository) {
this.repository = repository;
}
public void setCredentials(Credentials credentials) {
this.credentials = credentials;
}
public void setMaxActiveSessions(int maxActiveSessions) {
this.maxActiveSessions = maxActiveSessions;
}
}
| 7,723 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/extension/Geo.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.examples.extension;
import javax.xml.namespace.QName;
import org.apache.abdera.Abdera;
import org.apache.abdera.model.Entry;
/**
* Simple example showing the use of the dynamic extension APIs
*/
public class Geo {
private static final String GEO_NS = "http://www.postneo.com/icbm/";
private static final String GEO_PFX = "icbm";
private static final QName LAT = new QName(GEO_NS, "latitude", GEO_PFX);
private static final QName LONG = new QName(GEO_NS, "longitude", GEO_PFX);
public static void main(String[] args) throws Exception {
Abdera abdera = new Abdera();
Entry entry = abdera.getFactory().newEntry();
// Set the extension value
entry.addSimpleExtension(LAT, "39.02980");
entry.addSimpleExtension(LONG, "-77.07929");
// Get the extension value
System.out.println(entry.getSimpleExtension(LAT));
System.out.println(entry.getSimpleExtension(LONG));
}
}
| 7,724 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/extension/FooExtensionFactory.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.examples.extension;
import javax.xml.namespace.QName;
import org.apache.abdera.util.AbstractExtensionFactory;
public class FooExtensionFactory extends AbstractExtensionFactory {
public static final String NS = "tag:example.org,2006:foo";
public static final QName FOO = new QName(NS, "foo", "f");
public static final QName BAR = new QName(NS, "bar", "f");
public FooExtensionFactory() {
super(NS);
addImpl(FOO, Foo.class);
addImpl(BAR, Bar.class);
}
}
| 7,725 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/extension/Bar.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.examples.extension;
import javax.xml.namespace.QName;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.Element;
import org.apache.abdera.model.ExtensibleElementWrapper;
public class Bar extends ExtensibleElementWrapper {
public Bar(Element internal) {
super(internal);
}
public Bar(Factory factory, QName qname) {
super(factory, qname);
}
public void setFoo(Foo foo) {
addExtension(foo);
}
public Foo getFoo() {
return getExtension(FooExtensionFactory.FOO);
}
}
| 7,726 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/extension/Foo.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.examples.extension;
import javax.xml.namespace.QName;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.Element;
import org.apache.abdera.model.ElementWrapper;
public class Foo extends ElementWrapper {
public Foo(Element internal) {
super(internal);
}
public Foo(Factory factory, QName qname) {
super(factory, qname);
}
public String getFoo() {
return getText();
}
public void setFoo(String foo) {
setText(foo);
}
}
| 7,727 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/extension/Example.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.examples.extension;
import org.apache.abdera.Abdera;
import org.apache.abdera.model.Entry;
/**
* Simple example showing the use of static extensions
*/
public class Example {
public static void main(String[] args) throws Exception {
Abdera abdera = new Abdera();
Entry entry = abdera.getFactory().newEntry();
Foo foo = entry.addExtension(FooExtensionFactory.FOO);
foo.setFoo("foo");
Bar bar = entry.addExtension(FooExtensionFactory.BAR);
bar.setFoo((Foo)foo.clone());
bar.getFoo().setFoo("bar");
System.out.println(entry);
}
}
| 7,728 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/unicode/NormalizationExample.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.examples.unicode;
import org.apache.abdera.i18n.text.Normalizer;
/**
* Example that demonstrates Abdera's basic support for Unicode normalization.
*/
public class NormalizationExample {
public static void main(String... args) throws Exception {
// Three different representations of the same character (Angstrom)
String s1 = "\u00c5";
String s2 = "\u0041\u030A";
String s3 = "\u212B";
System.out.println(s1 + "=" + s2 + " ?\t" + s1.equals(s2)); // false
System.out.println(s1 + "=" + s3 + " ?\t" + s1.equals(s3)); // false
System.out.println(s2 + "=" + s3 + " ?\t" + s2.equals(s3)); // false
// Normalize to NFC
String n1 = Normalizer.normalize(s1, Normalizer.Form.C);
String n2 = Normalizer.normalize(s2, Normalizer.Form.C);
String n3 = Normalizer.normalize(s3, Normalizer.Form.C);
System.out.println(n1 + "=" + n2 + " ?\t" + n1.equals(n2)); // true
System.out.println(n1 + "=" + n3 + " ?\t" + n1.equals(n3)); // true
System.out.println(n2 + "=" + n3 + " ?\t" + n2.equals(n3)); // true
// s1 is already normalized to NFC
System.out.println(n1.equals(s1)); // true
}
}
| 7,729 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/unicode/SlugSanitization.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.examples.unicode;
import org.apache.abdera.i18n.text.Normalizer;
import org.apache.abdera.i18n.text.Sanitizer;
/**
* In the Atom Publishing Protocol, the Slug HTTP header is used to allow a client to provide text that can be used to
* create a human-friendly URL for an entry. For instance, in many weblog software packages, it is not uncommon to find
* entries whose permalink URL's look like /my_trip_to_the_zoo. Slug text provided by the client, however, may not be
* directly suitable for use within a URL. It may, for instance, contain non-ascii characters, whitespace, or characters
* not allowed within a URL. The Sanitizer class will take input text and output a modified result suitable for use in
* URL's
*/
public class SlugSanitization {
public static void main(String... args) throws Exception {
// french for "My trip to the beach".. note the accented character and the whitespace characters
String input = "Mon\tvoyage à la\tplage";
// The default rules will replace whitespace with underscore characters
// and convert non-ascii characters to pct-encoded utf-8
String output = Sanitizer.sanitize(input);
System.out.println(output);
// Output = Mon_voyage_%C3%A0_la_plage
// As an alternative to pct-encoding, a replacement string can be provided
output = Sanitizer.sanitize(input, "");
System.out.println(output);
// Output = Mon_voyage__la_plage
// In certain cases, applying Unicode normalization form D to the
// input can produce a good ascii equivalent to the input text.
output = Sanitizer.sanitize(input, "", true, Normalizer.Form.D);
System.out.println(output);
// Output = mon_voyage_a_la_plage
}
}
| 7,730 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/security/DHEnc.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.examples.security;
import java.security.Provider;
import java.security.Security;
import org.apache.abdera.Abdera;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.Document;
import org.apache.abdera.model.Entry;
import org.apache.abdera.security.AbderaSecurity;
import org.apache.abdera.security.Encryption;
import org.apache.abdera.security.EncryptionOptions;
import org.apache.abdera.security.util.DHContext;
public class DHEnc {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
Abdera abdera = new Abdera();
try {
String jce =
abdera.getConfiguration().getConfigurationOption("jce.provider",
"org.bouncycastle.jce.provider.BouncyCastleProvider");
Class provider = Class.forName(jce);
Provider p = (Provider)provider.newInstance();
Security.addProvider(p);
} catch (Exception e) {
// The Configured JCE Provider is not available... try to proceed anyway
}
// Prepare the crypto provider
try {
String jce =
abdera.getConfiguration().getConfigurationOption("jce.provider",
"org.bouncycastle.jce.provider.BouncyCastleProvider");
Class provider = Class.forName(jce);
Provider p = (Provider)provider.newInstance();
Security.addProvider(p);
} catch (Exception e) {
throw new RuntimeException("The Configured JCE Provider is not available");
}
// Create the entry to encrypt
AbderaSecurity absec = new AbderaSecurity(abdera);
Factory factory = abdera.getFactory();
Entry entry = factory.newEntry();
entry.setId("http://example.org/foo/entry");
entry.setUpdated(new java.util.Date());
entry.setTitle("This is an entry");
entry.setContentAsXhtml("This <b>is</b> <i>markup</i>");
entry.addAuthor("James");
entry.addLink("http://www.example.org");
// Prepare the Diffie-Hellman Key Exchange Session
// There are two participants in the session, A and B
// Each has their own DHContext. A creates their context and
// sends the request key parameters to B. B uses those parameters
// to create their context, the returns it's public key
// back to A.
DHContext context_a = new DHContext();
DHContext context_b = new DHContext(context_a.getRequestString());
context_a.setPublicKey(context_b.getResponseString());
// Prepare the encryption options
Encryption enc = absec.getEncryption();
// Encrypt the document using A's DHContext
EncryptionOptions options = context_a.getEncryptionOptions(enc);
Document enc_doc = enc.encrypt(entry.getDocument(), options);
enc_doc.writeTo(System.out);
System.out.println("\n\n");
// Decrypt the document using B's DHContext
options = context_b.getEncryptionOptions(enc);
Document<Entry> entry_doc = enc.decrypt(enc_doc, options);
entry_doc.writeTo(System.out);
}
}
| 7,731 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/security/DSig.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.examples.security;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import org.apache.abdera.Abdera;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.Document;
import org.apache.abdera.model.Entry;
import org.apache.abdera.security.AbderaSecurity;
import org.apache.abdera.security.Signature;
import org.apache.abdera.security.SignatureOptions;
public class DSig {
private static final String keystoreFile = "/key.jks";
private static final String keystoreType = "JKS";
private static final String keystorePass = "testing";
private static final String privateKeyAlias = "James";
private static final String privateKeyPass = "testing";
private static final String certificateAlias = "James";
public static void main(String[] args) throws Exception {
// Initialize the keystore
KeyStore ks = KeyStore.getInstance(keystoreType);
InputStream in = DSig.class.getResourceAsStream(keystoreFile);
ks.load(in, keystorePass.toCharArray());
PrivateKey signingKey = (PrivateKey)ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());
X509Certificate cert = (X509Certificate)ks.getCertificate(certificateAlias);
// Create the entry to sign
Abdera abdera = new Abdera();
AbderaSecurity absec = new AbderaSecurity(abdera);
Factory factory = abdera.getFactory();
Entry entry = factory.newEntry();
entry.setId("http://example.org/foo/entry");
entry.setUpdated(new java.util.Date());
entry.setTitle("This is an entry");
entry.setContentAsXhtml("This <b>is</b> <i>markup</i>");
entry.addAuthor("James");
entry.addLink("http://www.example.org");
// Prepare the digital signature options
Signature sig = absec.getSignature();
SignatureOptions options = sig.getDefaultSignatureOptions();
options.setCertificate(cert);
options.setSigningKey(signingKey);
// Sign the entry
entry = sig.sign(entry, options);
// Check the round trip
ByteArrayOutputStream out = new ByteArrayOutputStream();
entry.writeTo(out); // do not use the pretty writer, it will break the signature
ByteArrayInputStream bais = new ByteArrayInputStream(out.toByteArray());
Document<Entry> entry_doc = abdera.getParser().parse(bais);
entry = entry_doc.getRoot();
System.out.println("Valid? " + sig.verify(entry, null));
entry.setTitle("Change the title");
System.out.println("Valid after changing the title? " + sig.verify(entry, null));
entry = sig.removeInvalidSignatures(entry, options);
}
}
| 7,732 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/security/Enc.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.examples.security;
import java.security.Provider;
import java.security.Security;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import org.apache.abdera.Abdera;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.Document;
import org.apache.abdera.model.Entry;
import org.apache.abdera.security.AbderaSecurity;
import org.apache.abdera.security.Encryption;
import org.apache.abdera.security.EncryptionOptions;
public class Enc {
@SuppressWarnings("unchecked")
public static void main(String[] args) throws Exception {
Abdera abdera = new Abdera();
// Prepare the crypto provider
try {
String jce =
abdera.getConfiguration().getConfigurationOption("jce.provider",
"org.bouncycastle.jce.provider.BouncyCastleProvider");
Class provider = Class.forName(jce);
Provider p = (Provider)provider.newInstance();
Security.addProvider(p);
} catch (Exception e) {
// The configured JCE Provider is not available, try to proceed anyway
}
// Generate Encryption Key
String jceAlgorithmName = "AES";
KeyGenerator keyGenerator = KeyGenerator.getInstance(jceAlgorithmName);
keyGenerator.init(128);
SecretKey key = keyGenerator.generateKey();
// Create the entry to encrypt
AbderaSecurity absec = new AbderaSecurity(abdera);
Factory factory = abdera.getFactory();
Entry entry = factory.newEntry();
entry.setId("http://example.org/foo/entry");
entry.setUpdated(new java.util.Date());
entry.setTitle("This is an entry");
entry.setContentAsXhtml("This <b>is</b> <i>markup</i>");
entry.addAuthor("James");
entry.addLink("http://www.example.org");
// Prepare the encryption options
Encryption enc = absec.getEncryption();
EncryptionOptions options = enc.getDefaultEncryptionOptions();
options.setDataEncryptionKey(key);
// Encrypt the document using the generated key
Document enc_doc = enc.encrypt(entry.getDocument(), options);
enc_doc.writeTo(System.out);
System.out.println("\n\n");
// Decrypt the document using the generated key
Document<Entry> entry_doc = enc.decrypt(enc_doc, options);
entry_doc.writeTo(System.out);
}
}
| 7,733 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/xsltxpath/XPathExample.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.examples.xsltxpath;
import java.io.InputStream;
import org.apache.abdera.Abdera;
import org.apache.abdera.model.Document;
import org.apache.abdera.model.Feed;
import org.apache.abdera.parser.Parser;
import org.apache.abdera.xpath.XPath;
public class XPathExample {
public static void main(String[] args) throws Exception {
Abdera abdera = new Abdera();
Parser parser = abdera.getParser();
XPath xpath = abdera.getXPath();
InputStream in = XPathExample.class.getResourceAsStream("/simple.xml");
Document<Feed> doc = parser.parse(in);
Feed feed = doc.getRoot();
System.out.println(xpath.evaluate("count(/a:feed)", feed)); // 1.0
System.out.println(xpath.numericValueOf("count(/a:feed)", feed)); // 1.0
System.out.println(xpath.booleanValueOf("/a:feed/a:entry", feed)); // true (the feed has an entry)
System.out.println(xpath.valueOf("/a:feed/a:entry/a:title", feed)); // Atom-Powered Robots Run Amok
System.out.println(xpath.selectNodes("/a:feed/a:entry", feed)); // every entry
System.out.println(xpath.selectSingleNode("/a:feed", feed));
System.out.println(xpath.selectSingleNode("..", feed.getTitleElement()));
System.out.println(xpath.selectSingleNode("ancestor::*", feed.getEntries().get(0)));
System.out.println(xpath.valueOf("concat('The feed is is ',/a:feed/a:id)", feed)); // "The feed is is urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6"
}
}
| 7,734 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/xsltxpath/XsltExample.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.examples.xsltxpath;
import java.io.ByteArrayOutputStream;
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.model.Content;
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.parser.Parser;
import org.apache.abdera.util.AbderaSource;
public class XsltExample {
public static void main(String[] args) {
Parser parser = Abdera.getNewParser();
try {
// Apply an XSLT transform to the entire Feed
TransformerFactory factory = TransformerFactory.newInstance();
// Abdera is capable of parsing any well-formed XML document, even XSLT
Document<Element> xslt = parser.parse(XsltExample.class.getResourceAsStream("/test.xslt"));
AbderaSource xsltSource = new AbderaSource(xslt);
Transformer transformer = factory.newTransformer(xsltSource);
// Now let's get the feed we're going to transform
Document<Feed> feed = parser.parse(XsltExample.class.getResourceAsStream("/simple.xml"));
AbderaSource feedSource = new AbderaSource(feed);
// Prepare the output
ByteArrayOutputStream out = new ByteArrayOutputStream();
Result result = new StreamResult(out);
transformer.transform(feedSource, result);
System.out.println(out); // "This is a test urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6"
// Apply an XSLT transform to XML in the content element
xslt = parser.parse(XsltExample.class.getResourceAsStream("/content.xslt"));
xsltSource = new AbderaSource(xslt);
transformer = factory.newTransformer(xsltSource);
feed = parser.parse(XsltExample.class.getResourceAsStream("/xmlcontent.xml"));
Entry entry = feed.getRoot().getEntries().get(0);
Content content = entry.getContentElement();
AbderaSource contentSource = new AbderaSource(content.getValueElement());
// Note that the AbderaSource is set to the value element of atom:content!!
out = new ByteArrayOutputStream();
result = new StreamResult(out);
transformer.transform(contentSource, result);
System.out.println(out); // "This is a test test"
} catch (Exception exception) {
// TrAX is likely not configured, skip the test
}
}
}
| 7,735 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/xsltxpath/XPathFunctionsExample.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.examples.xsltxpath;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.xml.namespace.QName;
import org.apache.abdera.Abdera;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
import org.apache.abdera.model.Link;
import org.apache.abdera.model.Source;
import org.apache.abdera.parser.stax.FOMXPath;
import org.apache.abdera.xpath.XPath;
import org.apache.axiom.om.OMNode;
import org.jaxen.Context;
import org.jaxen.Function;
import org.jaxen.FunctionCallException;
public class XPathFunctionsExample {
@SuppressWarnings("unchecked")
public static void main(String... args) throws Exception {
Abdera abdera = Abdera.getInstance();
Feed feed = abdera.newFeed();
feed.setBaseUri("http://example.org/");
// add additional feed metadata
Entry entry = feed.addEntry();
// add additional feed metadata
entry.addLink("alternate.xml"); // relative URI
XPath xpath = abdera.getXPath();
System.out.println(xpath.valueOf("abdera:resolve(/a:feed/a:entry/a:link/@href)", feed));
// You can add your own xpath functions.
FOMXPath fxpath = (FOMXPath)xpath;
Map<QName, Function> functions = fxpath.getDefaultFunctions();
functions.put(AlternateLinkFunction.QNAME, new AlternateLinkFunction());
fxpath.setDefaultFunctions(functions);
List<Link> links = fxpath.selectNodes("abdera:altlinks(/a:feed/a:entry)", feed);
System.out.println(links);
}
public static class AlternateLinkFunction implements Function {
public static final QName QNAME = new QName("http://abdera.apache.org", "altlinks");
@SuppressWarnings("unchecked")
public Object call(Context context, List args) throws FunctionCallException {
List<Link> results = new ArrayList<Link>();
if (args.isEmpty())
return null;
for (Object obj : args) {
if (obj instanceof List) {
for (Object o : (List)obj) {
try {
if (o instanceof OMNode) {
OMNode node = (OMNode)o;
List<Link> links = null;
if (node instanceof Source) {
Source source = (Source)node;
links = source.getLinks("alternate");
} else if (node instanceof Entry) {
Entry entry = (Entry)node;
links = entry.getLinks("alternate");
}
if (links != null)
results.addAll(links);
}
} catch (Exception e) {
}
}
} else {
// nothing to do
}
}
return results;
}
}
}
| 7,736 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/uritemplates/AtomIDTemplate.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.examples.uritemplates;
import org.apache.abdera.Abdera;
import org.apache.abdera.i18n.templates.Template;
import org.apache.abdera.i18n.templates.URITemplate;
import org.apache.abdera.model.Entry;
/**
* This example demonstrates the use of URI Templates to create an atom:id value from an annotated Java object.
*/
public class AtomIDTemplate {
public static void main(String... args) throws Exception {
ID id = new ID("myblog", "entries", "abc123xyz");
Abdera abdera = Abdera.getInstance();
Entry entry = abdera.newEntry();
entry.setId(Template.expandAnnotated(id));
entry.setTitle("This is a test");
entry.writeTo("prettyxml", System.out);
}
@URITemplate("tag:example.org,2007:/{collection}/{view}/{id}")
public static class ID {
private final String collection;
private final String view;
private final String id;
public ID(String collection, String view, String id) {
this.collection = collection;
this.view = view;
this.id = id;
}
public String getCollection() {
return collection;
}
public String getView() {
return view;
}
public String getId() {
return id;
}
}
}
| 7,737 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/uritemplates/AtomLinkTemplate.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.examples.uritemplates;
import org.apache.abdera.Abdera;
import org.apache.abdera.i18n.templates.Template;
import org.apache.abdera.i18n.templates.URITemplate;
import org.apache.abdera.i18n.templates.VarName;
public class AtomLinkTemplate {
public static void main(String... args) throws Exception {
Abdera abdera = Abdera.getInstance();
abdera.newStreamWriter().setOutputStream(System.out).startDocument().startFeed()
.writeBase("http://example.org").writeLink(getPage("entries", 1, 10), "current")
.writeLink(getPage("entries", 2, 10), "self").writeLink(getPage("entries", 1, 10), "previous")
.writeLink(getPage("entries", 3, 10), "next").writeLink(getPage("entries", 1, 10), "first")
.writeLink(getPage("entries", 10, 10), "last").endFeed().endDocument().flush();
}
private static String getPage(String view, int page, int count) {
return Template.expandAnnotated(new PagingLink(view, page, count));
}
@URITemplate("/{view}?{-join|&|page,count}")
public static class PagingLink {
private final String view;
private final int page;
private final int count;
public PagingLink(String view, int page, int count) {
this.view = view;
this.page = page;
this.count = count;
}
public String getView() {
return view;
}
public int getPage() {
return page;
}
@VarName("count")
public int getPageSize() {
return count;
}
}
}
| 7,738 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/uritemplates/URITemplates.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.examples.uritemplates;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.abdera.i18n.templates.CachingContext;
import org.apache.abdera.i18n.templates.HashMapContext;
import org.apache.abdera.i18n.templates.Template;
@SuppressWarnings("unchecked")
public final class URITemplates {
private static final Template template =
new Template(
"http://example.org{-opt|/~|user}{user}{-opt|/-/|categories}{-listjoin|/|categories}{-opt|?|foo,bar}{-join|&|foo,bar}");
public static void main(String... args) throws Exception {
// two examples of resolving the template
exampleWithObject();
exampleIRIWithObject();
exampleWithMap();
exampleWithHashMapContext();
exampleWithCustomContext();
// explain the template
System.out.println(template);
}
// Using a Java object
private static void exampleWithObject() {
MyObject myObject = new MyObject();
System.out.println(template.expand(myObject));
}
// Using a Java object
private static void exampleIRIWithObject() {
MyObject myObject = new MyObject();
System.out.println(template.expand(myObject, true));
}
// Using a Map
private static void exampleWithMap() {
Map<String, Object> map = new HashMap();
map.put("user", "james");
map.put("categories", new String[] {"a", "b", "c"});
map.put("foo", "abc");
map.put("bar", "xyz");
System.out.println(template.expand(map));
}
// Using a HashMap based context
private static void exampleWithHashMapContext() {
HashMapContext context = new HashMapContext();
context.put("user", "james");
context.put("categories", new String[] {"a", "b", "c"});
context.put("foo", "abc");
context.put("bar", "xyz");
System.out.println(template.expand(context));
}
// Using a custom context implementation
private static void exampleWithCustomContext() {
CachingContext context = new CachingContext() {
private static final long serialVersionUID = 4896250661828139020L;
protected <T> T resolveActual(String var) {
if (var.equals("user"))
return (T)"james";
else if (var.equals("categories"))
return (T)new String[] {"a", "b", "c"};
else if (var.equals("foo"))
return (T)"abc";
else if (var.equals("bar"))
return (T)"xyz";
else
return null;
}
public Iterator<String> iterator() {
return Arrays.asList(new String[] {"user", "categories", "foo", "bar"}).iterator();
}
};
System.out.println(template.expand(context));
}
public static class MyObject {
public String user = "james";
public List getCategories() {
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
return list;
}
public Foo[] getFoo() {
return new Foo[] {new Foo(), new Foo()};
}
public String getBar() {
return "xyz";
}
}
private static class Foo {
public String toString() {
return "abcæ";
}
}
}
| 7,739 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/ext/Geo.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.examples.ext;
import org.apache.abdera.Abdera;
import org.apache.abdera.ext.geo.Coordinate;
import org.apache.abdera.ext.geo.GeoHelper;
import org.apache.abdera.ext.geo.Point;
import org.apache.abdera.ext.geo.Position;
import org.apache.abdera.model.Entry;
/**
* The Geo extensions allow Atom entries to be geotagged using the Georss extensions.
*/
public class Geo {
public static void main(String... args) throws Exception {
Abdera abdera = new Abdera();
Entry entry = abdera.newEntry();
entry.setTitle("Middle of the Ocean");
Point point = new Point(new Coordinate(37.0625, -95.677068));
GeoHelper.addPosition(entry, point);
Position[] positions = GeoHelper.getPositions(entry);
for (Position pos : positions) {
if (pos instanceof Point) {
Point p = (Point)pos;
System.out.println(p.getCoordinate());
}
}
// By default, positions are encoded using the simple georss encoding,
// W3C and GML encodings are also supported
GeoHelper.addPosition(entry, point, GeoHelper.Encoding.W3C);
GeoHelper.addPosition(entry, point, GeoHelper.Encoding.GML);
}
}
| 7,740 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/ext/Json.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.examples.ext;
import org.apache.abdera.Abdera;
import org.apache.abdera.model.Entry;
/**
* The JSONWriter can be used to serialize an Abdera entry into a JSON structure
*/
public class Json {
public static void main(String... args) throws Exception {
Abdera abdera = new Abdera();
Entry entry = abdera.newEntry();
entry.newId();
entry.setTitle("test");
entry.setContentAsHtml("<b>foo</b>");
entry.addAuthor("James");
entry.addCategory("term");
entry.writeTo("json", System.out);
/**
* Produces: { "id":"urn:uuid:97893C35372BE77BD51200273434152", "title":"test", "content":{
* "attributes":{"type":"html"}, "children":[{ "name":"b", "attributes":{}, "children":["foo"]}]},
* "authors":[{"name":"James"}], "categories":[{"term":"term"}] }
*/
}
}
| 7,741 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/ext/License.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.examples.ext;
import java.util.List;
import org.apache.abdera.Abdera;
import org.apache.abdera.ext.license.LicenseHelper;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
import org.apache.abdera.model.Link;
/**
* The Atom License extension is described in Experimental RFC4946 and provides a way of associating copyright licenses
* with feeds and entries. This is useful when working with things like Creative Commons licenses.
*/
public class License {
public static void main(String... args) throws Exception {
Abdera abdera = new Abdera();
Feed feed = abdera.newFeed();
Entry entry = feed.addEntry();
// Add a license to the feed
LicenseHelper.addLicense(feed, "http://example.org/foo", "Foo");
// does the feed have a license link?
System.out.println(LicenseHelper.hasLicense(feed));
// does the feed have a specific license link?
System.out.println(LicenseHelper.hasLicense(feed, "http://example.org/foo"));
// since the entry does not have a license, it inherits the feeds
System.out.println(LicenseHelper.hasLicense(entry));
System.out.println(LicenseHelper.hasLicense(entry, "http://example.org/foo"));
// list the licenses
List<Link> licenses = LicenseHelper.getLicense(entry);
for (Link link : licenses) {
System.out.println(link.getResolvedHref());
}
// Add an unspecified license to the entry
LicenseHelper.addUnspecifiedLicense(entry);
// now the entry does not inherit the feeds license
System.out.println(LicenseHelper.hasLicense(entry, "http://example.org/foo"));
}
}
| 7,742 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/ext/Sharing.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.examples.ext;
import org.apache.abdera.Abdera;
import org.apache.abdera.ext.sharing.Conflicts;
import org.apache.abdera.ext.sharing.SharingHelper;
import org.apache.abdera.ext.sharing.Sync;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
/**
* Basic Simple Sharing Extensions support
*/
public class Sharing {
public static void main(String... args) throws Exception {
Abdera abdera = new Abdera();
// Create two feeds
Feed f1 = abdera.newFeed();
Feed f2 = abdera.newFeed();
// Create a couple of sharing-enabled entries
Entry e1 = SharingHelper.createEntry(abdera, "jms", f1);
e1.newId();
Entry e2 = SharingHelper.createEntry(abdera, "jms", f1);
e2.newId();
Entry e3 = (Entry)e2.clone();
f2.addEntry(e3);
// concurrent modification of the same entry by two different users in two different feeds
SharingHelper.updateEntry(e2, "bob");
SharingHelper.updateEntry(e3, "joe");
// prepare a third feed for merging
Feed f3 = (Feed)f2.clone();
// merge f1 with f2 to produce f3
SharingHelper.mergeFeeds(f1, f3);
// there will be two entries in f3, one of which shows a conflict
for (Entry entry : f3.getEntries()) {
System.out.println(entry.getId());
if (SharingHelper.hasConflicts(entry)) {
Sync sync = SharingHelper.getSync(entry);
Conflicts conflicts = sync.getConflicts();
System.out.println("\tNumber of conflicts: " + conflicts.getEntries().size());
}
}
}
}
| 7,743 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/ext/Paging.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.examples.ext;
import org.apache.abdera.Abdera;
import org.apache.abdera.ext.history.FeedPagingHelper;
import org.apache.abdera.model.Feed;
public class Paging {
public static void main(String... args) throws Exception {
Abdera abdera = new Abdera();
Feed feed = abdera.newFeed();
// Set/Get the paging links
FeedPagingHelper.setCurrent(feed, "feed");
FeedPagingHelper.setNext(feed, "feed?page=3");
FeedPagingHelper.setPrevious(feed, "feed?page=1");
FeedPagingHelper.setFirst(feed, "feed");
FeedPagingHelper.setLast(feed, "feed?page=10");
FeedPagingHelper.setNextArchive(feed, "feed?page=3");
FeedPagingHelper.setPreviousArchive(feed, "feed?page=1");
System.out.println(FeedPagingHelper.getCurrent(feed));
System.out.println(FeedPagingHelper.getNext(feed));
System.out.println(FeedPagingHelper.getPrevious(feed));
System.out.println(FeedPagingHelper.getFirst(feed));
System.out.println(FeedPagingHelper.getLast(feed));
System.out.println(FeedPagingHelper.getNextArchive(feed));
System.out.println(FeedPagingHelper.getPreviousArchive(feed));
// Set/Get the archive flag
FeedPagingHelper.setArchive(feed, true);
if (FeedPagingHelper.isArchive(feed))
System.out.println("archive feed!");
// Set/Get the complete flag
FeedPagingHelper.setComplete(feed, true);
if (FeedPagingHelper.isComplete(feed))
System.out.println("complete feed!");
}
}
| 7,744 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/ext/Bidi.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.examples.ext;
import org.apache.abdera.Abdera;
import org.apache.abdera.ext.bidi.BidiHelper;
import org.apache.abdera.i18n.text.Bidi.Direction;
import org.apache.abdera.model.Entry;
/**
* The Atom Bidi Extension is described in an IETF Internet-Draft and is used to communicate information about the base
* directionality of text in an Atom document.
*/
public class Bidi {
public static void main(String... args) throws Exception {
String text = "\u05e4\u05e2\u05d9\u05dc\u05d5\u05ea \u05d4\u05d1\u05d9\u05e0\u05d0\u05d5\u05dd, W3C";
Abdera abdera = new Abdera();
Entry entry = abdera.newEntry();
BidiHelper.setDirection(Direction.RTL, entry);
entry.setTitle(text);
// non bidi, incorrectly displayed
System.out.println(entry.getTitle());
// with bidi, correctly displayed
System.out.println(BidiHelper.getBidiElementText(entry.getTitleElement()));
// with bidi, correctly displayed
System.out.println(BidiHelper.getBidiText(BidiHelper.getDirection(entry), entry.getTitle()));
// there are also direction guessing algorithms available
entry = abdera.newEntry();
entry.setTitle(text);
entry.setLanguage("ar");
System.out.println(BidiHelper.guessDirectionFromJavaBidi(entry.getTitleElement()));
System.out.println(BidiHelper.guessDirectionFromTextProperties(entry.getTitleElement()));
System.out.println(BidiHelper.guessDirectionFromLanguage(entry.getTitleElement()));
}
}
| 7,745 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/ext/Features.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.examples.ext;
import org.apache.abdera.Abdera;
import org.apache.abdera.ext.features.Feature;
import org.apache.abdera.ext.features.FeatureSelector;
import org.apache.abdera.ext.features.FeaturesHelper;
import org.apache.abdera.model.Collection;
import org.apache.abdera.model.Service;
import org.apache.abdera.model.Workspace;
/**
* The Atompub Features Extension is described in an IETF I-D and is used to communicate information about features that
* are supported, required or unsupported by an Atompub collection.
*/
public class Features {
public static void main(String... args) throws Exception {
Abdera abdera = new Abdera();
Service service = abdera.newService();
Workspace workspace = service.addWorkspace("My workspace");
Collection collection = workspace.addCollection("My collection", "foo");
// Specify which features are supported by the collection
org.apache.abdera.ext.features.Features features = FeaturesHelper.addFeaturesElement(collection);
features.addFeature(FeaturesHelper.FEATURE_SUPPORTS_DRAFTS);
features.addFeature(FeaturesHelper.FEATURE_REQUIRES_TEXT_TEXT);
features.addFeature(FeaturesHelper.FEATURE_IGNORES_SLUG);
features.addFeature(FeaturesHelper.FEATURE_SUPPORTS_BIDI);
// Get the support status of a specific feature
System.out.println(FeaturesHelper.getFeatureStatus(collection, FeaturesHelper.FEATURE_SUPPORTS_DRAFTS));
System.out.println(FeaturesHelper.getFeatureStatus(collection, FeaturesHelper.FEATURE_REQUIRES_TEXT_TEXT));
System.out.println(FeaturesHelper.getFeatureStatus(collection, FeaturesHelper.FEATURE_IGNORES_SLUG));
System.out.println(FeaturesHelper.getFeatureStatus(collection, FeaturesHelper.FEATURE_SUPPORTS_BIDI));
System.out.println(FeaturesHelper.getFeatureStatus(collection, FeaturesHelper.FEATURE_SUPPORTS_GEO));
Feature[] fs = FeaturesHelper.getFeatures(collection);
for (Feature feature : fs) {
System.out.println("\t" + feature.getRef());
}
// Select a collection by feature
Collection[] selectedCollections =
FeaturesHelper.select(service, new FeatureSelector(FeaturesHelper.FEATURE_SUPPORTS_DRAFTS,
FeaturesHelper.FEATURE_SUPPORTS_BIDI));
System.out.println("Selected Collections:");
for (Collection selected : selectedCollections)
System.out.println("\t" + selected.getTitle());
}
}
| 7,746 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/ext/Serializer.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.examples.ext;
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;
/**
* The Serializer extension allows Java objects to be automatically serialized into Atom documents using the objects
* public getters or fields. The implementation is still largely experimental
*/
public class Serializer {
static Date date_now = new Date();
static Calendar cal_now = Calendar.getInstance();
public static void main(String... args) throws Exception {
Abdera abdera = Abdera.getInstance();
// demonstrate serialization of a non-annotated java object
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();
// once the object has been serialized, we can see that it's a parseable Atom document
ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
Document<Entry> doc = abdera.getParser().parse(in);
Entry entry = doc.getRoot();
entry.writeTo(System.out);
System.out.println();
// demonstrate serialization using an annotated java object
// annotations allow the developer to customize the way the
// object is serialized
sw = abdera.newStreamWriter();
out = new ByteArrayOutputStream();
sw.setOutputStream(out).setAutoIndent(true);
c = new ConventionSerializationContext(sw);
sw.startDocument();
c.serialize(new MyAnnotatedEntry());
sw.endDocument();
in = new ByteArrayInputStream(out.toByteArray());
doc = abdera.getParser().parse(in);
entry = doc.getRoot();
entry.writeTo(System.out);
}
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";
}
}
@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,747 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/ext/Thread.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.examples.ext;
import org.apache.abdera.Abdera;
import org.apache.abdera.ext.thread.InReplyTo;
import org.apache.abdera.ext.thread.ThreadHelper;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Link;
/**
* The Atom Threading Extensions are described in RFC4685 and provide a means of representing threaded discussions and
* parent/child relationships in Atom.
*/
public class Thread {
public static void main(String... args) throws Exception {
Abdera abdera = new Abdera();
Entry e1 = abdera.newEntry();
Entry e2 = abdera.newEntry();
e1.newId();
e2.newId();
// Entry e2 is a reply to Entry e1
ThreadHelper.addInReplyTo(e2, e1);
// Get the in-reply-to information
InReplyTo irt = ThreadHelper.getInReplyTo(e2);
System.out.println(irt.getRef());
// Add a link to a feed containing replies to e1
Link replies = e1.addLink("replies.xml", Link.REL_REPLIES);
// Set the known number of replies as an attribute on the link
ThreadHelper.setCount(replies, 10);
// alternatively, use the thr:total element to specify the number of replies
ThreadHelper.addTotal(e1, 10);
}
}
| 7,748 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/appclient/SSLExample.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.examples.appclient;
import java.security.KeyStore;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.X509TrustManager;
import org.apache.abdera.Abdera;
import org.apache.abdera.protocol.client.AbderaClient;
import org.apache.abdera.protocol.client.util.ClientAuthSSLProtocolSocketFactory;
public class SSLExample {
/**
* Abdera's default trust manager is registered on port 443 and accepts all server certificates and issuers.
*/
public static void defaultTrustManager() throws Exception {
Abdera abdera = new Abdera();
AbderaClient client = new AbderaClient(abdera);
// Default trust manager provider registered for port 443
AbderaClient.registerTrustManager();
client.get("https://localhost:9080/foo");
}
/**
* The default trust manager can be registered for additional ports
*/
public static void defaultTrustManager2() throws Exception {
Abdera abdera = new Abdera();
AbderaClient client = new AbderaClient(abdera);
// Default trust manager provider registered for port 9443
AbderaClient.registerTrustManager(9443);
client.get("https://localhost:9080/foo");
}
/**
* You can provide your own X509TrustManager implementation
*/
public static void customTrustManager() throws Exception {
Abdera abdera = new Abdera();
AbderaClient client = new AbderaClient(abdera);
// Default trust manager provider registered for port 9443
AbderaClient.registerTrustManager(new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] certs, String arg1) throws CertificateException {
// ignore this one for now
}
public void checkServerTrusted(X509Certificate[] certs, String arg1) throws CertificateException {
// logic to determine if the cert is acceptable
// throw a CertificateException if it's not
}
public X509Certificate[] getAcceptedIssuers() {
List<X509Certificate> certs = new ArrayList<X509Certificate>();
// prepare list of accepted issuer certs
return certs.toArray(new X509Certificate[certs.size()]);
}
});
client.get("https://localhost:9080/foo");
}
/**
* You can provide your own secure socket factory to support additional use cases, such as using client certs for
* auth
*/
public static void clientAuth() throws Exception {
Abdera abdera = new Abdera();
AbderaClient client = new AbderaClient(abdera);
KeyStore keystore = null;
ClientAuthSSLProtocolSocketFactory factory =
new ClientAuthSSLProtocolSocketFactory(keystore, "keystorepassword");
AbderaClient.registerFactory(factory, 443);
// DO NOT register a trust manager after this point
client.get("https://localhost:9080/foo");
}
}
| 7,749 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/appclient/Main.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.examples.appclient;
import java.util.Date;
import java.util.List;
import org.apache.abdera.Abdera;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.Collection;
import org.apache.abdera.model.Document;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Link;
import org.apache.abdera.model.Service;
import org.apache.abdera.protocol.client.AbderaClient;
import org.apache.abdera.i18n.iri.IRI;
public class Main {
public static void main(String[] args) throws Exception {
Abdera abdera = new Abdera();
AbderaClient abderaClient = new AbderaClient(abdera);
Factory factory = abdera.getFactory();
// Perform introspection. This is an optional step. If you already
// know the URI of the APP collection to POST to, you can skip it.
Document<Service> introspection = abderaClient.get(args[0]).getDocument();
Service service = introspection.getRoot();
Collection collection = service.getCollection(args[1], args[2]);
report("The Collection Element", collection.toString());
// Create the entry to post to the collection
Entry entry = factory.newEntry();
entry.setId("tag:example.org,2006:foo");
entry.setTitle("This is the title");
entry.setUpdated(new Date());
entry.addAuthor("James");
entry.setContent("This is the content");
report("The Entry to Post", entry.toString());
// Post the entry. Be sure to grab the resolved HREF of the collection
Document<Entry> doc = abderaClient.post(collection.getResolvedHref().toString(), entry).getDocument();
// In some implementations (such as Google's GData API, the entry URI is
// distinct from it's edit URI. To be safe, we should assume it may be
// different
IRI entryUri = doc.getBaseUri();
report("The Created Entry", doc.getRoot().toString());
// Grab the Edit URI from the entry. The entry MAY have more than one
// edit link. We need to make sure we grab the right one.
IRI editUri = getEditUri(doc.getRoot());
// If there is an Edit Link, we can edit the entry
if (editUri != null) {
// Before we can edit, we need to grab an "editable" representation
doc = abderaClient.get(editUri.toString()).getDocument();
// Change whatever you want in the retrieved entry
doc.getRoot().getTitleElement().setValue("This is the changed title");
// Put it back to the server
abderaClient.put(editUri.toString(), doc.getRoot());
// This is just to show that the entry has been modified
doc = abderaClient.get(entryUri.toString()).getDocument();
report("The Modified Entry", doc.getRoot().toString());
} else {
// Otherwise, the entry cannot be modified (no suitable edit link was found)
report("The Entry cannot be modified", null);
}
// Delete the entry. Again, we need to make sure that we have the current
// edit link for the entry
doc = abderaClient.get(entryUri.toString()).getDocument();
editUri = getEditUri(doc.getRoot());
if (editUri != null) {
abderaClient.delete(editUri.toString());
report("The Enry has been deleted", null);
} else {
report("The Entry cannot be deleted", null);
}
}
private static IRI getEditUri(Entry entry) throws Exception {
IRI editUri = null;
List<Link> editLinks = entry.getLinks("edit");
for (Link link : editLinks) {
// if there is more than one edit link, we should not automatically
// assume that it's always going to point to an Atom document
// representation.
if (link.getMimeType() != null) {
if (link.getMimeType().match("application/atom+xml")) {
editUri = link.getResolvedHref();
break;
}
} else { // assume that an edit link with no type attribute is the right one to use
editUri = link.getResolvedHref();
break;
}
}
return editUri;
}
private static void report(String title, String message) {
System.out.println("== " + title + " ==");
if (message != null)
System.out.println(message);
System.out.println();
}
}
| 7,750 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/appclient/Services.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.examples.appclient;
import java.io.FileInputStream;
import java.util.Date;
import javax.xml.namespace.QName;
import org.apache.abdera.Abdera;
import org.apache.abdera.ext.gdata.GoogleLoginAuthCredentials;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.AtomDate;
import org.apache.abdera.model.Collection;
import org.apache.abdera.model.Document;
import org.apache.abdera.model.Element;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Service;
import org.apache.abdera.parser.stax.util.FOMHelper;
import org.apache.abdera.protocol.Response;
import org.apache.abdera.protocol.client.AbderaClient;
import org.apache.abdera.protocol.client.RequestOptions;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
public class Services {
/**
* Posting to Blogger Beta
*/
public static void postToBlogger() throws Exception {
Abdera abdera = new Abdera();
// Create the entry that will be posted
Factory factory = abdera.getFactory();
Entry entry = factory.newEntry();
entry.setId(FOMHelper.generateUuid());
entry.setUpdated(new java.util.Date());
entry.addAuthor("James");
entry.setTitle("Posting to Blogger");
entry.setContentAsXhtml("<p>This is an example post to the new blogger beta</p>");
// Initialize the client
AbderaClient abderaClient = new AbderaClient(abdera);
// Get and set the GoogleLogin authentication token
GoogleLoginAuthCredentials creds = new GoogleLoginAuthCredentials("username", "password", "blogger");
abderaClient.addCredentials("http://beta.blogger.com", null, "GoogleLogin", creds);
RequestOptions options = abderaClient.getDefaultRequestOptions();
options.setUseChunked(false);
// Post the entry
Response response =
abderaClient.post("http://beta.blogger.com/feeds/7352231422284704069/posts/full", entry, options);
// Check the response.
if (response.getStatus() == 201)
System.out.println("Success!");
else
System.out.println("Failed!");
}
/**
* Posting to Roller
*/
public static void postToRoller() throws Exception {
// Set the URI of the Introspection document
String start = "http://example.org/app";
Abdera abdera = new Abdera();
Factory factory = abdera.getFactory();
// Create the entry that will be posted
Entry entry = factory.newEntry();
entry.setId(FOMHelper.generateUuid());
entry.setUpdated(new java.util.Date());
entry.addAuthor("James");
entry.setTitle("Posting to Roller");
entry.setContentAsHtml("<p>This is an example post to Roller</p>");
// Initialize the client and set the authentication credentials
AbderaClient abderaClient = new AbderaClient(abdera);
abderaClient.addCredentials(start, null, null, new UsernamePasswordCredentials("username", "password"));
// Get the service document and look up the collection uri
Document<Service> service_doc = abderaClient.get(start).getDocument();
Service service = service_doc.getRoot();
Collection collection = service.getWorkspaces().get(0).getCollections().get(0);
String uri = collection.getHref().toString();
// Post the entry to the collection
Response response = abderaClient.post(uri, entry);
// Check the result
if (response.getStatus() == 201)
System.out.println("Success!");
else
System.out.println("Failed!");
}
/**
* Posting a Podcast to Roller
*/
public static void postMediaToRoller() throws Exception {
// Set the introspection document
String start = "http://example.org/app";
Abdera abdera = new Abdera();
// Prepare the media resource to be sent
FileInputStream fis = new FileInputStream("mypodcast.mp3");
InputStreamRequestEntity re = new InputStreamRequestEntity(fis, "audio/mp3");
// Initialize the client and set the auth credentials
AbderaClient abderaClient = new AbderaClient(abdera);
abderaClient.addCredentials(start, null, null, new UsernamePasswordCredentials("username", "password"));
// Get the service doc and locate the href of the collection
Document<Service> service_doc = abderaClient.get(start).getDocument();
Service service = service_doc.getRoot();
Collection collection = service.getWorkspaces().get(0).getCollections().get(1);
String uri = collection.getHref().toString();
// Set the filename. Note: the Title header was used by older drafts
// of the Atom Publishing Protocol and should no longer be used. The
// current Roller APP implementation still currently requires it.
RequestOptions options = abderaClient.getDefaultRequestOptions();
options.setHeader("Title", "mypodcast.mp3");
// Post the entry
Response response = abderaClient.post(uri, re, options);
// Check the response
if (response.getStatus() == 201)
System.out.println("Success!");
else
System.out.println("Failed!");
}
/**
* Post to Google Calendar
*/
public static void postToCalendar() throws Exception {
Abdera abdera = new Abdera();
// Prepare the entry
Factory factory = abdera.getFactory();
Entry entry = factory.newEntry();
entry.setId(FOMHelper.generateUuid());
entry.setUpdated(new java.util.Date());
entry.addAuthor("James");
entry.setTitle("New Calendar Event");
entry.setContentAsXhtml("<p>A new calendar event</p>");
// Add the Google Specific extensions
((Element)entry.addExtension(new QName("http://schemas.google.com/g/2005", "transparency")))
.setAttributeValue("value", "http://schemas.google.com/g/2005#event.opaque");
((Element)entry.addExtension(new QName("http://schemas.google.com/g/2005", "eventStatus")))
.setAttributeValue("value", "http://schemas.google.com/g/2005#event.confirmed");
((Element)entry.addExtension(new QName("http://schemas.google.com/g/2005", "where")))
.setAttributeValue("valueString", "Rolling Lawn Courts");
Element el = entry.addExtension(new QName("http://schemas.google.com/g/2005", "when"));
el.setAttributeValue("startTime", AtomDate.valueOf(new Date()).toString());
el.setAttributeValue("endTime", AtomDate.valueOf(new Date()).toString());
// Prepare the client
AbderaClient abderaClient = new AbderaClient(abdera);
// Get and set the GoogleLogin auth token
GoogleLoginAuthCredentials creds = new GoogleLoginAuthCredentials("username", "password", "cl");
abderaClient.addCredentials("http://www.google.com/calendar", null, "GoogleLogin", creds);
String uri = "http://www.google.com/calendar/feeds/default/private/full";
RequestOptions options = abderaClient.getDefaultRequestOptions();
options.setUseChunked(false);
// Post the entry
Response response = abderaClient.post(uri, entry, options);
// Google Calendar might return a 302 response with a new POST URI.
// If it does, get the new URI and post again
if (response.getStatus() == 302) {
uri = response.getLocation().toString();
response = abderaClient.post(uri, entry, options);
}
// Check the response
if (response.getStatus() == 201)
System.out.println("Success!");
else
System.out.println("Failed!");
}
}
| 7,751 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/html/HtmlExample.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.examples.html;
import java.io.StringReader;
import java.util.List;
import org.apache.abdera.Abdera;
import org.apache.abdera.model.Document;
import org.apache.abdera.model.Element;
import org.apache.abdera.parser.Parser;
import org.apache.abdera.xpath.XPath;
/**
* The optional HTML Parser extension allows Abdera to parse and work with HTML
*/
public class HtmlExample {
@SuppressWarnings("unchecked")
public static void main(String... args) throws Exception {
String html = "<html><body><p>this is <i>html</i></body></html>";
Abdera abdera = Abdera.getInstance();
Parser parser = abdera.getParserFactory().getParser("html");
Document<Element> doc = parser.parse(new StringReader(html));
Element root = doc.getRoot();
root.writeTo(System.out);
System.out.println();
XPath xpath = abdera.getXPath();
List<Element> list = xpath.selectNodes("//i", doc.getRoot());
for (Element element : list)
System.out.println(element);
}
}
| 7,752 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/simple/i18nExample.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.examples.simple;
import java.util.Date;
import org.apache.abdera.Abdera;
import org.apache.abdera.ext.bidi.BidiHelper;
import org.apache.abdera.i18n.text.Bidi.Direction;
import org.apache.abdera.model.Element;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
/**
* Simple example demonstrating Abdera's i18n support
*/
public class i18nExample {
public static void main(String... args) throws Exception {
Abdera abdera = Abdera.getInstance();
Feed feed = abdera.newFeed();
feed.getDocument().setCharset("UTF-8");
// Set the language context and default text direction
feed.setLanguage("ar"); // Arabic
BidiHelper.setDirection(Direction.RTL, feed);
feed.setBaseUri("http://\u0645\u062b\u0627\u0644.org/ar/feed.xml");
feed.setId("tag:\u0645\u062b\u0627\u0644.org,2007:/\u0645\u062b\u0627\u0644");
feed.setUpdated(new Date());
feed
.setTitle("\u0645\u062b\u0644\u0627\u0020\u0627\u0644\u0646\u0635\u0020\u0627\u0644\u0639\u0631\u0628\u064a");
feed.addAuthor("\u062c\u064a\u0645\u0633");
feed.addLink("", "self");
feed.addLink("http://\u0645\u062b\u0627\u0644.org/ar/blog");
Entry entry = feed.addEntry();
entry.setId("tag:\u0645\u062b\u0627\u0644.org,2007:/\u0645\u062b\u0627\u0644/1");
entry.setTitle("\u0645\u062b\u0627\u0644\u0020\u062f\u062e\u0648\u0644");
entry.setUpdated(new Date());
entry.addLink("http://\u0645\u062b\u0627\u0644.org/ar/blog/1");
entry
.setSummaryAsXhtml("<p xml:lang=\"ar\" dir=\"rtl\">\u0648\u0647\u0630\u0627\u0020\u0645\u062b\u0627\u0644\u0020\u0639\u0644\u0649\u0020\u0648\u062c\u0648\u062f\u0020\u0041\u0074\u006f\u006d\u0020\u0031\u002e\u0030\u0020\u0052\u0054\u004c\u0020\u0627\u0644\u0627\u0639\u0644\u0627\u0641\u0020\u0627\u0644\u062a\u064a\u0020\u062a\u062d\u062a\u0648\u064a\u0020\u0639\u0644\u0649\u0020\u0627\u0644\u0646\u0635\u0020\u0627\u0644\u0639\u0631\u0628\u064a</p>");
feed.writeTo("prettyxml", System.out);
System.out.println();
Element el = feed.getEntries().get(0).getSummaryElement().getValueElement().getFirstChild();
System.out.println("Incorrect: " + el.getText());
System.out.println("Correct: " + BidiHelper.getBidiElementText(el));
}
}
| 7,753 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/simple/StreamWriterExample.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.examples.simple;
import java.util.Date;
import org.apache.abdera.Abdera;
import org.apache.abdera.writer.StreamWriter;
/**
* Demonstrates the use of the Abdera StreamWriter interface
*/
public class StreamWriterExample {
public static void main(String... args) {
Abdera abdera = Abdera.getInstance();
StreamWriter out =
abdera.newStreamWriter().setOutputStream(System.out, "UTF-8").setAutoflush(false).setAutoIndent(true)
.startDocument().startFeed().writeBase("http://example.org").writeLanguage("en-US")
.writeId("http://example.org").writeTitle("<Testing 123>").writeSubtitle("Foo").writeAuthor("James",
null,
null)
.writeUpdated(new Date()).writeLink("http://example.org/foo").writeLink("http://example.org/bar",
"self").writeCategory("foo")
.writeCategory("bar").writeLogo("logo").writeIcon("icon").writeGenerator("1.0",
"http://example.org",
"foo").flush();
for (int n = 0; n < 100; n++) {
out.startEntry().writeId("http://example.org/" + n).writeTitle("Entry #" + n).writeUpdated(new Date())
.writePublished(new Date()).writeEdited(new Date()).writeSummary("This is text summary")
.writeAuthor("James", null, null).writeContributor("Joe", null, null).startContent("application/xml")
.startElement("a", "b", "c").startElement("x", "y", "z").writeElementText("This is a test")
.startElement("a").writeElementText("foo").endElement().startElement("b", "bar")
.writeAttribute("foo", new Date()).writeAttribute("bar", 123L).writeElementText(123.123).endElement()
.endElement().endElement().endContent().endEntry().flush();
}
out.endFeed().endDocument().flush();
}
}
| 7,754 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/simple/Create.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.examples.simple;
import java.net.URL;
import java.util.Date;
import javax.activation.DataHandler;
import javax.activation.URLDataSource;
import org.apache.abdera.Abdera;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.model.Content;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
import org.apache.abdera.i18n.iri.IRI;
public class Create {
public static void main(String[] args) throws Exception {
Factory factory = Abdera.getNewFactory();
Feed feed = factory.newFeed();
feed.setLanguage("en-US");
feed.setBaseUri("http://example.org");
feed.setTitle("Example Feed");
feed.addLink("http://example.org/");
feed.setUpdated(new Date());
feed.addAuthor("John Doe");
feed.setId("urn:uuid:60a76c80-d399-11d9-b93C-0003939e0af6");
feed.addContributor("Bob Jones");
feed.addCategory("example");
// Creates an entry and inserts it at the beginning of the list
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");
entry.setUpdated(new Date());
entry.setSummary("Some text.");
// Creates an entry and inserts it at the beginning of the list
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");
entry2.setUpdated(new Date());
entry2.setSummary("A response");
// Creates an entry and appends it to the end of the list
Entry entry3 = feed.addEntry();
entry3.setTitleAsXhtml("<p>Test</p>");
entry3.addLink("/2003/12/13/atom03/2");
entry3.setId("HTTP://www.Example.org/foo/../bar", true); // normalizes the id to the value
// http://www.example.org/bar
entry3.setUpdated(new Date());
entry3.setSummaryAsHtml("<p><a href=\"foo\">Test</a></p>").setBaseUri("http://example.org/site/");
entry3.setSource(feed.getAsSource());
// Out-of-line content
Entry entry4 = feed.addEntry();
entry4.setTitle("re: Atom-Powered Robots Run Amok");
entry4.addLink("/2003/12/13/atom03/3");
entry4.setId("urn:uuid:1225c695-cfb8-4ebb-aaaa-cafebabecafe");
entry4.setUpdated(new Date());
entry4.setSummary("An entry with out-of-line content");
entry4.setContent(new IRI("http://example.org/0xcafebabe"), "text/html");
// Base64 binary content
Entry entry5 = feed.addEntry();
entry5.setTitle("re: Atom-Powered Robots Run Amok");
entry5.addLink("/2003/12/13/atom03/4");
entry5.setId("urn:uuid:1225c695-cfb8-4ebb-aaaa-80cb323feb5c");
entry5.setUpdated(new Date());
entry5.setSummary("A simple Base64 encoded binary image");
URL url = Create.class.getResource("/atom-logo75px.gif");
entry5.setContent(new DataHandler(new URLDataSource(url)), "image/gif");
// XML content
Entry entry6 = feed.addEntry();
entry6.setTitle("re: Atom-Powered Robots Run Amok");
entry6.addLink("/2003/12/13/atom03/5");
entry6.setId("urn:uuid:1225c695-cfb8-4ebb-aaaa-80cb323feb5d");
entry6.setUpdated(new Date());
entry6.setSummary("XML content");
entry6.setContent("<a xmlns='urn:foo'><b/></a>", Content.Type.XML);
feed.getDocument().writeTo(System.out);
}
}
| 7,755 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/simple/UnacceptableElementsExample.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.examples.simple;
import javax.xml.namespace.QName;
import org.apache.abdera.Abdera;
import org.apache.abdera.filter.ListParseFilter;
import org.apache.abdera.model.Document;
import org.apache.abdera.model.Feed;
import org.apache.abdera.parser.Parser;
import org.apache.abdera.parser.ParserOptions;
import org.apache.abdera.parser.stax.FOMException;
import org.apache.abdera.util.filter.BlackListParseFilter;
public class UnacceptableElementsExample {
public static void main(String[] args) throws Exception {
Parser parser = Abdera.getNewParser();
/**
* By subclassing BlackListParseFilter, we can throw an error when the parsed XML contains any content we don't
* want
*/
ListParseFilter exceptionFilter = new BlackListParseFilter() {
private static final long serialVersionUID = 7564587859561916928L;
@Override
public boolean acceptable(QName qname) {
boolean answer = super.acceptable(qname);
if (!(answer)) {
throw new FOMException("Unacceptable element ::" + qname);
}
return answer;
}
@Override
public boolean acceptable(QName qname, QName attribute) {
return true;
}
};
exceptionFilter.add(new QName("http://example.org", "a"));
ParserOptions options = parser.getDefaultParserOptions();
options.setParseFilter(exceptionFilter);
Document<Feed> doc =
parser.parse(UnacceptableElementsExample.class.getResourceAsStream("/xmlcontent.xml"), null, options);
// this will throw a FOMException
doc.writeTo(System.out);
}
}
| 7,756 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/simple/StreamBuilderExample.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.examples.simple;
import java.util.Date;
import org.apache.abdera.Abdera;
import org.apache.abdera.factory.StreamBuilder;
import org.apache.abdera.model.Document;
import org.apache.abdera.model.Feed;
/**
* Demonstrates the use of the Abdera StreamWriter interface
*/
public class StreamBuilderExample {
public static void main(String... args) throws Exception {
Abdera abdera = Abdera.getInstance();
StreamBuilder out = abdera.getWriterFactory().newStreamWriter("fom");
out.startDocument().startFeed().writeBase("http://example.org").writeLanguage("en-US")
.writeId("http://example.org").writeTitle("<Testing 123>").writeSubtitle("Foo").writeAuthor("James",
null,
null)
.writeUpdated(new Date()).writeLink("http://example.org/foo").writeLink("http://example.org/bar", "self")
.writeCategory("foo").writeCategory("bar").writeLogo("logo").writeIcon("icon")
.writeGenerator("1.0", "http://example.org", "foo");
for (int n = 0; n < 100; n++) {
out.startEntry().writeId("http://example.org/" + n).writeTitle("Entry #" + n).writeUpdated(new Date())
.writePublished(new Date()).writeEdited(new Date()).writeSummary("This is text summary")
.writeAuthor("James", null, null).writeContributor("Joe", null, null).startContent("application/xml")
.startElement("a", "b", "c").startElement("x", "y", "z").writeElementText("This is a test")
.startElement("a").writeElementText("foo").endElement().startElement("b", "bar")
.writeAttribute("foo", new Date()).writeAttribute("bar", 123L).writeElementText(123.123).endElement()
.endElement().endElement().endContent().endEntry();
}
Document<Feed> doc = out.endFeed().endDocument().getBase();
doc.writeTo(System.out);
}
}
| 7,757 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/simple/LangTagExample.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.examples.simple;
import java.util.Locale;
import org.apache.abdera.i18n.rfc4646.Lang;
import org.apache.abdera.i18n.rfc4646.Range;
import org.apache.abdera.i18n.rfc4646.Subtag;
/**
* Example using the Lang tag implementation
*/
@SuppressWarnings("unused")
public class LangTagExample {
public static void main(String... args) throws Exception {
// English, written in Latin script, as spoken in California
Lang lang = new Lang("en-Latn-US-calif");
// Iterate over the tags
for (Subtag tag : lang)
System.out.println(tag.getType() + "\t" + tag.getName());
// Access individual tags
String language = lang.getLanguage().getName();
String script = lang.getScript().getName();
String region = lang.getRegion().getName();
String variant = lang.getVariant().getName();
// Perform extended range matching
Range range = new Range("en-US-*", true);
System.out.println(range.matches(lang, true));
// Locale integration
Locale locale = lang.getLocale();
System.out.println(locale);
}
}
| 7,758 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/simple/Parse.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.examples.simple;
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.Feed;
import org.apache.abdera.parser.Parser;
public class Parse {
public static void main(String[] args) throws Exception {
Parser parser = Abdera.getNewParser();
InputStream in = Parse.class.getResourceAsStream("/simple.xml");
Document<Feed> doc = parser.parse(in);
Feed feed = doc.getRoot();
System.out.println(feed.getTitle());
System.out.println(feed.getTitleType());
System.out.println(feed.getAlternateLink().getResolvedHref());
System.out.println(feed.getUpdated());
System.out.println(feed.getAuthor().getName());
System.out.println(feed.getId());
Entry entry = feed.getEntries().get(0);
System.out.println(entry.getTitle());
System.out.println(entry.getTitleType());
System.out.println(entry.getAlternateLink().getHref()); // relative URI
System.out.println(entry.getAlternateLink().getResolvedHref()); // absolute URI resolved against Base URI
System.out.println(entry.getId());
System.out.println(entry.getUpdated());
System.out.println(entry.getSummary());
System.out.println(entry.getSummaryType());
}
}
| 7,759 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/simple/PrintTitles.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.examples.simple;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import org.apache.abdera.Abdera;
import org.apache.abdera.filter.ListParseFilter;
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.Constants;
import org.apache.abdera.util.filter.WhiteListParseFilter;
/**
* Illustrates the use of optimized-parsing using the WhiteListParseFilter. Using this mechanism, only the elements
* added to the ParseFilter will be parsed and added to the Feed Object Model instance. The resulting savings in memory
* and CPU costs is significant.
*/
public class PrintTitles {
public static void main(String args[]) {
InputStream input;
Parser parser = Abdera.getNewParser();
try {
input = new URL(args[0]).openStream();
} catch (Exception e) {
e.printStackTrace();
return;
}
ParserOptions opts = parser.getDefaultParserOptions();
ListParseFilter filter = new WhiteListParseFilter();
filter.add(Constants.FEED);
filter.add(Constants.ENTRY);
filter.add(Constants.TITLE);
opts.setParseFilter(filter);
Document<Feed> doc;
try {
doc = parser.parse(input, "", opts);
} catch (Exception e) {
e.printStackTrace();
return;
}
Feed feed = doc.getRoot();
List<Entry> entries = feed.getEntries();
for (Entry e : entries) {
System.out.println(e.getTitle());
}
}
}
| 7,760 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/simple/EntityProviderExample.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.examples.simple;
import java.util.Date;
import org.apache.abdera.Abdera;
import org.apache.abdera.protocol.EntityProvider;
import org.apache.abdera.util.EntityTag;
import org.apache.abdera.writer.StreamWriter;
/**
* The EntityProvider interface allows developers to provide custom Object-to-Java serialization based on the
* StreamWriter interface.
*/
public class EntityProviderExample {
public static void main(String... args) throws Exception {
Abdera abdera = Abdera.getInstance();
StreamWriter sw = abdera.newStreamWriter().setOutputStream(System.out).setAutoIndent(true);
Foo foo = new Foo();
foo.writeTo(sw);
sw.close();
}
public static class Foo implements EntityProvider {
private static final String NS = "urn:foo";
private String foo = "foo";
private String bar = "bar";
private String baz = "baz";
public String getContentType() {
return "application/foo+xml";
}
public EntityTag getEntityTag() {
return EntityTag.generate(foo, bar, baz);
}
public Date getLastModified() {
return null;
}
public boolean isRepeatable() {
return true;
}
public void writeTo(StreamWriter sw) {
sw.startDocument().startElement(foo, NS).startElement(bar, NS).startElement(baz, NS).endElement()
.endElement().endElement().endDocument();
}
}
}
| 7,761 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/appserver | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/appserver/employee/EmployeeCollectionAdapter.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.examples.appserver.employee;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import javax.xml.namespace.QName;
import org.apache.abdera.Abdera;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.i18n.iri.IRI;
import org.apache.abdera.model.Content;
import org.apache.abdera.model.Element;
import org.apache.abdera.model.Person;
import org.apache.abdera.protocol.server.RequestContext;
import org.apache.abdera.protocol.server.ResponseContext;
import org.apache.abdera.protocol.server.context.ResponseContextException;
import org.apache.abdera.protocol.server.impl.AbstractEntityCollectionAdapter;
public class EmployeeCollectionAdapter extends AbstractEntityCollectionAdapter<Employee> {
private static final String ID_PREFIX = "tag:acme.com,2007:employee:entry:";
private AtomicInteger nextId = new AtomicInteger(1000);
private Map<Integer, Employee> employees = new HashMap<Integer, Employee>();
private Factory factory = new Abdera().getFactory();
// START SNIPPET: feedmetadata
/**
* A unique ID for this feed.
*/
public String getId(RequestContext request) {
return "tag:acme.com,2007:employee:feed";
}
/**
* The title of our collection.
*/
public String getTitle(RequestContext request) {
return "Acme Employee Database";
}
/**
* The author of this collection.
*/
public String getAuthor(RequestContext request) {
return "Acme Industries";
}
// END SNIPPET: feedmetadata
// START SNIPPET: getEntries
public Iterable<Employee> getEntries(RequestContext request) {
return employees.values();
}
// END SNIPPET: getEntries
// START SNIPPET: getEntry
public Employee getEntry(String resourceName, RequestContext request) throws ResponseContextException {
Integer id = getIdFromResourceName(resourceName);
return employees.get(id);
}
private Integer getIdFromResourceName(String resourceName) throws ResponseContextException {
int idx = resourceName.indexOf("-");
if (idx == -1) {
throw new ResponseContextException(404);
}
return new Integer(resourceName.substring(0, idx));
}
public String getName(Employee entry) {
return entry.getId() + "-" + entry.getName().replaceAll(" ", "_");
}
// END SNIPPET: getEntry
// START SNIPPET: entryMetadata
public String getId(Employee entry) {
return ID_PREFIX + entry.getId();
}
public String getTitle(Employee entry) {
return entry.getName();
}
public Date getUpdated(Employee entry) {
return entry.getUpdated();
}
public List<Person> getAuthors(Employee entry, RequestContext request) throws ResponseContextException {
Person author = request.getAbdera().getFactory().newAuthor();
author.setName("Acme Industries");
return Arrays.asList(author);
}
public Object getContent(Employee entry, RequestContext request) {
Content content = factory.newContent(Content.Type.TEXT);
content.setText(entry.getName());
return content;
}
// END SNIPPET: entryMetadata
// START SNIPPET: methods
public Employee postEntry(String title,
IRI id,
String summary,
Date updated,
List<Person> authors,
Content content,
RequestContext request) throws ResponseContextException {
Employee employee = new Employee();
employee.setName(content.getText().trim());
employee.setId(nextId.getAndIncrement());
employees.put(employee.getId(), employee);
return employee;
}
public void putEntry(Employee employee,
String title,
Date updated,
List<Person> authors,
String summary,
Content content,
RequestContext request) throws ResponseContextException {
employee.setName(content.getText().trim());
}
public void deleteEntry(String resourceName, RequestContext request) throws ResponseContextException {
Integer id = getIdFromResourceName(resourceName);
employees.remove(id);
}
// END SNIPPET: methods
}
| 7,762 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/appserver | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/appserver/employee/AppServer.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.examples.appserver.employee;
import javax.servlet.http.HttpServlet;
import org.apache.abdera.protocol.server.Provider;
import org.apache.abdera.protocol.server.impl.DefaultProvider;
import org.apache.abdera.protocol.server.impl.SimpleWorkspaceInfo;
import org.apache.abdera.protocol.server.servlet.AbderaServlet;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;
public class AppServer {
public static void main(String... args) throws Exception {
int port = 9002;
try {
port = args.length > 0 ? Integer.parseInt(args[0]) : 9002;
} catch (Exception e) {
}
Server server = new Server(port);
Context context = new Context(server, "/", Context.SESSIONS);
ServletHolder servletHolder = new ServletHolder(new EmployeeProviderServlet());
context.addServlet(servletHolder, "/*");
server.start();
server.join();
}
// START SNIPPET: servlet
public static final class EmployeeProviderServlet extends AbderaServlet {
protected Provider createProvider() {
EmployeeCollectionAdapter ca = new EmployeeCollectionAdapter();
ca.setHref("employee");
SimpleWorkspaceInfo wi = new SimpleWorkspaceInfo();
wi.setTitle("Employee Directory Workspace");
wi.addCollection(ca);
DefaultProvider provider = new DefaultProvider("/");
provider.addWorkspace(wi);
provider.init(getAbdera(), null);
return provider;
}
}
// END SNIPPET: servlet
}
| 7,763 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/appserver | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/appserver/employee/Employee.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.examples.appserver.employee;
import java.util.Date;
// START SNIPPET: employee
public class Employee {
private int id;
private String name;
private Date updated;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
}
// END SNIPPET: employee
| 7,764 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/appserver | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/appserver/custom/CustomProvider.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. The ASF licenses this file to You
* under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. For additional information regarding
* copyright in this work, please see the NOTICE file in the top level
* directory of this distribution.
*/
package org.apache.abdera.examples.appserver.custom;
import org.apache.abdera.protocol.server.CollectionAdapter;
import org.apache.abdera.protocol.server.Filter;
import org.apache.abdera.protocol.server.FilterChain;
import org.apache.abdera.protocol.server.RequestContext;
import org.apache.abdera.protocol.server.ResponseContext;
import org.apache.abdera.protocol.server.TargetType;
import org.apache.abdera.protocol.server.context.RequestContextWrapper;
import org.apache.abdera.protocol.server.impl.AbstractWorkspaceProvider;
import org.apache.abdera.protocol.server.impl.RegexTargetResolver;
import org.apache.abdera.protocol.server.impl.SimpleWorkspaceInfo;
import org.apache.abdera.protocol.server.impl.TemplateTargetBuilder;
public class CustomProvider extends AbstractWorkspaceProvider {
private final SimpleAdapter adapter;
public CustomProvider() {
// Create the adapter that will handle all of the requests processed by this provider
this.adapter = new SimpleAdapter();
// The target resolver provides the URL path mappings
super.setTargetResolver(new RegexTargetResolver().setPattern("/atom(\\?[^#]*)?", TargetType.TYPE_SERVICE)
.setPattern("/atom/([^/#?]+);categories", TargetType.TYPE_CATEGORIES, "collection")
.setPattern("/atom/([^/#?;]+)(\\?[^#]*)?", TargetType.TYPE_COLLECTION, "collection")
.setPattern("/atom/([^/#?]+)/([^/#?]+)(\\?[^#]*)?", TargetType.TYPE_ENTRY, "collection", "entry"));
// The target builder is used to construct url's for the various targets
setTargetBuilder(new TemplateTargetBuilder().setTemplate(TargetType.TYPE_SERVICE, "{target_base}/atom")
.setTemplate(TargetType.TYPE_COLLECTION,
"{target_base}/atom/{collection}{-opt|?|q,c,s,p,l,i,o}{-join|&|q,c,s,p,l,i,o}")
.setTemplate(TargetType.TYPE_CATEGORIES, "{target_base}/atom/{collection};categories")
.setTemplate(TargetType.TYPE_ENTRY, "{target_base}/atom/{collection}/{entry}"));
// Add a Workspace descriptor so the provider can generate an atompub service document
SimpleWorkspaceInfo workspace = new SimpleWorkspaceInfo();
workspace.setTitle("A Simple Workspace");
workspace.addCollection(adapter);
addWorkspace(workspace);
// Add one of more Filters to be invoked prior to invoking the Provider
addFilter(new SimpleFilter());
}
public CollectionAdapter getCollectionAdapter(RequestContext request) {
return adapter;
}
public class SimpleFilter implements Filter {
public ResponseContext filter(RequestContext request, FilterChain chain) {
RequestContextWrapper rcw = new RequestContextWrapper(request);
rcw.setAttribute("offset", 10);
rcw.setAttribute("count", 10);
return chain.next(rcw);
}
}
}
| 7,765 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/appserver | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/appserver/custom/SimpleAdapter.java | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. The ASF licenses this file to You
* under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License. For additional information regarding
* copyright in this work, please see the NOTICE file in the top level
* directory of this distribution.
*/
package org.apache.abdera.examples.appserver.custom;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.abdera.Abdera;
import org.apache.abdera.i18n.text.UrlEncoding;
import org.apache.abdera.model.Document;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Feed;
import org.apache.abdera.parser.ParseException;
import org.apache.abdera.protocol.server.ProviderHelper;
import org.apache.abdera.protocol.server.RequestContext;
import org.apache.abdera.protocol.server.ResponseContext;
import org.apache.abdera.protocol.server.TargetType;
import org.apache.abdera.protocol.server.RequestContext.Scope;
import org.apache.abdera.protocol.server.context.BaseResponseContext;
import org.apache.abdera.protocol.server.context.ResponseContextException;
import org.apache.abdera.protocol.server.context.StreamWriterResponseContext;
import org.apache.abdera.protocol.server.impl.AbstractCollectionAdapter;
import org.apache.abdera.util.Constants;
import org.apache.abdera.writer.StreamWriter;
@SuppressWarnings("unchecked")
public class SimpleAdapter extends AbstractCollectionAdapter {
@Override
public String getAuthor(RequestContext request) throws ResponseContextException {
return "Simple McGee";
}
@Override
public String getId(RequestContext request) {
return "tag:example.org,2008:feed";
}
public String getHref(RequestContext request) {
Map<String, Object> params = new HashMap<String, Object>();
params.put("collection", "feed");
return request.urlFor(TargetType.TYPE_COLLECTION, params);
}
public String getTitle(RequestContext request) {
return "A simple feed";
}
public ResponseContext extensionRequest(RequestContext request) {
return ProviderHelper.notallowed(request, "Method Not Allowed", ProviderHelper.getDefaultMethods(request));
}
private Document<Feed> getFeedDocument(RequestContext context) throws ResponseContextException {
Feed feed = (Feed)context.getAttribute(Scope.SESSION, "feed");
if (feed == null) {
feed = createFeedBase(context);
feed.setBaseUri(getFeedBaseUri(context));
context.setAttribute(Scope.SESSION, "feed", feed);
}
return feed.getDocument();
}
private String getFeedBaseUri(RequestContext context) {
Map<String, String> params = new HashMap<String, String>();
params.put("collection", context.getTarget().getParameter("collection"));
String uri = context.urlFor(TargetType.TYPE_COLLECTION, params);
return context.getResolvedUri().resolve(uri).toString();
}
public ResponseContext getFeed(RequestContext request) {
Document<Feed> feed;
try {
feed = getFeedDocument(request);
} catch (ResponseContextException e) {
return e.getResponseContext();
}
return ProviderHelper.returnBase(feed, 200, feed.getRoot().getUpdated()).setEntityTag(ProviderHelper
.calculateEntityTag(feed.getRoot()));
}
public ResponseContext deleteEntry(RequestContext request) {
Entry entry = getAbderaEntry(request);
if (entry != null)
entry.discard();
return ProviderHelper.nocontent();
}
public ResponseContext getEntry(RequestContext request) {
Entry entry = (Entry)getAbderaEntry(request);
if (entry != null) {
Feed feed = entry.getParentElement();
entry = (Entry)entry.clone();
entry.setSource(feed.getAsSource());
Document<Entry> entry_doc = entry.getDocument();
return ProviderHelper.returnBase(entry_doc, 200, entry.getEdited()).setEntityTag(ProviderHelper
.calculateEntityTag(entry));
} else {
return ProviderHelper.notfound(request);
}
}
public ResponseContext postEntry(RequestContext request) {
Abdera abdera = request.getAbdera();
try {
Document<Entry> entry_doc = (Document<Entry>)request.getDocument(abdera.getParser()).clone();
if (entry_doc != null) {
Entry entry = entry_doc.getRoot();
if (!ProviderHelper.isValidEntry(entry))
return ProviderHelper.badrequest(request);
setEntryDetails(request, entry, abdera.getFactory().newUuidUri());
Feed feed = getFeedDocument(request).getRoot();
feed.insertEntry(entry);
feed.setUpdated(new Date());
BaseResponseContext rc =
(BaseResponseContext)ProviderHelper.returnBase(entry, 201, entry.getEdited());
return rc.setLocation(ProviderHelper.resolveBase(request).resolve(entry.getEditLinkResolvedHref())
.toString()).setContentLocation(rc.getLocation().toString()).setEntityTag(ProviderHelper
.calculateEntityTag(entry));
} else {
return ProviderHelper.badrequest(request);
}
} catch (ParseException pe) {
return ProviderHelper.notsupported(request);
} catch (ClassCastException cce) {
return ProviderHelper.notsupported(request);
} catch (Exception e) {
return ProviderHelper.badrequest(request);
}
}
private void setEntryDetails(RequestContext request, Entry entry, String id) {
entry.setUpdated(new Date());
entry.setEdited(entry.getUpdated());
entry.getIdElement().setValue(id);
entry.addLink(getEntryLink(request, entry.getId().toASCIIString()), "edit");
}
private String getEntryLink(RequestContext request, String entryid) {
Map<String, String> params = new HashMap<String, String>();
params.put("collection", request.getTarget().getParameter("collection"));
params.put("entry", entryid);
return request.urlFor(TargetType.TYPE_ENTRY, params);
}
public ResponseContext putEntry(RequestContext request) {
Abdera abdera = request.getAbdera();
Entry orig_entry = getAbderaEntry(request);
if (orig_entry != null) {
try {
Document<Entry> entry_doc = (Document<Entry>)request.getDocument(abdera.getParser()).clone();
if (entry_doc != null) {
Entry entry = entry_doc.getRoot();
if (!entry.getId().equals(orig_entry.getId()))
return ProviderHelper.conflict(request);
if (!ProviderHelper.isValidEntry(entry))
return ProviderHelper.badrequest(request);
setEntryDetails(request, entry, orig_entry.getId().toString());
orig_entry.discard();
Feed feed = getFeedDocument(request).getRoot();
feed.insertEntry(entry);
feed.setUpdated(new Date());
return ProviderHelper.nocontent();
} else {
return ProviderHelper.badrequest(request);
}
} catch (ParseException pe) {
return ProviderHelper.notsupported(request);
} catch (ClassCastException cce) {
return ProviderHelper.notsupported(request);
} catch (Exception e) {
return ProviderHelper.badrequest(request);
}
} else {
return ProviderHelper.notfound(request);
}
}
private Entry getAbderaEntry(RequestContext request) {
try {
return getFeedDocument(request).getRoot().getEntry(getEntryID(request));
} catch (Exception e) {
}
return null;
}
public String getEntryID(RequestContext request) {
if (request.getTarget().getType() != TargetType.TYPE_ENTRY)
return null;
String[] segments = request.getUri().toString().split("/");
return UrlEncoding.decode(segments[segments.length - 1]);
}
public ResponseContext getCategories(RequestContext request) {
return new StreamWriterResponseContext(request.getAbdera()) {
protected void writeTo(StreamWriter sw) throws IOException {
sw.startDocument().startCategories(false).writeCategory("foo").writeCategory("bar")
.writeCategory("baz").endCategories().endDocument();
}
}.setStatus(200).setContentType(Constants.CAT_MEDIA_TYPE);
}
}
| 7,766 |
0 | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/appserver | Create_ds/abdera/examples/src/main/java/org/apache/abdera/examples/appserver/custom/AppServer.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.examples.appserver.custom;
import org.apache.abdera.protocol.server.ServiceManager;
import org.apache.abdera.protocol.server.servlet.AbderaServlet;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.Context;
import org.mortbay.jetty.servlet.ServletHolder;
public class AppServer {
public static void main(String... args) throws Exception {
int port = 9002;
try {
port = args.length > 0 ? Integer.parseInt(args[0]) : 9002;
} catch (Exception e) {
}
Server server = new Server(port);
Context context = new Context(server, "/", Context.SESSIONS);
ServletHolder servletHolder = new ServletHolder(new AbderaServlet());
servletHolder.setInitParameter(ServiceManager.PROVIDER, CustomProvider.class.getName());
context.addServlet(servletHolder, "/*");
server.start();
server.join();
}
}
| 7,767 |
0 | Create_ds/abdera/client/src/test/java/org/apache/abdera/test | Create_ds/abdera/client/src/test/java/org/apache/abdera/test/client/JettyUtil.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.client;
import org.apache.axiom.testutils.PortAllocator;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.servlet.ServletHandler;
public class JettyUtil {
private static final String PORT_PROP = "abdera.test.client.port";
private static int PORT = PortAllocator.allocatePort();
private static Server server = null;
private static ServletHandler handler = null;
public static int getPort() {
if (System.getProperty(PORT_PROP) != null) {
PORT = Integer.parseInt(System.getProperty(PORT_PROP));
}
return PORT;
}
private static void initServer() throws Exception {
server = new Server();
Connector connector = new SocketConnector();
connector.setPort(getPort());
server.setConnectors(new Connector[] {connector});
handler = new ServletHandler();
server.setHandler(handler);
}
public static void addServlet(String _class, String path) {
try {
if (server == null)
initServer();
} catch (Exception e) {
}
handler.addServletWithMapping(_class, path);
}
public static void start() throws Exception {
if (server == null)
initServer();
if (server.isRunning())
return;
server.start();
}
public static void stop() throws Exception {
if (server == null)
return;
server.stop();
server = null;
}
public static boolean isRunning() {
return (server != null);
}
}
| 7,768 |
0 | Create_ds/abdera/client/src/test/java/org/apache/abdera/test | Create_ds/abdera/client/src/test/java/org/apache/abdera/test/client/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.client;
import org.apache.abdera.test.client.app.AppTest;
import org.apache.abdera.test.client.cache.CacheTest;
import org.apache.abdera.test.client.util.MultipartRelatedRequestEntityTest;
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(CacheTest.class, AppTest.class, MultipartRelatedRequestEntityTest.class);
}
}
| 7,769 |
0 | Create_ds/abdera/client/src/test/java/org/apache/abdera/test/client | Create_ds/abdera/client/src/test/java/org/apache/abdera/test/client/app/AppTest.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.client.app;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.activation.MimeType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.abdera.Abdera;
import org.apache.abdera.factory.Factory;
import org.apache.abdera.i18n.iri.IRI;
import org.apache.abdera.model.Collection;
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.model.Workspace;
import org.apache.abdera.parser.Parser;
import org.apache.abdera.parser.ParserOptions;
import org.apache.abdera.protocol.client.AbderaClient;
import org.apache.abdera.protocol.client.ClientResponse;
import org.apache.abdera.protocol.client.RequestOptions;
import org.apache.abdera.test.client.JettyUtil;
import org.apache.abdera.util.EntityTag;
import org.apache.abdera.util.MimeTypeHelper;
import org.apache.abdera.writer.WriterOptions;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Test to make sure that we can operate as a simple APP client
*/
@SuppressWarnings("serial")
public class AppTest {
protected static void getServletHandler(String... servletMappings) {
for (int n = 0; n < servletMappings.length; n = n + 2) {
String name = servletMappings[n];
String root = servletMappings[n + 1];
JettyUtil.addServlet(name, root);
}
}
protected String getBase() {
return "http://localhost:" + JettyUtil.getPort();
}
@BeforeClass
public static void setUp() throws Exception {
getServletHandler();
JettyUtil.start();
}
@AfterClass
public static void tearDown() throws Exception {
JettyUtil.stop();
}
private static Abdera abdera = new Abdera();
private static Factory getFactory() {
return abdera.getFactory();
}
private static Parser getParser() {
return abdera.getParser();
}
private static AppTest INSTANCE = null;
private static Document<Service> init_service_document(String base) {
try {
Service service = getFactory().newService();
Workspace workspace = service.addWorkspace("Test");
workspace.addCollection("Entries", base + "/collections/entries").setAcceptsEntry();
workspace.addCollection("Other", base + "/collections/other").setAccept("text/plain");
Document<Service> doc = service.getDocument();
return doc;
} catch (Exception e) {
}
return null;
}
private static Document<Feed> init_entries_document(String base) {
try {
Feed feed = getFactory().newFeed();
feed.setId(base + "/collections/entries");
feed.setTitle("Entries");
feed.setUpdated(new Date());
feed.addLink(base + "/collections/entries");
feed.addLink(base + "/collections/entries", "self");
feed.addAuthor("James");
Document<Feed> doc = feed.getDocument();
return doc;
} catch (Exception e) {
}
return null;
}
public static class ServiceDocumentServlet extends HttpServlet {
private Document<Service> service = init_service_document(AppTest.INSTANCE.getBase());
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/atomsvc+xml; charset=utf-8");
WriterOptions options = service.getDefaultWriterOptions();
options.setCharset("UTF-8");
service.writeTo(response.getOutputStream(), options);
}
}
/**
* this implements a very simple (and quite buggy) APP server. It's just enough for us to test the client behaviors.
* I'm sure it could be greatly improved.
*/
public static class CollectionServlet extends HttpServlet {
protected Document<Feed> feed = init_entries_document(AppTest.INSTANCE.getBase());
protected Map<String, String> media = new HashMap<String, String>();
private String[] tokens = null;
private final static int COLLECTION = 0;
private final static int ENTRY = 1;
private final static int MEDIA = 2;
private int getTargetType(HttpServletRequest request) {
tokens = request.getRequestURI().split("/");
if (tokens[2].equals("entries") && tokens.length == 3)
return COLLECTION;
if (tokens[2].equals("entries") && tokens.length == 4)
return ENTRY;
if (tokens[2].equals("media") && tokens.length == 4)
return MEDIA;
return -1;
}
private int getTarget() {
return (tokens.length != 4) ? -1 : Integer.parseInt(tokens[3]);
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
int t = getTargetType(request);
switch (t) {
case COLLECTION:
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/atom+xml; charset=utf-8");
WriterOptions options = feed.getDefaultWriterOptions();
options.setCharset("UTF-8");
feed.writeTo(response.getOutputStream(), options);
break;
case ENTRY:
try {
Entry entry = feed.getRoot().getEntries().get(getTarget());
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/atom+xml; charset=utf-8");
options = entry.getDefaultWriterOptions();
options.setCharset("UTF-8");
entry.writeTo(response.getOutputStream(), options);
} catch (Exception e) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
break;
}
break;
case MEDIA:
try {
String m = media.get(AppTest.INSTANCE.getBase() + "/collections/entries/" + getTarget());
if (m != null) {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/plain");
response.getWriter().write(m);
break;
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
} catch (Exception e) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
int t = getTargetType(request);
switch (t) {
case COLLECTION:
try {
if (MimeTypeHelper.isMatch(request.getContentType(), "application/atom+xml;type=entry")) {
MimeType type = new MimeType(request.getContentType());
String charset = type.getParameter("charset");
String uri = AppTest.INSTANCE.getBase() + "/collections/entries";
ParserOptions options = getParser().getDefaultParserOptions();
options.setCharset(charset);
Document<?> doc = getParser().parse(request.getInputStream(), uri, options);
if (doc.getRoot() instanceof Entry) {
Entry entry = (Entry)doc.getRoot().clone();
String newID =
AppTest.INSTANCE.getBase() + "/collections/entries/"
+ feed.getRoot().getEntries().size();
entry.setId(newID);
entry.setUpdated(new Date());
entry.addLink(entry.getId().toString(), "edit");
entry.addLink(entry.getId().toString(), "self");
feed.getRoot().insertEntry(entry);
response.setStatus(HttpServletResponse.SC_CREATED);
response.setHeader("Location", entry.getId().toString());
response.setHeader("Content-Location", entry.getId().toString());
WriterOptions woptions = entry.getDefaultWriterOptions();
woptions.setCharset("UTF-8");
entry.writeTo(response.getOutputStream(), woptions);
return;
}
}
if (MimeTypeHelper.isMatch(request.getContentType(), "text/plain")) {
int n = feed.getRoot().getEntries().size();
String media = read(request.getInputStream());
Entry entry = getFactory().newEntry();
String newID = AppTest.INSTANCE.getBase() + "/collections/entries/" + n;
String slug = request.getHeader("Slug");
entry.setId(newID);
entry.setTitle(slug);
entry.setUpdated(new Date());
entry.setSummary(slug);
entry.addLink(entry.getId().toString(), "edit");
entry.addLink(AppTest.INSTANCE.getBase() + "/collections/media/" + n, "edit-media")
.setMimeType("text/plain");
entry.addLink(entry.getId().toString(), "self");
entry.setContent(new IRI(AppTest.INSTANCE.getBase() + "/collections/media/" + n),
"text/plain");
feed.getRoot().insertEntry(entry);
this.media.put(entry.getId().toString(), media);
response.setStatus(HttpServletResponse.SC_CREATED);
response.setHeader("Location", entry.getId().toString());
response.setHeader("Content-Location", entry.getId().toString());
WriterOptions woptions = entry.getDefaultWriterOptions();
woptions.setCharset("UTF-8");
entry.writeTo(response.getOutputStream(), woptions);
return;
}
response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
} catch (Exception e) {
}
break;
default:
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
}
}
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
int t = getTargetType(request);
int target = getTarget();
switch (t) {
case ENTRY:
try {
if (MimeTypeHelper.isMatch(request.getContentType(), "application/atom+xml;type=entry")) {
Entry entry = feed.getRoot().getEntries().get(target);
MimeType type = new MimeType(request.getContentType());
String charset = type.getParameter("charset");
String uri = AppTest.INSTANCE.getBase() + "/collections/entries/" + target;
ParserOptions options = getParser().getDefaultParserOptions();
options.setCharset(charset);
Document<?> doc = getParser().parse(request.getInputStream(), uri, options);
if (doc.getRoot() instanceof Entry) {
Entry newentry = (Entry)doc.getRoot().clone();
if (newentry.getId().equals(entry.getId())) {
newentry.setUpdated(new Date());
entry.discard();
feed.getRoot().insertEntry(newentry);
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
return;
} else {
response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Cannot change atom:id");
return;
}
}
}
response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
} catch (Exception e) {
}
break;
case MEDIA:
if (MimeTypeHelper.isMatch(request.getContentType(), "text/plain")) {
String uri = AppTest.INSTANCE.getBase() + "/collections/entries/" + target;
String media = read(request.getInputStream());
this.media.put(uri, media);
Entry entry = feed.getRoot().getEntries().get(target);
entry.setUpdated(new Date());
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
return;
}
response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
break;
default:
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
}
}
protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
int t = getTargetType(request);
int target = getTarget();
switch (t) {
case ENTRY:
case MEDIA:
String uri = AppTest.INSTANCE.getBase() + "/collections/entries/" + target;
Entry entry = feed.getRoot().getEntries().get(target);
entry.discard();
media.remove(uri);
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
return;
default:
response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
}
}
}
private static String read(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int m = -1;
while ((m = in.read()) != -1) {
out.write(m);
}
String resp = new String(out.toByteArray());
return resp.trim();
}
public AppTest() {
AppTest.INSTANCE = this;
}
protected static void getServletHandler() {
getServletHandler(ServiceDocumentServlet.class.getName(),
"/service",
CollectionServlet.class.getName(),
"/collections/*");
}
@Test
public void testRequestOptions() throws Exception {
AbderaClient abderaClient = new AbderaClient();
RequestOptions options = abderaClient.getDefaultRequestOptions();
options.setIfModifiedSince(new Date());
assertNotNull(options.getIfModifiedSince());
options.set4xxRequestException(true);
assertTrue(options.is4xxRequestException());
options.set5xxRequestException(true);
assertTrue(options.is5xxRequestException());
options.setAccept("text/plain");
assertEquals("text/plain", options.getAccept());
options.setAcceptCharset("UTF-8");
assertEquals("UTF-8", options.getAcceptCharset());
options.setAcceptEncoding("gzip");
assertEquals("gzip", options.getAcceptEncoding());
options.setAcceptLanguage("en-US");
assertEquals("en-US", options.getAcceptLanguage());
options.setAuthorization("auth");
assertEquals("auth", options.getAuthorization());
options.setCacheControl("no-cache");
assertEquals("no-cache", options.getCacheControl());
options.setContentType("text/plain");
assertTrue(MimeTypeHelper.isMatch(options.getContentType(), new MimeType("text/plain")));
options.setEncodedHeader("foo", "UTF-8", "bar");
assertEquals("bar", options.getDecodedHeader("foo"));
options.setHeader("foo", "bar");
assertEquals("bar", options.getHeader("foo"));
options.setIfMatch("testing");
assertTrue(EntityTag.matchesAny(new EntityTag("testing"), options.getIfMatch()));
options.setIfNoneMatch("testing");
assertTrue(EntityTag.matchesAny(new EntityTag("testing"), options.getIfNoneMatch()));
options.setSlug("This is the slug");
assertEquals("This is the slug", options.getSlug());
options.setUsePostOverride(true);
assertTrue(options.isUsePostOverride());
}
@Test
public void testAppClient() throws Exception {
AbderaClient abderaClient = new AbderaClient();
Entry entry = getFactory().newEntry();
RequestOptions options = abderaClient.getDefaultRequestOptions();
options.setHeader("Connection", "close");
options.setUseExpectContinue(false);
// do the introspection step
ClientResponse response = abderaClient.get("http://localhost:" + JettyUtil.getPort() + "/service", options);
String col_uri;
try {
assertEquals(200, response.getStatus());
Document<Service> service_doc = response.getDocument();
assertNotNull(service_doc);
assertEquals(1, service_doc.getRoot().getWorkspaces().size());
Workspace workspace = service_doc.getRoot().getWorkspace("Test");
assertNotNull(workspace);
for (Collection c : workspace.getCollections()) {
assertNotNull(c.getTitle());
assertNotNull(c.getHref());
}
col_uri = getBase() + "/collections/entries";
} finally {
response.release();
}
// post a new entry
response = abderaClient.post(col_uri, entry, options);
String self_uri;
try {
assertEquals(201, response.getStatus());
assertNotNull(response.getLocation());
assertNotNull(response.getContentLocation());
self_uri = response.getLocation().toString();
} finally {
response.release();
}
// get the collection to see if our entry is there
response = abderaClient.get(col_uri, options);
try {
assertEquals(200, response.getStatus());
Document<Feed> feed_doc = response.getDocument();
assertEquals(1, feed_doc.getRoot().getEntries().size());
} finally {
response.release();
}
// get the entry to see if we can get it
response = abderaClient.get(self_uri, options);
String edit_uri;
try {
assertEquals(200, response.getStatus());
Document<Entry> entry_doc = response.getDocument();
// this isn't always true, but for our tests they are the same
assertEquals(self_uri, entry_doc.getRoot().getId().toString());
// get the edit uri from the entry
edit_uri = entry_doc.getRoot().getEditLink().getHref().toString();
// change the entry
Document<Entry> doc = response.getDocument();
entry = (Entry)doc.getRoot().clone();
entry.setTitle("New title");
} finally {
response.release();
}
// submit the changed entry back to the server
response = abderaClient.put(edit_uri, entry, options);
try {
assertEquals(204, response.getStatus());
} finally {
response.release();
}
// check to see if the entry was modified properly
response = abderaClient.get(self_uri, options);
try {
assertEquals(200, response.getStatus());
Document<Entry> entry_doc = response.getDocument();
assertEquals("New title", entry_doc.getRoot().getTitle());
} finally {
response.release();
}
// delete the entry
response = abderaClient.delete(edit_uri, options);
try {
assertEquals(204, response.getStatus());
} finally {
response.release();
}
// is it gone?
response = abderaClient.get(self_uri, options);
try {
assertEquals(404, response.getStatus());
} finally {
response.release();
}
// YAY! We're a working APP client
// Now let's try to do a media post
// Post the media resource
options = abderaClient.getDefaultRequestOptions();
options.setContentType("text/plain");
options.setHeader("Connection", "close");
options.setUseExpectContinue(false);
response = abderaClient.post(col_uri, new ByteArrayInputStream("test".getBytes()), options);
try {
assertEquals(201, response.getStatus());
assertNotNull(response.getLocation());
assertNotNull(response.getContentLocation());
self_uri = response.getLocation().toString();
} finally {
response.release();
}
// was an entry created?
options = abderaClient.getDefaultRequestOptions();
options.setHeader("Connection", "close");
response = abderaClient.get(self_uri, options);
String edit_media, media;
try {
assertEquals(200, response.getStatus());
Document<Entry> entry_doc = response.getDocument();
// this isn't always true, but for our tests they are the same
assertEquals(self_uri, entry_doc.getRoot().getId().toString());
// get the right links from the entry
edit_uri = entry_doc.getRoot().getEditLink().getHref().toString();
edit_media = entry_doc.getRoot().getLink("edit-media").getHref().toString();
media = entry_doc.getRoot().getContentElement().getSrc().toString();
// edit the entry
Document<Entry> doc = response.getDocument();
entry = (Entry)doc.getRoot().clone();
entry.setTitle("New title");
} finally {
response.release();
}
// submit the changes
options = abderaClient.getDefaultRequestOptions();
options.setContentType("application/atom+xml;type=entry");
options.setHeader("Connection", "close");
options.setUseExpectContinue(false);
response = abderaClient.put(edit_uri, entry, options);
try {
assertEquals(204, response.getStatus());
} finally {
response.release();
}
// get the media resource
response = abderaClient.get(media);
try {
assertEquals(200, response.getStatus());
String mediavalue = read(response.getInputStream());
assertEquals("test", mediavalue);
} finally {
response.release();
}
// edit the media resource
options = abderaClient.getDefaultRequestOptions();
options.setHeader("Connection", "close");
options.setContentType("text/plain");
options.setUseExpectContinue(false);
response = abderaClient.put(edit_media, new ByteArrayInputStream("TEST".getBytes()), options);
try {
assertEquals(204, response.getStatus());
} finally {
response.release();
}
// was the resource changed?
response = abderaClient.get(media, options);
try {
assertEquals(200, response.getStatus());
String mediavalue = read(response.getInputStream());
assertEquals("TEST", mediavalue);
} finally {
response.release();
}
// delete the entry
response = abderaClient.delete(edit_uri, options);
try {
assertEquals(204, response.getStatus());
} finally {
response.release();
}
// is the entry gone?
response = abderaClient.get(self_uri, options);
try {
assertEquals(404, response.getStatus());
} finally {
response.release();
}
// is the media resource gone?
options.setNoCache(true); // need to force revalidation to check
response = abderaClient.get(media, options);
try {
assertEquals(404, response.getStatus());
} finally {
response.release();
}
// YAY! We can handle media link entries
}
@Test
public void testEntityTag() throws Exception {
EntityTag tag1 = new EntityTag("tag");
EntityTag tag2 = new EntityTag("tag", true); // weak;
assertFalse(tag1.isWeak());
assertTrue(tag2.isWeak());
assertFalse(EntityTag.matches(tag1, tag2));
assertFalse(EntityTag.matchesAny(tag1, new EntityTag[] {tag2}));
assertEquals("\"tag\"", tag1.toString());
assertEquals("W/\"tag\"", tag2.toString());
tag1 = EntityTag.parse("\"tag\"");
assertFalse(tag1.isWeak());
assertEquals("tag", tag1.getTag());
tag2 = EntityTag.parse("W/\"tag\"");
assertTrue(tag2.isWeak());
assertEquals("tag", tag2.getTag());
EntityTag[] tags = EntityTag.parseTags("\"tag1\", W/\"tag2\"");
assertFalse(tags[0].isWeak());
assertEquals("tag1", tags[0].getTag());
assertTrue(tags[1].isWeak());
assertEquals("tag2", tags[1].getTag());
}
}
| 7,770 |
0 | Create_ds/abdera/client/src/test/java/org/apache/abdera/test/client | Create_ds/abdera/client/src/test/java/org/apache/abdera/test/client/cache/CacheTest.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.client.cache;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertNotNull;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.Assert;
import org.apache.abdera.protocol.client.AbderaClient;
import org.apache.abdera.protocol.client.ClientResponse;
import org.apache.abdera.protocol.client.RequestOptions;
import org.apache.abdera.protocol.client.cache.CachedResponse;
import org.apache.abdera.test.client.JettyUtil;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* These cache tests were originally based on Mark Nottingham's javascript cache tests, available at:
* http://www.mnot.net/javascript/xmlhttprequest/cache.html They have since been modified to use an embedded Jetty
* server instead of going off over the internet to hit Mark's server, since there are too many things that can get in
* the way of those sort things (proxies, intermediate caches, etc) if you try to talk to a remote server.
*/
@SuppressWarnings("serial")
public class CacheTest {
private static String CHECK_CACHE_INVALIDATE;
private static String CHECK_NO_CACHE;
// private static String CHECK_AUTH;
private static String CHECK_MUST_REVALIDATE;
public CacheTest() {
String base = getBase();
CHECK_CACHE_INVALIDATE = base + "/check_cache_invalidate";
CHECK_NO_CACHE = base + "/no_cache";
// CHECK_AUTH = base + "/auth";
CHECK_MUST_REVALIDATE = base + "/must_revalidate";
}
protected static void getServletHandler(String... servletMappings) {
for (int n = 0; n < servletMappings.length; n = n + 2) {
String name = servletMappings[n];
String root = servletMappings[n + 1];
JettyUtil.addServlet(name, root);
}
}
protected String getBase() {
return "http://localhost:" + JettyUtil.getPort();
}
@BeforeClass
public static void setUp() throws Exception {
getServletHandler();
JettyUtil.start();
}
@AfterClass
public static void tearDown() throws Exception {
JettyUtil.stop();
}
protected static void getServletHandler() {
getServletHandler("org.apache.abdera.test.client.cache.CacheTest$CheckCacheInvalidateServlet",
"/check_cache_invalidate",
"org.apache.abdera.test.client.cache.CacheTest$NoCacheServlet",
"/no_cache",
"org.apache.abdera.test.client.cache.CacheTest$AuthServlet",
"/auth",
"org.apache.abdera.test.client.cache.CacheTest$CheckMustRevalidateServlet",
"/must_revalidate");
}
public static class CheckMustRevalidateServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
String reqnum = request.getHeader("X-Reqnum");
int req = Integer.parseInt(reqnum);
if (req == 1) {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/plain");
response.setHeader("Cache-Control", "must-revalidate");
response.setDateHeader("Date", System.currentTimeMillis());
response.getWriter().println(reqnum);
response.getWriter().close();
} else if (req == 2) {
response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
response.setContentType("text/plain");
response.setDateHeader("Date", System.currentTimeMillis());
return;
} else if (req == 3) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
response.setDateHeader("Date", System.currentTimeMillis());
return;
}
}
}
public static class CheckCacheInvalidateServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
String reqnum = request.getHeader("X-Reqnum");
response.setStatus(HttpServletResponse.SC_OK);
response.setDateHeader("Date", System.currentTimeMillis());
response.setContentType("text/plain");
response.setHeader("Cache-Control", "max-age=60");
response.getWriter().println(reqnum);
response.getWriter().close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
}
protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
}
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
}
}
public static class NoCacheServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
String reqnum = request.getHeader("X-Reqnum");
int reqtest = Integer.parseInt(request.getHeader("X-Reqtest"));
response.setContentType("text/plain");
response.setStatus(HttpServletResponse.SC_OK);
switch (reqtest) {
case NOCACHE:
response.setHeader("Cache-Control", "no-cache");
break;
case NOSTORE:
response.setHeader("Cache-Control", "no-store");
break;
case MAXAGE0:
response.setHeader("Cache-Control", "max-age=0");
break;
}
response.setDateHeader("Date", System.currentTimeMillis());
response.getWriter().println(reqnum);
response.getWriter().close();
}
}
public static class AuthServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
String reqnum = request.getHeader("X-Reqnum");
int num = Integer.parseInt(reqnum);
switch (num) {
case 1:
response.setStatus(HttpServletResponse.SC_OK);
break;
case 2:
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
break;
default:
response.setStatus(HttpServletResponse.SC_OK);
break;
}
response.setDateHeader("Date", System.currentTimeMillis());
response.setContentType("text/plain");
response.getWriter().println(reqnum);
response.getWriter().close();
}
}
private static final int NOCACHE = 0;
private static final int NOSTORE = 1;
private static final int MAXAGE0 = 2;
private static final int POST = 3;
private static final int DELETE = 4;
private static final int PUT = 5;
@Test
public void testRequestNoStore() throws Exception {
_requestCacheInvalidation(NOSTORE);
}
@Test
public void testRequestNoCache() throws Exception {
_requestCacheInvalidation(NOCACHE);
}
@Test
public void testRequestMaxAge0() throws Exception {
_requestCacheInvalidation(MAXAGE0);
}
@Test
public void testResponseNoStore() throws Exception {
_responseNoCache(NOSTORE);
}
@Test
public void testResponseNoCache() throws Exception {
_responseNoCache(NOCACHE);
}
@Test
public void testResponseMaxAge0() throws Exception {
_responseNoCache(MAXAGE0);
}
@Test
public void testPostInvalidates() throws Exception {
_methodInvalidates(POST);
}
@Test
public void testPutInvalidates() throws Exception {
_methodInvalidates(PUT);
}
@Test
public void testDeleteInvalidates() throws Exception {
_methodInvalidates(DELETE);
}
@Test
public void testAuthForcesRevalidation() throws Exception {
// TODO: Actually need to rethink this. Responses to authenticated requests
// should never be cached unless the resource is explicitly marked as
// being cacheable (e.g. using Cache-Control: public). So this test
// was testing incorrect behavior.
// AbderaClient client = new CommonsClient();
// client.usePreemptiveAuthentication(true);
// client.addCredentials(CHECK_AUTH, null, null, new UsernamePasswordCredentials("james","snell"));
// RequestOptions options = client.getDefaultRequestOptions();
// options.setHeader("Connection", "close");
// options.setRevalidateWithAuth(true);
// options.setHeader("x-reqnum", "1");
// Response response = client.get(CHECK_AUTH, options);
//
// // first request works as expected. fills the cache
// String resp1 = getResponse(response);
// assertEquals(resp1, "1");
//
// // second request uses authentication, should force revalidation of the cache
// options.setHeader("x-reqnum", "2");
// response = client.get(CHECK_AUTH, options);
//
// resp1 = getResponse(response);
// assertEquals(response.getStatus(), HttpServletResponse.SC_UNAUTHORIZED);
// assertEquals(resp1, "2");
//
// // third request does not use authentication, but since the previous request
// // resulted in an "unauthorized" response, the cache needs to be refilled
// options.setHeader("x-reqnum", "3");
// client.usePreemptiveAuthentication(false);
// response = client.get(CHECK_AUTH, options);
//
// resp1 = getResponse(response);
// assertEquals(response.getStatus(), HttpServletResponse.SC_OK);
// assertEquals(resp1, "3");
//
// // fourth request does not use authentication, will pull from the cache
// options = client.getDefaultRequestOptions();
// options.setHeader("x-reqnum", "4");
// client.usePreemptiveAuthentication(false);
// response = client.get(CHECK_AUTH, options);
//
// resp1 = getResponse(response);
// assertEquals(response.getStatus(), HttpServletResponse.SC_OK);
// assertEquals(resp1, "3");
//
// // fifth request uses authentication, will force revalidation
// options.setAuthorization("Basic amFtZXM6c25lbGw=");
// options.setHeader("x-reqnum", "5");
// response = client.get(CHECK_AUTH, options);
//
// resp1 = getResponse(response);
// assertEquals(response.getStatus(), HttpServletResponse.SC_OK);
// assertEquals(resp1, "5");
}
@Test
public void testResponseMustRevalidate() throws Exception {
AbderaClient abderaClient = new AbderaClient();
RequestOptions options = abderaClient.getDefaultRequestOptions();
options.setHeader("Connection", "close");
options.setHeader("x-reqnum", "1");
ClientResponse response = abderaClient.get(CHECK_MUST_REVALIDATE, options);
String resp1 = getResponse(response);
assertEquals("1", resp1);
// Should be revalidated and use the cache
options.setHeader("x-reqnum", "2");
response = abderaClient.get(CHECK_MUST_REVALIDATE, options);
assertTrue(response instanceof CachedResponse);
String resp2 = getResponse(response);
assertEquals("1", resp2);
// Should be revalidated and return a 404
options.setHeader("x-reqnum", "3");
response = abderaClient.get(CHECK_MUST_REVALIDATE, options);
assertEquals(404, response.getStatus());
response.release();
}
private RequestOptions getRequestOptions(AbderaClient client, int num) {
RequestOptions options = client.getDefaultRequestOptions();
options.setHeader("Connection", "close");
options.setHeader("x-reqnum", String.valueOf(num));
options.setUseExpectContinue(false);
return options;
}
private void _methodInvalidates(int type) throws Exception {
AbderaClient abderaClient = new AbderaClient();
RequestOptions options = getRequestOptions(abderaClient, 1);
ClientResponse response = abderaClient.get(CHECK_CACHE_INVALIDATE, options);
String resp1 = getResponse(response);
response.release();
assertEquals("1", resp1);
// calling a method that could change state on the server should invalidate the cache
options = getRequestOptions(abderaClient, 2);
switch (type) {
case POST:
response = abderaClient.post(CHECK_CACHE_INVALIDATE, new ByteArrayInputStream("".getBytes()), options);
break;
case PUT:
response = abderaClient.put(CHECK_CACHE_INVALIDATE, new ByteArrayInputStream("".getBytes()), options);
break;
case DELETE:
response = abderaClient.delete(CHECK_CACHE_INVALIDATE, options);
break;
}
response.release();
options = getRequestOptions(abderaClient, 3);
response = abderaClient.get(CHECK_CACHE_INVALIDATE, options);
resp1 = getResponse(response);
response.release();
assertEquals("3", resp1);
}
private void _requestCacheInvalidation(int type) throws Exception {
AbderaClient abderaClient = new AbderaClient();
RequestOptions options = getRequestOptions(abderaClient, 1);
ClientResponse response = abderaClient.get(CHECK_CACHE_INVALIDATE, options);
String resp1 = getResponse(response);
assertEquals("1", resp1);
// Should not use the cache
options = getRequestOptions(abderaClient, 2);
switch (type) {
case NOCACHE:
options.setNoCache(true);
break;
case NOSTORE:
options.setNoStore(true);
break;
case MAXAGE0:
options.setMaxAge(0);
break;
}
response = abderaClient.get(CHECK_CACHE_INVALIDATE, options);
String resp2 = getResponse(response);
assertEquals("2", resp2);
// Should use the cache
options = getRequestOptions(abderaClient, 3);
switch (type) {
case NOCACHE:
options.setNoCache(false);
break;
case NOSTORE:
options.setNoStore(false);
break;
case MAXAGE0:
options.setMaxAge(60);
break;
}
response = abderaClient.get(CHECK_CACHE_INVALIDATE, options);
String resp3 = getResponse(response);
assertEquals("2", resp3);
}
private void _responseNoCache(int type) throws Exception {
AbderaClient abderaClient = new AbderaClient();
RequestOptions options = getRequestOptions(abderaClient, 1);
options.setHeader("x-reqtest", String.valueOf(type));
ClientResponse response = abderaClient.get(CHECK_NO_CACHE, options);
String resp1 = getResponse(response);
assertEquals("1", resp1);
// Should not use the cache
options = getRequestOptions(abderaClient, 2);
options.setHeader("x-reqtest", String.valueOf(type));
response = abderaClient.get(CHECK_NO_CACHE, options);
String resp2 = getResponse(response);
assertEquals("2", resp2);
// Should use the cache
options = getRequestOptions(abderaClient, 3);
options.setHeader("x-reqtest", String.valueOf(type));
response = abderaClient.get(CHECK_NO_CACHE, options);
String resp3 = getResponse(response);
assertEquals("3", resp3);
}
private static String getResponse(ClientResponse response) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int m = -1;
InputStream in = response.getInputStream();
while ((m = in.read()) != -1) {
out.write(m);
}
in.close();
String resp = new String(out.toByteArray());
return resp.trim();
}
@Test
public void testInitCache() {
AbderaClient client = new AbderaClient();
assertNotNull(client.getCache());
}
}
| 7,771 |
0 | Create_ds/abdera/client/src/test/java/org/apache/abdera/test/client | Create_ds/abdera/client/src/test/java/org/apache/abdera/test/client/util/MultipartRelatedRequestEntityTest.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.client.util;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import javax.activation.MimeType;
import org.apache.abdera.Abdera;
import org.apache.abdera.i18n.iri.IRI;
import org.apache.abdera.model.Entry;
import org.apache.abdera.protocol.client.util.MultipartRelatedRequestEntity;
import org.apache.abdera.util.MimeTypeHelper;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.junit.Test;
import org.mortbay.io.WriterOutputStream;
public class MultipartRelatedRequestEntityTest {
@Test
public void testMultipartFormat() throws IOException {
Entry entry = Abdera.getInstance().newEntry();
entry.setTitle("my image");
entry.addAuthor("david");
entry.setId("tag:apache.org,2008:234534344");
entry.setSummary("multipart test");
entry.setContent(new IRI("cid:234234@example.com"), "image/jpg");
RequestEntity request =
new MultipartRelatedRequestEntity(entry, this.getClass().getResourceAsStream("info.png"), "image/jpg",
"asdfasdfasdf");
StringWriter sw = new StringWriter();
WriterOutputStream os = new WriterOutputStream(sw);
request.writeRequest(os);
String multipart = sw.toString();
// System.out.println(sw.toString());
assertTrue(multipart.contains("content-id: <234234@example.com>"));
assertTrue(multipart.contains("content-type: image/jpg"));
}
@Test
public void testMultimediaRelatedContentType() throws Exception {
MimeType type = new MimeType("Multipart/Related;boundary=\"35245352345sdfg\"");
assertTrue(MimeTypeHelper.isMatch("Multipart/Related", type.toString()));
assertEquals("35245352345sdfg", type.getParameter("boundary"));
}
// @Test
public void testMultipartEncoding() throws Exception {
InputStream input = this.getClass().getResourceAsStream("info.png");
int BUFF_SIZE = 1024;
byte[] line = new byte[BUFF_SIZE];
ByteArrayOutputStream output = new ByteArrayOutputStream();
while (input.read(line) != -1) {
output.write(line);
}
Base64 base64 = new Base64();
byte[] encoded = base64.encode(output.toByteArray());
ByteArrayInputStream bi = new ByteArrayInputStream(base64.decode(encoded));
File f = new File("info-out.png");
if (f.exists())
f.delete();
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
int end;
while ((end = bi.read(line)) != -1) {
fo.write(line, 0, end);
}
fo.flush();
fo.close();
}
}
| 7,772 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/CommonsResponse.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.client;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.abdera.Abdera;
import org.apache.abdera.i18n.text.io.CompressionUtil;
import org.apache.abdera.protocol.client.util.AutoReleasingInputStream;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.URIException;
public class CommonsResponse extends AbstractClientResponse implements ClientResponse {
private final HttpMethod method;
protected CommonsResponse(Abdera abdera, HttpMethod method) {
super(abdera);
if (method.isRequestSent())
this.method = method;
else
throw new IllegalStateException();
parse_cc();
getServerDate();
}
public HttpMethod getHttpMethod() {
return method;
}
/**
* Return the request method
*/
public String getMethod() {
return method.getName();
}
/**
* Return the status code of the response
*/
public int getStatus() {
return method.getStatusCode();
}
/**
* Return the status text of the response
*/
public String getStatusText() {
return method.getStatusText();
}
/**
* Release the resources associated with this response
*/
public void release() {
method.releaseConnection();
}
/**
* Return the value of the named HTTP header
*/
public String getHeader(String header) {
Header h = method.getResponseHeader(header);
return h != null ? h.getValue() : null;
}
/**
* Return the values of the named HTTP header
*/
public Object[] getHeaders(String header) {
Header[] headers = method.getResponseHeaders(header);
List<Object> values = new ArrayList<Object>();
for (Header h : headers) {
values.add(h.getValue());
}
return values.toArray(new Object[values.size()]);
}
/**
* Return all of the HTTP headers
*/
public Map<String, Object[]> getHeaders() {
Header[] headers = method.getResponseHeaders();
Map<String, Object[]> map = new HashMap<String, Object[]>();
for (Header header : headers) {
Object[] values = map.get(header.getName());
List<Object> list = values == null ? new ArrayList<Object>() : Arrays.asList(values);
list.add(header.getValue());
map.put(header.getName(), list.toArray(new Object[list.size()]));
}
return java.util.Collections.unmodifiableMap(map);
}
/**
* Return a listing of HTTP header names
*/
public String[] getHeaderNames() {
Header[] headers = method.getResponseHeaders();
List<String> list = new ArrayList<String>();
for (Header h : headers) {
String name = h.getName();
if (!list.contains(name))
list.add(name);
}
return list.toArray(new String[list.size()]);
}
/**
* Return the request URI
*/
public String getUri() {
try {
return method.getURI().toString();
} catch (URIException e) {
}
return null; // shouldn't happen
}
/**
* Return the inputstream for reading the content of the response. The InputStream returned will automatically
* decode Content-Encodings and will automatically release the response when the stream has been read fully.
*/
public InputStream getInputStream() throws IOException {
if (in == null ) {
String ce = getHeader("Content-Encoding");
in = method.getResponseBodyAsStream();
if (ce != null && in != null) {
in = CompressionUtil.getDecodingInputStream(in, ce);
}
in = new AutoReleasingInputStream(method, in);
}
return in;
}
}
| 7,773 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/AbstractClientResponse.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.client;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.Date;
import javax.activation.MimeType;
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.ParseException;
import org.apache.abdera.parser.Parser;
import org.apache.abdera.parser.ParserOptions;
import org.apache.abdera.protocol.util.AbstractResponse;
import org.apache.abdera.protocol.util.CacheControlUtil;
import org.apache.abdera.util.EntityTag;
import org.apache.commons.httpclient.util.DateParseException;
import org.apache.commons.httpclient.util.DateUtil;
/**
* Abstract base class for a ClientResponse
*/
public abstract class AbstractClientResponse extends AbstractResponse implements ClientResponse {
protected final Abdera abdera;
protected final Parser parser;
protected final Date now = new Date();
protected InputStream in = null;
protected Date response_date = null;
protected AbstractClientResponse(Abdera abdera) {
this.abdera = abdera;
this.parser = abdera.getParser();
}
protected Date initResponseDate() {
Date date = getDateHeader("Date");
return (date != null) ? date : now;
}
protected synchronized Parser getParser() {
return parser;
}
/**
* Get the response payload as a parsed Abdera FOM Document
*/
public <T extends Element> Document<T> getDocument() throws ParseException {
return getDocument(getParser());
}
/**
* Get the response payload as a parsed Abdera FOM Document using the specified parser options
*
* @param options The parser options
*/
public <T extends Element> Document<T> getDocument(ParserOptions options) throws ParseException {
return getDocument(getParser(), options);
}
/**
* Get the response payload as a parsed Abdera FOM Document using the specified parser
*
* @param parser The parser
*/
public <T extends Element> Document<T> getDocument(Parser parser) throws ParseException {
return getDocument(parser, parser.getDefaultParserOptions());
}
/**
* Get the response payload as a parsed Abdera FOM Document using the specified parser and parser options
*
* @param parser The parser
* @param options The parser options
*/
public <T extends Element> Document<T> getDocument(Parser parser, ParserOptions options) throws ParseException {
try {
if (options == null)
options = parser.getDefaultParserOptions();
String charset = getCharacterEncoding();
if (charset != null)
options.setCharset(charset);
IRI cl = getContentLocation();
if (cl != null && !cl.isAbsolute()) {
IRI r = new IRI(getUri());
cl = r.resolve(cl);
}
String base = (cl != null) ? cl.toASCIIString() : getUri();
Document<T> doc = parser.parse(getReader(), base, options);
EntityTag etag = getEntityTag();
if (etag != null)
doc.setEntityTag(etag);
Date lm = getLastModified();
if (lm != null)
doc.setLastModified(lm);
MimeType mt = getContentType();
if (mt != null)
doc.setContentType(mt.toString());
String language = getContentLanguage();
if (language != null)
doc.setLanguage(language);
String slug = getSlug();
if (slug != null)
doc.setSlug(slug);
return doc;
} catch (Exception e) {
throw new ParseException(e);
}
}
/**
* Get the response payload as an input stream
*/
public InputStream getInputStream() throws IOException {
return in;
}
/**
* Set the response input stream (used internally by Abdera)
*/
public void setInputStream(InputStream in) {
this.in = in;
}
/**
* Get the response payload as a reader (assumed UTF-8 charset)
*/
public Reader getReader() throws IOException {
String charset = getCharacterEncoding();
return getReader(charset != null ? charset : "UTF-8");
}
/**
* Get the response payload as a reader using the specified charset
*
* @param charset The character set encoding
*/
public Reader getReader(String charset) throws IOException {
if (charset == null)
charset = "UTF-8";
return new InputStreamReader(getInputStream(), charset);
}
/**
* Return the date returned by the server in the response
*/
public Date getServerDate() {
if (response_date == null)
response_date = initResponseDate();
return response_date;
}
protected void parse_cc() {
String cc = getHeader("Cache-Control");
if (cc != null)
CacheControlUtil.parseCacheControl(cc, this);
}
/**
* Get the character set encoding specified by the server in the Content-Type header
*/
public String getCharacterEncoding() {
String charset = null;
try {
MimeType mt = getContentType();
if (mt != null)
charset = mt.getParameter("charset");
} catch (Exception e) {
}
return charset;
}
/**
* Return the named HTTP header as a java.util.Date
*/
public Date getDateHeader(String header) {
try {
String value = getHeader(header);
if (value != null)
return DateUtil.parseDate(value);
else
return null;
} catch (DateParseException e) {
return null; // treat other invalid date formats, especially including the value "0", as in the past
}
}
}
| 7,774 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/AbderaClient.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.client;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.net.ssl.TrustManager;
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.model.Entry;
import org.apache.abdera.protocol.EntityProvider;
import org.apache.abdera.protocol.Response.ResponseType;
import org.apache.abdera.protocol.client.cache.Cache;
import org.apache.abdera.protocol.client.cache.CacheFactory;
import org.apache.abdera.protocol.client.cache.CachedResponse;
import org.apache.abdera.protocol.client.cache.LRUCache;
import org.apache.abdera.protocol.client.cache.Cache.Disposition;
import org.apache.abdera.protocol.client.util.BaseRequestEntity;
import org.apache.abdera.protocol.client.util.EntityProviderRequestEntity;
import org.apache.abdera.protocol.client.util.MethodHelper;
import org.apache.abdera.protocol.client.util.MultipartRelatedRequestEntity;
import org.apache.abdera.protocol.client.util.SimpleSSLProtocolSocketFactory;
import org.apache.abdera.protocol.error.Error;
import org.apache.abdera.protocol.error.ProtocolException;
import org.apache.abdera.protocol.util.CacheControlUtil;
import org.apache.abdera.util.EntityTag;
import org.apache.abdera.util.Version;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.Credentials;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.auth.AuthPolicy;
import org.apache.commons.httpclient.auth.AuthScheme;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.Protocol;
import org.apache.commons.httpclient.protocol.ProtocolSocketFactory;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
/**
* An Atom Publishing Protocol client.
*/
@SuppressWarnings( {"unchecked", "deprecation"})
public class AbderaClient {
public static final String DEFAULT_USER_AGENT = Version.APP_NAME + "/" + Version.VERSION;
public static int DEFAULT_MAX_REDIRECTS = 10;
protected final Abdera abdera;
protected final Cache cache;
private final HttpClient client;
public AbderaClient() {
this(new Abdera(), DEFAULT_USER_AGENT);
}
/**
* Create an AbderaClient instance using the specified useragent name
*
* @param useragent
*/
public AbderaClient(String useragent) {
this(new Abdera(), useragent);
}
/**
* Create an AbderaClient instance using the specified Abdera instance and useragent name
*
* @param abdera
* @param useragent
*/
public AbderaClient(Abdera abdera, String useragent) {
this(abdera, useragent, initCache(abdera));
}
/**
* Create an AbderaClient instance using the specified Abdera instance and useragent name
*
* @param abdera
* @param useragent
*/
public AbderaClient(Abdera abdera, String useragent, Cache cache) {
this.abdera = abdera;
this.cache = cache;
MultiThreadedHttpConnectionManager connManager = new MultiThreadedHttpConnectionManager();
client = new HttpClient(connManager);
client.getParams().setParameter(HttpClientParams.USER_AGENT, useragent);
client.getParams().setBooleanParameter(HttpClientParams.USE_EXPECT_CONTINUE, true);
client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
setAuthenticationSchemeDefaults();
setMaximumRedirects(DEFAULT_MAX_REDIRECTS);
}
/**
* Create an Abdera using a preconfigured HttpClient object
*
* @param client An Apache HttpClient object
*/
public AbderaClient(HttpClient client) {
this(new Abdera(), client);
}
/**
* Create an Abdera using a preconfigured HttpClient object
*
* @param abdera
* @param client An Apache HttpClient object
*/
public AbderaClient(Abdera abdera, HttpClient client) {
this(abdera, client, initCache(abdera));
}
/**
* Create an Abdera using a preconfigured HttpClient object
*
* @param abdera
* @param client An Apache HttpClient object
*/
public AbderaClient(Abdera abdera, HttpClient client, Cache cache) {
this.abdera = abdera;
this.cache = cache;
this.client = client;
setAuthenticationSchemeDefaults();
setMaximumRedirects(DEFAULT_MAX_REDIRECTS);
}
/**
* Create an AbderaClient instance using the specified Abdera instance
*
* @param abdera
*/
public AbderaClient(Abdera abdera) {
this(abdera, DEFAULT_USER_AGENT);
}
/**
* Create an AbderaClient instance using the specified Abdera instance
*
* @param abdera
*/
public AbderaClient(Abdera abdera, Cache cache) {
this(abdera, DEFAULT_USER_AGENT, cache);
}
/**
* Returns the client HTTP cache instance
*/
public Cache getCache() {
return cache;
}
/**
* @deprecated The CacheFactory interface is no longer used.
*/
public Cache initCache(CacheFactory factory) {
return initCache(abdera);
}
/**
* Initializes the client HTTP cache
*/
public static Cache initCache(Abdera abdera) {
return new LRUCache(abdera);
}
/**
* Sends an HTTP HEAD request to the specified URI.
*
* @param uri The request URI
* @param options The request options
*/
public ClientResponse head(String uri, RequestOptions options) {
return execute("HEAD", uri, (RequestEntity)null, options);
}
/**
* Sends an HTTP GET request to the specified URI.
*
* @param uri The request URI
* @param options The request options
*/
public ClientResponse get(String uri, RequestOptions options) {
return execute("GET", uri, (RequestEntity)null, options);
}
/**
* Sends an HTTP POST request to the specified URI.
*
* @param uri The request URI
* @param provider An EntityProvider implementation providing the payload of the request
* @param options The request options
*/
public ClientResponse post(String uri, EntityProvider provider, RequestOptions options) {
return post(uri, new EntityProviderRequestEntity(abdera, provider, options.isUseChunked()), options);
}
/**
* Sends an HTTP POST request to the specified URI.
*
* @param uri The request URI
* @param entity A RequestEntity object providing the payload of the request
* @param options The request options
*/
public ClientResponse post(String uri, RequestEntity entity, RequestOptions options) {
return execute("POST", uri, entity, options);
}
/**
* Sends an HTTP POST request to the specified URI.
*
* @param uri The request URI
* @param in An InputStream providing the payload of the request
* @param options The request options
*/
public ClientResponse post(String uri, InputStream in, RequestOptions options) {
return execute("POST", uri, new InputStreamRequestEntity(in), options);
}
/**
* Sends an HTTP POST request to the specified URI.
*
* @param uri The request URI
* @param base An Abdera FOM Document or Element object providing the payload of the request
* @param options The request options
*/
public ClientResponse post(String uri, Base base, RequestOptions options) {
if (base instanceof Document) {
Document d = (Document)base;
if (options.getSlug() == null && d.getSlug() != null)
options.setSlug(d.getSlug());
}
return execute("POST", uri, new BaseRequestEntity(base, options.isUseChunked()), options);
}
/**
* Sends an HTTP POST request to the specified URI. It uses the media and entry parameters to create a
* multipart/related object. If the contentType is not provided this method tries to get it from the type attribute
* of the entry content.
*
* @param uri The request URI
* @param entry The entry that will be sent as the first element of the multipart/related object
* @param media The media object that will be sent as the second element of the multipart/related object
*/
public ClientResponse post(String uri, Entry entry, InputStream media) {
return post(uri, entry, media, getDefaultRequestOptions());
}
/**
* Sends an HTTP POST request to the specified URI. It uses the media and entry parameters to create a
* multipart/related object. If the contentType is not provided this method tries to get it from the type attribute
* of the entry content.
*
* @param uri The request URI
* @param entry The entry that will be sent as the first element of the multipart/related object
* @param media The media object that will be sent as the second element of the multipart/related object
* @param options The request options
*/
public ClientResponse post(String uri, Entry entry, InputStream media, RequestOptions options) {
return post(uri, entry, media, null, options);
}
/**
* Sends an HTTP POST request to the specified URI. It uses the media and entry parameters to create a
* multipart/related object.
*
* @param uri The request URI
* @param entry The entry that will be sent as the first element of the multipart/related object
* @param media The media object that will be sent as the second element of the multipart/related object
* @param contentType the content type of the media object
* @param options The request options
*/
public ClientResponse post(String uri, Entry entry, InputStream media, String contentType, RequestOptions options) {
return execute("POST", uri, new MultipartRelatedRequestEntity(entry, media, contentType), options);
}
/**
* Sends an HTTP PUT request to the specified URI.
*
* @param uri The request URI
* @param provider An EntityProvider implementation providing the payload of the request
* @param options The request options
*/
public ClientResponse put(String uri, EntityProvider provider, RequestOptions options) {
if (options == null)
options = getDefaultRequestOptions();
if (options.isConditionalPut()) {
EntityTag etag = provider.getEntityTag();
if (etag != null)
options.setIfMatch(etag);
else {
Date lm = provider.getLastModified();
if (lm != null)
options.setIfUnmodifiedSince(lm);
}
}
return put(uri, new EntityProviderRequestEntity(abdera, provider, options.isUseChunked()), options);
}
/**
* Sends an HTTP PUT request to the specified URI.
*
* @param uri The request URI
* @param entity A RequestEntity object providing the payload of the request
* @param options The request options
*/
public ClientResponse put(String uri, RequestEntity entity, RequestOptions options) {
return execute("PUT", uri, entity, options);
}
/**
* Sends an HTTP PUT request to the specified URI.
*
* @param uri The request URI
* @param in An InputStream providing the payload of the request
* @param options The request options
*/
public ClientResponse put(String uri, InputStream in, RequestOptions options) {
return execute("PUT", uri, new InputStreamRequestEntity(in), options);
}
/**
* Sends an HTTP PUT request to the specified URI.
*
* @param uri The request URI
* @param base A FOM Document or Element providing the payload of the request
* @param options The request options
*/
public ClientResponse put(String uri, Base base, RequestOptions options) {
if (options == null)
options = getDefaultRequestOptions();
if (base instanceof Document) {
Document d = (Document)base;
if (options.getSlug() == null && d.getSlug() != null)
options.setSlug(d.getSlug());
if (options.isConditionalPut()) {
if (d.getEntityTag() != null)
options.setIfMatch(d.getEntityTag());
else if (d.getLastModified() != null)
options.setIfUnmodifiedSince(d.getLastModified());
}
}
return execute("PUT", uri, new BaseRequestEntity(base, options.isUseChunked()), options);
}
/**
* Sends an HTTP DELETE request to the specified URI.
*
* @param uri The request URI
* @param options The request options
*/
public ClientResponse delete(String uri, RequestOptions options) {
return execute("DELETE", uri, (RequestEntity)null, options);
}
/**
* Sends an HTTP HEAD request to the specified URI using the default options
*
* @param uri The request URI
*/
public ClientResponse head(String uri) {
return head(uri, getDefaultRequestOptions());
}
/**
* Sends an HTTP GET request to the specified URI using the default options
*
* @param uri The request URI
*/
public ClientResponse get(String uri) {
return get(uri, getDefaultRequestOptions());
}
/**
* Sends an HTTP POST request to the specified URI using the default options
*
* @param uri The request URI
* @param provider An EntityProvider implementation providing the payload the request
*/
public ClientResponse post(String uri, EntityProvider provider) {
return post(uri, provider, getDefaultRequestOptions());
}
/**
* Sends an HTTP POST request to the specified URI using the default options
*
* @param uri The request URI
* @param entity A RequestEntity object providing the payload of the request
*/
public ClientResponse post(String uri, RequestEntity entity) {
return post(uri, entity, getDefaultRequestOptions());
}
/**
* Sends an HTTP POST request to the specified URI using the default options
*
* @param uri The request URI
* @param in An InputStream providing the payload of the request
*/
public ClientResponse post(String uri, InputStream in) {
return post(uri, in, getDefaultRequestOptions());
}
/**
* Sends an HTTP POST request to the specified URI using the default options
*
* @param uri The request URI
* @param base A FOM Document or Element providing the payload of the request
*/
public ClientResponse post(String uri, Base base) {
return post(uri, base, getDefaultRequestOptions());
}
/**
* Sends an HTTP PUT request to the specified URI using the default options
*
* @param uri The request URI
* @param provider An EntityProvider implementation providing the payload of the request
*/
public ClientResponse put(String uri, EntityProvider provider) {
return put(uri, provider, getDefaultRequestOptions());
}
/**
* Sends an HTTP PUT request to the specified URI using the default options
*
* @param uri The request URI
* @param entity A RequestEntity object providing the payload of the request
*/
public ClientResponse put(String uri, RequestEntity entity) {
return put(uri, entity, getDefaultRequestOptions());
}
/**
* Sends an HTTP PUT request to the specified URI using the default options
*
* @param uri The request URI
* @param in An InputStream providing the payload of the request
*/
public ClientResponse put(String uri, InputStream in) {
return put(uri, in, getDefaultRequestOptions());
}
/**
* Sends an HTTP PUT request to the specified URI using the default options
*
* @param uri The request URI
* @param base A FOM Document or Element providing the payload of the request
*/
public ClientResponse put(String uri, Base base) {
return put(uri, base, getDefaultRequestOptions());
}
/**
* Sends an HTTP DELETE request to the specified URI using the default options
*
* @param uri The request URI
*/
public ClientResponse delete(String uri) {
return delete(uri, getDefaultRequestOptions());
}
/**
* Register a new authentication scheme.
*
* @param name
* @param scheme
*/
public static void registerScheme(String name, Class<? extends AuthScheme> scheme) {
AuthPolicy.registerAuthScheme(name, scheme);
}
/**
* Unregister a specific authentication scheme
*
* @param name The name of the authentication scheme (e.g. "basic", "digest", etc)
*/
public static void unregisterScheme(String name) {
AuthPolicy.unregisterAuthScheme(name);
}
/**
* Unregister multiple HTTP authentication schemes
*/
public static void unregisterScheme(String... names) {
for (String name : names)
unregisterScheme(name);
}
/**
* Register the specified TrustManager for SSL support on the default port (443)
*
* @param trustManager The TrustManager implementation
*/
public static void registerTrustManager(TrustManager trustManager) {
registerTrustManager(trustManager, 443);
}
/**
* Register the default TrustManager for SSL support on the default port (443)
*/
public static void registerTrustManager() {
registerTrustManager(443);
}
/**
* Register the specified TrustManager for SSL support on the specified port
*
* @param trustManager The TrustManager implementation
* @param port The port
*/
public static void registerTrustManager(TrustManager trustManager, int port) {
SimpleSSLProtocolSocketFactory f = new SimpleSSLProtocolSocketFactory(trustManager);
registerFactory(f, port);
}
/**
* Register the default trust manager on the specified port
*
* @param port The port
*/
public static void registerTrustManager(int port) {
SimpleSSLProtocolSocketFactory f = new SimpleSSLProtocolSocketFactory();
registerFactory(f, port);
}
/**
* Register the specified secure socket factory on the specified port
*/
public static void registerFactory(SecureProtocolSocketFactory factory, int port) {
Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory)factory, port));
}
/**
* Configure the client to use preemptive authentication (HTTP Basic Authentication only)
*/
public AbderaClient usePreemptiveAuthentication(boolean val) {
client.getParams().setAuthenticationPreemptive(val);
return this;
}
private boolean useCache(String method, RequestOptions options) {
return (CacheControlUtil.isIdempotent(method)) && !options.isNoCache()
&& !options.isNoStore()
&& options.getUseLocalCache();
}
private boolean mustRevalidate(RequestOptions options, CachedResponse response) {
if (options.getRevalidateWithAuth()) {
if (options.getAuthorization() != null)
return true;
if (client.getParams().getBooleanParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, false))
return true;
if (response != null) {
if (response.isPublic())
return false;
}
}
return false;
}
/**
* Sends the specified method request to the specified URI. This can be used to send extension HTTP methods to a
* server (e.g. PATCH, LOCK, etc)
*
* @param method The HTTP method
* @param uri The request URI
* @param base A FOM Document and Element providing the payload for the request
* @param options The Request Options
*/
public ClientResponse execute(String method, String uri, Base base, RequestOptions options) {
return execute(method, uri, new BaseRequestEntity(base), options);
}
/**
* Sends the specified method request to the specified URI. This can be used to send extension HTTP methods to a
* server (e.g. PATCH, LOCK, etc)
*
* @param method The HTTP method
* @param uri The request URI
* @param provider An EntityProvider implementation providing the payload of the request
* @param options The Request Options
*/
public ClientResponse execute(String method, String uri, EntityProvider provider, RequestOptions options) {
if (options == null)
options = getDefaultRequestOptions();
return execute(method, uri, new EntityProviderRequestEntity(abdera, provider, options.isUseChunked()), options);
}
/**
* Sends the specified method request to the specified URI. This can be used to send extension HTTP methods to a
* server (e.g. PATCH, LOCK, etc)
*
* @param method The HTTP method
* @param uri The request URI
* @param in An InputStream providing the payload of the request
* @param options The Request Options
*/
public ClientResponse execute(String method, String uri, InputStream in, RequestOptions options) {
RequestEntity re = null;
try {
if (options.getContentType() != null) {
re = new InputStreamRequestEntity(in, options.getContentType().toString());
} else {
re = new InputStreamRequestEntity(in);
}
} catch (Exception e) {
re = new InputStreamRequestEntity(in);
}
return execute(method, uri, re, options);
}
private Disposition getCacheDisposition(boolean usecache,
String uri,
RequestOptions options,
CachedResponse cached_response) {
Disposition disp = (usecache) ? cache.disposition(uri, options) : Disposition.TRANSPARENT;
disp =
(!disp.equals(Disposition.TRANSPARENT) && mustRevalidate(options, cached_response)) ? Disposition.STALE
: disp;
return disp;
}
/**
* Sends the specified method request to the specified URI. This can be used to send extension HTTP methods to a
* server (e.g. PATCH, LOCK, etc)
*
* @param method The HTTP method
* @param uri The request URI
* @param entity A RequestEntity object providing the payload for the request
* @param options The Request Options
*/
public ClientResponse execute(String method, String uri, RequestEntity entity, RequestOptions options) {
boolean usecache = useCache(method, options);
options = options != null ? options : getDefaultRequestOptions();
try {
Cache cache = getCache();
CachedResponse cached_response = cache.get(uri);
switch (getCacheDisposition(usecache, uri, options, cached_response)) {
case FRESH: // CACHE HIT: FRESH
if (cached_response != null)
return checkRequestException(cached_response, options);
case STALE: // CACHE HIT: STALE
// revalidate the cached entry
if (cached_response != null) {
if (cached_response.getEntityTag() != null)
options.setIfNoneMatch(cached_response.getEntityTag().toString());
else if (cached_response.getLastModified() != null)
options.setIfModifiedSince(cached_response.getLastModified());
else
options.setNoCache(true);
}
default: // CACHE MISS
HttpMethod httpMethod = MethodHelper.createMethod(method, uri, entity, options);
client.executeMethod(httpMethod);
if (usecache && (httpMethod.getStatusCode() == 304 || httpMethod.getStatusCode() == 412)
&& cached_response != null)
return cached_response;
ClientResponse response = new CommonsResponse(abdera, httpMethod);
response =
options.getUseLocalCache() ? response = cache.update(uri, options, response, cached_response)
: response;
return checkRequestException(response, options);
}
} catch (RuntimeException r) {
throw r;
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
private ClientResponse checkRequestException(ClientResponse response, RequestOptions options) {
if (response == null)
return response;
ResponseType type = response.getType();
if ((type.equals(ResponseType.CLIENT_ERROR) && options.is4xxRequestException()) || (type
.equals(ResponseType.SERVER_ERROR) && options.is5xxRequestException())) {
try {
Document<Element> doc = response.getDocument();
org.apache.abdera.protocol.error.Error error = null;
if (doc != null) {
Element root = doc.getRoot();
if (root instanceof Error) {
error = (Error)root;
}
}
if (error == null)
error =
org.apache.abdera.protocol.error.Error.create(abdera, response.getStatus(), response
.getStatusText());
error.throwException();
} catch (ProtocolException pe) {
throw pe;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return response;
}
/**
* Get a copy of the default request options
*/
public RequestOptions getDefaultRequestOptions() {
return MethodHelper.createDefaultRequestOptions();
}
/**
* Add authentication credentials
*/
public AbderaClient addCredentials(String target, String realm, String scheme, Credentials credentials)
throws URISyntaxException {
String host = AuthScope.ANY_HOST;
int port = AuthScope.ANY_PORT;
if (target != null) {
URI uri = new URI(target);
host = uri.getHost();
port = uri.getPort();
}
AuthScope scope =
new AuthScope(host, port, (realm != null) ? realm : AuthScope.ANY_REALM, (scheme != null) ? scheme
: AuthScope.ANY_SCHEME);
client.getState().setCredentials(scope, credentials);
return this;
}
/**
* Configure the client to use the default authentication scheme settings
*/
public AbderaClient setAuthenticationSchemeDefaults() {
List authPrefs = AuthPolicy.getDefaultAuthPrefs();
client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
return this;
}
/**
* When multiple authentication schemes are supported by a server, the client will automatically select a scheme
* based on the configured priority. For instance, to tell the client to prefer "digest" over "basic", set the
* priority by calling setAuthenticationSchemePriority("digest","basic")
*/
public AbderaClient setAuthenticationSchemePriority(String... scheme) {
List authPrefs = java.util.Arrays.asList(scheme);
client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
return this;
}
/**
* Returns the current listing of preferred authentication schemes, in order of preference
*
* @see setAuthenticationSchemePriority
*/
public String[] getAuthenticationSchemePriority() {
List list = (List)client.getParams().getParameter(AuthPolicy.AUTH_SCHEME_PRIORITY);
return (String[])list.toArray(new String[list.size()]);
}
/**
* <p>
* Per http://jakarta.apache.org/commons/httpclient/performance.html
* </p>
* <blockquote> Generally it is recommended to have a single instance of HttpClient per communication component or
* even per application. However, if the application makes use of HttpClient only very infrequently, and keeping an
* idle instance of HttpClient in memory is not warranted, it is highly recommended to explicitly shut down the
* multithreaded connection manager prior to disposing the HttpClient instance. This will ensure proper closure of
* all HTTP connections in the connection pool. </blockquote>
*/
public AbderaClient teardown() {
((MultiThreadedHttpConnectionManager)client.getHttpConnectionManager()).shutdown();
return this;
}
/**
* Set the maximum number of connections allowed for a single host
*/
public AbderaClient setMaxConnectionsPerHost(int max) {
Map<HostConfiguration, Integer> m = new HashMap<HostConfiguration, Integer>();
m.put(HostConfiguration.ANY_HOST_CONFIGURATION, max);
client.getHttpConnectionManager().getParams().setParameter(HttpConnectionManagerParams.MAX_HOST_CONNECTIONS, m);
return this;
}
/**
* Return the maximum number of connections allowed for a single host
*/
public int getMaxConnectionsPerHost() {
Map<HostConfiguration, Integer> m =
(Map<HostConfiguration, Integer>)client.getHttpConnectionManager().getParams()
.getParameter(HttpConnectionManagerParams.MAX_HOST_CONNECTIONS);
if (m == null)
return MultiThreadedHttpConnectionManager.DEFAULT_MAX_HOST_CONNECTIONS;
Integer i = m.get(HostConfiguration.ANY_HOST_CONFIGURATION);
return i != null ? i.intValue() : MultiThreadedHttpConnectionManager.DEFAULT_MAX_HOST_CONNECTIONS;
}
/**
* Return the maximum number of connections allowed for the client
*/
public AbderaClient setMaxConnectionsTotal(int max) {
client.getHttpConnectionManager().getParams()
.setIntParameter(HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, max);
return this;
}
/**
* Return the maximum number of connections allowed for the client
*/
public int getMaxConnectionsTotal() {
return client.getHttpConnectionManager().getParams()
.getIntParameter(HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS,
MultiThreadedHttpConnectionManager.DEFAULT_MAX_TOTAL_CONNECTIONS);
}
/**
* Configure the client to use the specified proxy
*/
public AbderaClient setProxy(String host, int port) {
client.getHostConfiguration().setProxy(host, port);
return this;
}
/**
* Specify the auth credentials for the proxy server
*/
public AbderaClient setProxyCredentials(String host, int port, Credentials credentials) {
setProxyCredentials(host, port, null, null, credentials);
return this;
}
/**
* Specify the auth credentials for the proxy server
*/
public AbderaClient setProxyCredentials(String host, int port, String realm, String scheme, Credentials credentials) {
host = host != null ? host : AuthScope.ANY_HOST;
port = port > -1 ? port : AuthScope.ANY_PORT;
AuthScope scope =
new AuthScope(host, port, realm != null ? realm : AuthScope.ANY_REALM, scheme != null ? scheme
: AuthScope.ANY_SCHEME);
client.getState().setProxyCredentials(scope, credentials);
return this;
}
/**
* Manually add cookies
*/
public AbderaClient addCookie(String domain, String name, String value) {
Cookie cookie = new Cookie(domain, name, value);
client.getState().addCookie(cookie);
return this;
}
/**
* Manually add cookies
*/
public AbderaClient addCookie(String domain, String name, String value, String path, Date expires, boolean secure) {
Cookie cookie = new Cookie(domain, name, value, path, expires, secure);
client.getState().addCookie(cookie);
return this;
}
/**
* Manually add cookies
*/
public AbderaClient addCookie(String domain, String name, String value, String path, int maxAge, boolean secure) {
Cookie cookie = new Cookie(domain, name, value, path, maxAge, secure);
client.getState().addCookie(cookie);
return this;
}
/**
* Manually add cookies
*/
public AbderaClient addCookies(Cookie cookie) {
client.getState().addCookie(cookie);
return this;
}
/**
* Manually add cookies
*/
public AbderaClient addCookies(Cookie... cookies) {
client.getState().addCookies(cookies);
return this;
}
/**
* Get all the cookies
*/
public Cookie[] getCookies() {
return client.getState().getCookies();
}
/**
* Get the cookies for a specific domain and path
*/
public Cookie[] getCookies(String domain, String path) {
Cookie[] cookies = getCookies();
List<Cookie> list = new ArrayList<Cookie>();
for (Cookie cookie : cookies) {
String test = cookie.getDomain();
if (test.startsWith("."))
test = test.substring(1);
if ((domain.endsWith(test) || test.endsWith(domain)) && (path == null || cookie.getPath().startsWith(path))) {
list.add(cookie);
}
}
return list.toArray(new Cookie[list.size()]);
}
/**
* Get the cookies for a specific domain
*/
public Cookie[] getCookies(String domain) {
return getCookies(domain, null);
}
/**
* Clear the cookies
*/
public AbderaClient clearCookies() {
client.getState().clearCookies();
return this;
}
/**
* Sets the timeout until a connection is etablished. A value of zero means the timeout is not used. The default
* value is zero.
*/
public AbderaClient setConnectionTimeout(int timeout) {
client.getHttpConnectionManager().getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, timeout);
return this;
}
/**
* Sets the default socket timeout (SO_TIMEOUT) in milliseconds which is the timeout for waiting for data. A timeout
* value of zero is interpreted as an infinite timeout.
*/
public AbderaClient setSocketTimeout(int timeout) {
client.getParams().setSoTimeout(timeout);
return this;
}
/**
* Sets the timeout in milliseconds used when retrieving an HTTP connection from the HTTP connection manager.
*/
public void setConnectionManagerTimeout(long timeout) {
client.getParams().setLongParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, timeout);
}
/**
* Return the timeout until a connection is etablished, in milliseconds. A value of zero means the timeout is not
* used. The default value is zero.
*/
public int getConnectionTimeout() {
return client.getHttpConnectionManager().getParams()
.getIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, 0);
}
/**
* Return the socket timeout for the connection in milliseconds A timeout value of zero is interpreted as an
* infinite timeout.
*/
public int getSocketTimeout() {
return client.getParams().getSoTimeout();
}
/**
* Returns the timeout in milliseconds used when retrieving an HTTP connection from the HTTP connection manager.
*/
public long getConnectionManagerTimeout() {
return client.getParams().getLongParameter(HttpClientParams.CONNECTION_MANAGER_TIMEOUT, 0);
}
/**
* Determines whether Nagle's algorithm is to be used. The Nagle's algorithm tries to conserve bandwidth by
* minimizing the number of segments that are sent. When applications wish to decrease network latency and increase
* performance, they can disable Nagle's algorithm (that is enable TCP_NODELAY). Data will be sent earlier, at the
* cost of an increase in bandwidth consumption.
*/
public void setTcpNoDelay(boolean enable) {
client.getHttpConnectionManager().getParams().setBooleanParameter(HttpConnectionParams.TCP_NODELAY, enable);
}
/**
* Tests if Nagle's algorithm is to be used.
*/
public boolean getTcpNoDelay() {
return client.getHttpConnectionManager().getParams().getBooleanParameter(HttpConnectionParams.TCP_NODELAY,
false);
}
/**
* Return the HttpConnectionManagerParams object of the underlying HttpClient. This enables you to configure options
* not explicitly exposed by the AbderaClient
*/
public HttpConnectionManagerParams getHttpConnectionManagerParams() {
return client.getHttpConnectionManager().getParams();
}
/**
* Return the HttpClientParams object of the underlying HttpClient. This enables you to configure options not
* explicitly exposed by the AbderaClient
*/
public HttpClientParams getHttpClientParams() {
return client.getParams();
}
/**
* Set the maximum number of redirects
*/
public AbderaClient setMaximumRedirects(int redirects) {
client.getParams().setIntParameter(HttpClientParams.MAX_REDIRECTS, redirects);
return this;
}
/**
* Get the maximum number of redirects
*/
public int getMaximumRedirects() {
return client.getParams().getIntParameter(HttpClientParams.MAX_REDIRECTS, DEFAULT_MAX_REDIRECTS);
}
/**
* Clear all credentials (including proxy credentials)
*/
public AbderaClient clearCredentials() {
client.getState().clearCredentials();
clearProxyCredentials();
return this;
}
/**
* Clear proxy credentials
*/
public AbderaClient clearProxyCredentials() {
client.getState().clearProxyCredentials();
return this;
}
/**
* Clear all state (cookies, credentials, etc)
*/
public AbderaClient clearState() {
client.getState().clear();
return this;
}
}
| 7,775 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/RequestOptions.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.client;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import javax.activation.MimeType;
import org.apache.abdera.i18n.rfc4646.Lang;
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.Request;
import org.apache.abdera.protocol.util.AbstractRequest;
import org.apache.abdera.protocol.util.CacheControlUtil;
import org.apache.abdera.util.EntityTag;
import org.apache.commons.httpclient.util.DateParseException;
import org.apache.commons.httpclient.util.DateUtil;
/**
* The RequestOptions class allows a variety of options affecting the execution of the request to be modified.
*/
public class RequestOptions extends AbstractRequest implements Request {
private boolean noLocalCache = false;
private boolean revalidateAuth = false;
private boolean useChunked = false;
private boolean usePostOverride = false;
private boolean requestException4xx = false;
private boolean requestException5xx = false;
private boolean useExpectContinue = true;
private boolean useConditional = true;
private boolean followRedirects = true;
private final Map<String, String[]> headers = new HashMap<String, String[]>();
public RequestOptions() {
}
/**
* Create the RequestOptions object with the specified If-Modified-Since header value
*
* @param ifModifiedSince
*/
public RequestOptions(Date ifModifiedSince) {
this();
setIfModifiedSince(ifModifiedSince);
}
/**
* Create the RequestOptions object with the specified If-None-Match header value
*
* @param IfNoneMatch
*/
public RequestOptions(String ifNoneMatch) {
this();
setIfNoneMatch(ifNoneMatch);
}
/**
* Create the RequestOptions object with the specified If-None-Match header value
*
* @param IfNoneMatch
*/
public RequestOptions(String... ifNoneMatch) {
this();
setIfNoneMatch(ifNoneMatch);
}
/**
* Create the RequestOptions object with the specified If-Modified-Since and If-None-Match header values
*
* @param ifModifiedSince
* @param IfNoneMatch
*/
public RequestOptions(Date ifModifiedSince, String ifNoneMatch) {
this();
setIfModifiedSince(ifModifiedSince);
setIfNoneMatch(ifNoneMatch);
}
/**
* Create the RequestOptions object with the specified If-Modified-Since and If-None-Match header values
*
* @param ifModifiedSince
* @param IfNoneMatch
*/
public RequestOptions(Date ifModifiedSince, String... ifNoneMatch) {
this();
setIfModifiedSince(ifModifiedSince);
setIfNoneMatch(ifNoneMatch);
}
/**
* Create the RequestOptions object
*
* @param no_cache True if the request will indicate that cached responses should not be returned
*/
public RequestOptions(boolean no_cache) {
this();
setNoCache(no_cache);
}
private Map<String, String[]> getHeaders() {
return headers;
}
private String combine(String... values) {
StringBuilder v = new StringBuilder();
for (String val : values) {
if (v.length() > 0)
v.append(", ");
v.append(val);
}
return v.toString();
}
/**
* The difference between this and getNoCache is that this only disables the local cache without affecting the
* Cache-Control header.
*/
public boolean getUseLocalCache() {
return !noLocalCache;
}
/**
* True if the local client cache should be used
*/
public RequestOptions setUseLocalCache(boolean use_cache) {
this.noLocalCache = !use_cache;
return this;
}
/**
* Set the value of the HTTP Content-Type header
*/
public RequestOptions setContentType(String value) {
return setHeader("Content-Type", value);
}
public RequestOptions setContentLocation(String iri) {
return setHeader("Content-Location", iri);
}
/**
* Set the value of the HTTP Content-Type header
*/
public RequestOptions setContentType(MimeType value) {
return setHeader("Content-Type", value.toString());
}
/**
* Set the value of the HTTP Authorization header
*/
public RequestOptions setAuthorization(String auth) {
return setHeader("Authorization", auth);
}
/**
* Set the value of a header using proper encoding of non-ascii characters
*/
public RequestOptions setEncodedHeader(String header, String charset, String value) {
return setHeader(header, Rfc2047Helper.encode(value, charset));
}
/**
* Set the values of a header using proper encoding of non-ascii characters
*/
public RequestOptions setEncodedHeader(String header, String charset, String... values) {
if (values != null && values.length > 0) {
for (int n = 0; n < values.length; n++) {
values[n] = Rfc2047Helper.encode(values[n], charset);
}
getHeaders().put(header, new String[] {combine(values)});
} else {
removeHeaders(header);
}
return this;
}
/**
* Set the value of the specified HTTP header
*/
public RequestOptions setHeader(String header, String value) {
return value != null ? setHeader(header, new String[] {value}) : removeHeaders(header);
}
/**
* Set the value of the specified HTTP header
*/
public RequestOptions setHeader(String header, String... values) {
if (values != null && values.length > 0) {
getHeaders().put(header, new String[] {combine(values)});
} else {
removeHeaders(header);
}
return this;
}
/**
* Set the date value of the specified HTTP header
*/
public RequestOptions setDateHeader(String header, Date value) {
return value != null ? setHeader(header, DateUtil.formatDate(value)) : removeHeaders(header);
}
/**
* Similar to setEncodedHeader, but allows for multiple instances of the specified header
*/
public RequestOptions addEncodedHeader(String header, String charset, String value) {
return addHeader(header, Rfc2047Helper.encode(value, charset));
}
/**
* Similar to setEncodedHeader, but allows for multiple instances of the specified header
*/
public RequestOptions addEncodedHeader(String header, String charset, String... values) {
if (values == null || values.length == 0)
return this;
for (int n = 0; n < values.length; n++) {
values[n] = Rfc2047Helper.encode(values[n], charset);
}
List<String> list = Arrays.asList(getHeaders().get(header));
String value = combine(values);
if (list != null) {
if (!list.contains(value))
list.add(value);
} else {
setHeader(header, new String[] {value});
}
return this;
}
/**
* Similar to setHeader but allows for multiple instances of the specified header
*/
public RequestOptions addHeader(String header, String value) {
if (value != null)
addHeader(header, new String[] {value});
return this;
}
/**
* Similar to setHeader but allows for multiple instances of the specified header
*/
public RequestOptions addHeader(String header, String... values) {
if (values == null || values.length == 0)
return this;
String[] headers = getHeaders().get(header);
List<String> list = headers != null ? Arrays.asList(headers) : new ArrayList<String>();
String value = combine(values);
if (list != null) {
if (!list.contains(value))
list.add(value);
} else {
setHeader(header, new String[] {value});
}
return this;
}
/**
* Similar to setDateHeader but allows for multiple instances of the specified header
*/
public RequestOptions addDateHeader(String header, Date value) {
if (value == null)
return this;
return addHeader(header, DateUtil.formatDate(value));
}
/**
* Returns the text value of the specified header
*/
public String getHeader(String header) {
String[] list = getHeaders().get(header);
return (list != null && list.length > 0) ? list[0] : null;
}
/**
* Return a listing of text values for the specified header
*/
public String[] getHeaders(String header) {
return getHeaders().get(header);
}
/**
* Returns the date value of the specified header
*/
public Date getDateHeader(String header) {
String val = getHeader(header);
try {
return (val != null) ? DateUtil.parseDate(val) : null;
} catch (DateParseException e) {
throw new RuntimeException(e);
}
}
/**
* Returns a listing of header names
*/
public String[] getHeaderNames() {
Set<String> names = getHeaders().keySet();
return names.toArray(new String[names.size()]);
}
/**
* Sets the value of the HTTP If-Match header
*/
public RequestOptions setIfMatch(String entity_tag) {
return setIfMatch(new EntityTag(entity_tag));
}
/**
* Sets the value of the HTTP If-Match header
*/
public RequestOptions setIfMatch(EntityTag entity_tag) {
return setHeader("If-Match", entity_tag.toString());
}
/**
* Sets the value of the HTTP If-Match header
*/
public RequestOptions setIfMatch(EntityTag... entity_tags) {
return setHeader("If-Match", EntityTag.toString(entity_tags));
}
/**
* Sets the value of the HTTP If-Match header
*/
public RequestOptions setIfMatch(String... entity_tags) {
return setHeader("If-Match", EntityTag.toString(entity_tags));
}
/**
* Sets the value of the HTTP If-None-Match header
*/
public RequestOptions setIfNoneMatch(String entity_tag) {
return setIfNoneMatch(new EntityTag(entity_tag));
}
/**
* Sets the value of the HTTP If-None-Match header
*/
public RequestOptions setIfNoneMatch(EntityTag entity_tag) {
return setHeader("If-None-Match", entity_tag.toString());
}
/**
* Sets the value of the HTTP If-None-Match header
*/
public RequestOptions setIfNoneMatch(EntityTag... entity_tags) {
return setHeader("If-None-Match", EntityTag.toString(entity_tags));
}
/**
* Sets the value of the HTTP If-None-Match header
*/
public RequestOptions setIfNoneMatch(String... entity_tags) {
return setHeader("If-None-Match", EntityTag.toString(entity_tags));
}
/**
* Sets the value of the HTTP If-Modified-Since header
*/
public RequestOptions setIfModifiedSince(Date date) {
return setDateHeader("If-Modified-Since", date);
}
/**
* Sets the value of the HTTP If-Unmodified-Since header
*/
public RequestOptions setIfUnmodifiedSince(Date date) {
return setDateHeader("If-Unmodified-Since", date);
}
/**
* Sets the value of the HTTP Accept header
*/
public RequestOptions setAccept(String accept) {
return setAccept(new String[] {accept});
}
/**
* Sets the value of the HTTP Accept header
*/
public RequestOptions setAccept(String... accept) {
return setHeader("Accept", combine(accept));
}
public RequestOptions setAcceptLanguage(Locale locale) {
return setAcceptLanguage(Lang.fromLocale(locale));
}
public RequestOptions setAcceptLanguage(Locale... locales) {
String[] langs = new String[locales.length];
for (int n = 0; n < locales.length; n++)
langs[n] = Lang.fromLocale(locales[n]);
setAcceptLanguage(langs);
return this;
}
/**
* Sets the value of the HTTP Accept-Language header
*/
public RequestOptions setAcceptLanguage(String accept) {
return setAcceptLanguage(new String[] {accept});
}
/**
* Sets the value of the HTTP Accept-Language header
*/
public RequestOptions setAcceptLanguage(String... accept) {
return setHeader("Accept-Language", combine(accept));
}
/**
* Sets the value of the HTTP Accept-Charset header
*/
public RequestOptions setAcceptCharset(String accept) {
return setAcceptCharset(new String[] {accept});
}
/**
* Sets the value of the HTTP Accept-Charset header
*/
public RequestOptions setAcceptCharset(String... accept) {
return setHeader("Accept-Charset", combine(accept));
}
/**
* Sets the value of the HTTP Accept-Encoding header
*/
public RequestOptions setAcceptEncoding(String accept) {
return setAcceptEncoding(new String[] {accept});
}
/**
* Sets the value of the HTTP Accept-Encoding header
*/
public RequestOptions setAcceptEncoding(String... accept) {
return setHeader("Accept-Encoding", combine(accept));
}
/**
* Sets the value of the Atom Publishing Protocol Slug header
*/
public RequestOptions setSlug(String slug) {
if (slug.indexOf((char)10) > -1 || slug.indexOf((char)13) > -1)
throw new IllegalArgumentException(Localizer.get("SLUG.BAD.CHARACTERS"));
return setHeader("Slug", UrlEncoding.encode(slug, Profile.ASCIISANSCRLF.filter()));
}
/**
* Sets the value of the HTTP Cache-Control header
*/
public RequestOptions setCacheControl(String cc) {
CacheControlUtil.parseCacheControl(cc, this);
return this;
}
/**
* Remove the specified HTTP header
*/
public RequestOptions removeHeaders(String name) {
getHeaders().remove(name);
return this;
}
/**
* Return the value of the Cache-Control header
*/
public String getCacheControl() {
return CacheControlUtil.buildCacheControl(this);
}
/**
* Configure the AbderaClient Side cache to revalidate when using Authorization
*/
public boolean getRevalidateWithAuth() {
return revalidateAuth;
}
/**
* Configure the AbderaClient Side cache to revalidate when using Authorization
*/
public RequestOptions setRevalidateWithAuth(boolean revalidateAuth) {
this.revalidateAuth = revalidateAuth;
return this;
}
/**
* Should the request use chunked encoding?
*/
public boolean isUseChunked() {
return useChunked;
}
/**
* Set whether the request should use chunked encoding.
*/
public RequestOptions setUseChunked(boolean useChunked) {
this.useChunked = useChunked;
return this;
}
/**
* Set whether the request should use the X-HTTP-Method-Override option
*/
public RequestOptions setUsePostOverride(boolean useOverride) {
this.usePostOverride = useOverride;
return this;
}
/**
* Return whether the request should use the X-HTTP-Method-Override option
*/
public boolean isUsePostOverride() {
return this.usePostOverride;
}
/**
* Set whether or not to throw a RequestExeption on 4xx responses
*/
public RequestOptions set4xxRequestException(boolean v) {
this.requestException4xx = v;
return this;
}
/**
* Return true if a RequestException should be thrown on 4xx responses
*/
public boolean is4xxRequestException() {
return this.requestException4xx;
}
/**
* Set whether or not to throw a RequestExeption on 5xx responses
*/
public RequestOptions set5xxRequestException(boolean v) {
this.requestException5xx = v;
return this;
}
/**
* Return true if a RequestException should be thrown on 5xx responses
*/
public boolean is5xxRequestException() {
return this.requestException5xx;
}
/**
* Set whether or not to use the HTTP Expect-Continue mechanism (enabled by default)
*/
public RequestOptions setUseExpectContinue(boolean useExpect) {
this.useExpectContinue = useExpect;
return this;
}
/**
* Return true if Expect-Continue should be used
*/
public boolean isUseExpectContinue() {
return this.useExpectContinue;
}
/**
* True if HTTP Conditional Requests should be used automatically. This only has an effect when putting a Document
* that has an ETag or Last-Modified date present
*/
public boolean isConditionalPut() {
return this.useConditional;
}
/**
* True if HTTP Conditinal Request should be used automatically. This only has an effect when putting a Document
* that has an ETag or Last-Modified date present
*/
public RequestOptions setConditionalPut(boolean conditional) {
this.useConditional = conditional;
return this;
}
/**
* True if the client should follow redirects automatically
*/
public boolean isFollowRedirects() {
return followRedirects;
}
/**
* True if the client should follow redirects automatically
*/
public RequestOptions setFollowRedirects(boolean followredirects) {
this.followRedirects = followredirects;
return this;
}
}
| 7,776 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/ClientResponse.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.client;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.Date;
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.Response;
public interface ClientResponse extends Response {
/**
* Return the request method
*/
String getMethod();
/**
* Return the request URI. The request was redirected, this will return the new URI
*/
String getUri();
/**
* Release the resources associated with this response
*/
void release();
/**
* Returns the inputstream used to read data from this response
*/
InputStream getInputStream() throws IOException;
/**
* Returns a reader used to read data from this response. Will use the character set declared in the Content-Type to
* create the reader
*/
Reader getReader() throws IOException;
/**
* Returns a reader used to read data from this response. Will use the character set specified to create the reader
*/
Reader getReader(String charset) throws IOException;
void setInputStream(InputStream in);
/**
* If the response contains an XML document, parse the document
*/
<T extends Element> Document<T> getDocument() throws ParseException;
/**
* If the response contains an XML document, parse the document using the specified ParserOptions
*/
<T extends Element> Document<T> getDocument(ParserOptions options) throws ParseException;
/**
* If the response contains an XML document, parse the document using the specified Parser
*/
<T extends Element> Document<T> getDocument(Parser parser) throws ParseException;
/**
* If the response contains an XML document, parse the document using the specified Parser and ParserOptions
*/
<T extends Element> Document<T> getDocument(Parser parser, ParserOptions options) throws ParseException;
/**
* Return the server-specified date returned in the response
*/
Date getServerDate();
/**
* Return the character set encoding specified in the ContentType header, if any
*/
String getCharacterEncoding();
}
| 7,777 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/cache/LRUCacheFactory.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.client.cache;
import org.apache.abdera.Abdera;
/**
* @deprecated No longer used
*/
public class LRUCacheFactory implements CacheFactory {
public LRUCacheFactory(Abdera abdera) {
}
public LRUCacheFactory() {
}
public Cache getCache(Abdera abdera) {
return new LRUCache(abdera);
}
}
| 7,778 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/cache/Cache.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.client.cache;
import org.apache.abdera.protocol.client.ClientResponse;
import org.apache.abdera.protocol.client.RequestOptions;
public interface Cache extends Iterable<Object> {
public static enum Disposition {
STALE, FRESH, TRANSPARENT
}
/**
* Get the disposition of a specific item
*/
Disposition disposition(Object key, RequestOptions options);
/**
* Get a specific item from the cache
*/
CachedResponse get(Object key);
/**
* Clear all items from the cache
*/
Cache clear();
/**
* Remove a specific item from the cache
*/
Cache remove(Object key);
/**
* Update the cached item
*/
ClientResponse update(Object key, RequestOptions options, ClientResponse response, ClientResponse cached_response);
}
| 7,779 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/cache/LRUCache.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.client.cache;
import org.apache.abdera.Abdera;
public class LRUCache extends InMemoryCache implements Cache {
private final static int DEFAULT_SIZE = 10;
public LRUCache(Abdera abdera) {
this(abdera, DEFAULT_SIZE);
}
public LRUCache(Abdera abdera, final int size) {
super(abdera, new LRUMap<Object, CachedResponse>(size, 0.75f));
}
}
| 7,780 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/cache/AbstractCache.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.client.cache;
import java.io.IOException;
import org.apache.abdera.Abdera;
import org.apache.abdera.protocol.client.ClientResponse;
import org.apache.abdera.protocol.client.RequestOptions;
import org.apache.abdera.protocol.util.CacheControlUtil;
public abstract class AbstractCache implements Cache {
protected final Abdera abdera;
protected AbstractCache(Abdera abdera) {
this.abdera = abdera;
}
public Disposition disposition(Object key, RequestOptions options) {
CachedResponse response = get(key);
if (response != null && options != null) {
if (options.isNoCache())
return Disposition.TRANSPARENT;
else if (response.isNoCache())
return Disposition.STALE;
else if (options != null && options.isOnlyIfCached())
return Disposition.FRESH;
else if (response.isMustRevalidate())
return Disposition.STALE;
else if (response.getCachedTime() != -1) {
if (response.isFresh()) {
long maxAge = options.getMaxAge();
long currentAge = response.getCurrentAge();
long minFresh = options.getMinFresh();
if (maxAge != -1)
return (maxAge > currentAge) ? Disposition.FRESH : Disposition.STALE;
if (minFresh != -1)
return response.getFreshnessLifetime() < currentAge + minFresh ? Disposition.TRANSPARENT
: Disposition.FRESH;
return Disposition.FRESH;
} else {
long maxStale = options.getMaxStale();
if (maxStale != -1)
return maxStale < response.getHowStale() ? Disposition.STALE : Disposition.FRESH;
return Disposition.STALE;
}
}
}
return Disposition.TRANSPARENT;
}
protected abstract void add(Object key, CachedResponse response);
protected abstract CachedResponse createCachedResponse(ClientResponse response, Object key) throws IOException;
private boolean shouldUpdateCache(ClientResponse response, boolean allowedByDefault) {
if (allowedByDefault) {
return !response.isNoCache() && !response.isNoStore() && response.getMaxAge() != 0;
} else {
return response.getExpires() != null || response.getMaxAge() > 0
|| response.isMustRevalidate()
|| response.isPublic()
|| response.isPrivate();
}
}
public ClientResponse update(Object key,
RequestOptions options,
ClientResponse response,
ClientResponse cached_response) {
int status = response.getStatus();
String uri = response.getUri();
String method = response.getMethod();
// if the method changes state on the server, don't cache and
// clear what we already have
if (!CacheControlUtil.isIdempotent(method)) {
remove(uri);
return response;
}
// otherwise, base the decision on the response status code
switch (status) {
case 200:
case 203:
case 300:
case 301:
case 410:
// rfc2616 says these are cacheable unless otherwise noted
if (shouldUpdateCache(response, true))
return update(key, options, response);
else
remove(uri);
break;
case 304:
case 412:
// if not revalidated, fall through
if (cached_response != null)
return cached_response;
default:
// rfc2616 says are *not* cacheable unless otherwise noted
if (shouldUpdateCache(response, false))
return update(key, options, response);
else
remove(uri);
break;
}
return response;
}
private ClientResponse update(Object key, RequestOptions options, ClientResponse response) {
try {
CachedResponse cachedResponse = createCachedResponse(response, key);
add(key, cachedResponse);
return cachedResponse;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
| 7,781 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/cache/InMemoryCachedResponse.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.client.cache;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import org.apache.abdera.Abdera;
import org.apache.abdera.protocol.client.ClientResponse;
import org.apache.abdera.protocol.client.util.MethodHelper;
import org.apache.abdera.protocol.util.CacheControlUtil;
public class InMemoryCachedResponse extends CachedResponseBase implements CachedResponse {
private final String method;
private final int status;
private final String status_text;
private final String uri;
private final Map<String, Object[]> headers;
private final byte[] buf;
public InMemoryCachedResponse(Abdera abdera, Cache cache, Object key, ClientResponse response) throws IOException {
super(abdera, key, cache);
this.method = response.getMethod();
this.status = response.getStatus();
this.status_text = response.getStatusText();
this.uri = response.getUri();
this.headers = MethodHelper.getCacheableHeaders(response);
CacheControlUtil.parseCacheControl(this.getHeader("Cache-Control"), this);
buf = cacheStream(response.getInputStream());
response.setInputStream(getInputStream());
}
/**
* This is terribly inefficient, but it is an in-memory cache that is being used by parsers that incrementally
* consume InputStreams at different rates. There's really no other way to do it.
*/
private byte[] cacheStream(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
byte[] buf = new byte[1024];
int m = -1;
while ((m = in.read(buf)) != -1) {
out.write(buf, 0, m);
}
return out.toByteArray();
}
public Map<String, Object[]> getHeaders() {
return headers;
}
public String getMethod() {
return method;
}
public String getHeader(String header) {
Object[] values = getHeaders().get(header);
return (values != null && values.length > 0) ? (String)values[0] : null;
}
public String[] getHeaderNames() {
return getHeaders().keySet().toArray(new String[getHeaders().size()]);
}
public Object[] getHeaders(String header) {
return getHeaders().get(header);
}
public int getStatus() {
return status;
}
public String getStatusText() {
return status_text;
}
public String getUri() {
return uri;
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(this.buf);
}
@Override
public void setInputStream(InputStream in) {
throw new UnsupportedOperationException();
}
}
| 7,782 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/cache/CachedResponse.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.client.cache;
import org.apache.abdera.protocol.client.ClientResponse;
public interface CachedResponse extends ClientResponse {
Object getKey();
Cache getCache();
long getCachedTime();
long getInitialAge();
long getResidentAge();
long getCurrentAge();
long getFreshnessLifetime();
long getHowStale();
boolean isFresh();
}
| 7,783 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/cache/InMemoryCache.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.client.cache;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import org.apache.abdera.Abdera;
import org.apache.abdera.protocol.client.ClientResponse;
public abstract class InMemoryCache extends AbstractCache {
protected transient final Map<Object, CachedResponse> cache;
protected InMemoryCache(Abdera abdera, Map<Object, CachedResponse> map) {
super(abdera);
this.cache = map;
}
@Override
protected CachedResponse createCachedResponse(ClientResponse response, Object key) throws IOException {
return new InMemoryCachedResponse(abdera, this, key, response);
}
public Cache clear() {
cache.clear();
return this;
}
public CachedResponse get(Object key) {
return cache.get(key);
}
public Cache remove(Object key) {
cache.remove(key);
return this;
}
protected void add(Object key, CachedResponse response) {
cache.put(key, response);
}
public Iterator<Object> iterator() {
return cache.keySet().iterator();
}
}
| 7,784 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/cache/LRUMap.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.client.cache;
import java.util.LinkedHashMap;
import java.util.Map;
public final class LRUMap<A, B> extends LinkedHashMap<A, B> {
private static final long serialVersionUID = -8243948270889739367L;
private final int size;
public LRUMap(int initialSize, float loadFactor) {
super(initialSize, loadFactor, true);
this.size = initialSize;
}
protected boolean removeEldestEntry(Map.Entry<A, B> eldest) {
return size() > size;
}
}
| 7,785 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/cache/CachedResponseBase.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.client.cache;
import java.util.Date;
import org.apache.abdera.Abdera;
import org.apache.abdera.protocol.client.AbstractClientResponse;
public abstract class CachedResponseBase extends AbstractClientResponse implements CachedResponse {
protected final Object key;
protected final Cache cache;
protected long initial_age;
protected CachedResponseBase(Abdera abdera, Object key, Cache cache) {
super(abdera);
this.key = key;
this.cache = cache;
}
private long calcInitialAge() {
long age_value = getAge();
long now = (new Date()).getTime();
long cachedTime = getCachedTime();
long date_value = (cachedTime != -1) ? cachedTime : 0;
long apparent_age = Math.max(0, now - date_value);
long corrected_received_age = Math.max(apparent_age, age_value);
return corrected_received_age / 1000;
}
public Object getKey() {
return key;
}
public Cache getCache() {
return cache;
}
public void release() {
if (cache != null) {
cache.remove(key);
}
}
public long getInitialAge() {
if (initial_age == -1)
initial_age = calcInitialAge();
return initial_age;
}
public long getCachedTime() {
return getServerDate().getTime();
}
public long getResidentAge() {
long now = (new Date()).getTime();
long init = getCachedTime();
return Math.max(0, (now - init)) / 1000;
}
public long getCurrentAge() {
return getInitialAge() + getResidentAge();
}
public long getFreshnessLifetime() {
long lifetime = getMaxAge();
if (lifetime == -1) {
Date expires_date = getExpires();
long expires = (expires_date != null) ? expires_date.getTime() : -1;
long cachedTime = getCachedTime();
if (expires != -1) {
lifetime = (expires > cachedTime) ? (expires - cachedTime) / 1000 : 0;
} // else, expires is not set, return -1 for now. TODO: apply heuristics
}
return lifetime;
}
public long getHowStale() {
return (!isFresh()) ? getCurrentAge() - getFreshnessLifetime() : 0;
}
public boolean isFresh() {
long lifetime = getFreshnessLifetime();
long currentage = getCurrentAge();
return (lifetime != -1) ? lifetime > currentage : true;
}
}
| 7,786 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/cache/CacheFactory.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.client.cache;
import org.apache.abdera.Abdera;
/**
* @deprecated No longer used
*/
public interface CacheFactory {
Cache getCache(Abdera abdera);
}
| 7,787 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/util/NonOpTrustManager.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.client.util;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.X509TrustManager;
public class NonOpTrustManager implements X509TrustManager {
public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
}
| 7,788 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/util/LocalizationHelper.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.client.util;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;
import org.apache.abdera.i18n.rfc4646.Lang;
import org.apache.abdera.i18n.rfc4646.Range;
import org.apache.abdera.model.Entry;
import org.apache.abdera.model.Link;
import org.apache.abdera.model.Source;
public final class LocalizationHelper {
private LocalizationHelper() {
}
public static Link[] selectAlternate(Source source) {
return selectAlternate(source, Locale.getDefault());
}
public static Link[] selectAlternate(Entry entry) {
return selectAlternate(entry, Locale.getDefault());
}
public static Link[] selectAlternate(Source source, Locale locale) {
return selectAlternate(source, new Range(Lang.fromLocale(locale), true));
}
public static Link[] selectAlternate(Entry entry, Locale locale) {
return selectAlternate(entry, new Range(Lang.fromLocale(locale), true));
}
public static Link[] selectAlternate(Entry entry, Locale... locales) {
Range[] ranges = new Range[locales.length];
for (int n = 0; n < locales.length; n++)
ranges[n] = new Range(Lang.fromLocale(locales[n]), true);
return selectAlternate(entry, ranges);
}
public static Link[] selectAlternate(Entry entry, Range range) {
return selectAlternate(entry, new Range[] {range});
}
public static Link[] selectAlternate(Entry entry, Range... ranges) {
return selectAlternate(entry.getLinks("alternate"), ranges);
}
public static Link[] selectAlternate(Entry entry, String range) {
return selectAlternate(entry, new String[] {range});
}
public static Link[] selectAlternate(Entry entry, String... ranges) {
Range[] r = new Range[ranges.length];
for (int n = 0; n < ranges.length; n++)
r[n] = new Range(ranges[n], true);
return selectAlternate(entry, r);
}
public static Link[] selectAlternate(Source source, Locale... locales) {
Range[] ranges = new Range[locales.length];
for (int n = 0; n < locales.length; n++)
ranges[n] = new Range(Lang.fromLocale(locales[n]), true);
return selectAlternate(source, ranges);
}
public static Link[] selectAlternate(Source source, Range range) {
return selectAlternate(source, new Range[] {range});
}
public static Link[] selectAlternate(Source source, Range... ranges) {
return selectAlternate(source.getLinks("alternate"), ranges);
}
public static Link[] selectAlternate(Source source, String range) {
return selectAlternate(source, new String[] {range});
}
public static Link[] selectAlternate(Source source, String... ranges) {
Range[] r = new Range[ranges.length];
for (int n = 0; n < ranges.length; n++)
r[n] = new Range(ranges[n], true);
return selectAlternate(source, r);
}
public static Link[] selectAlternate(List<Link> links, String range) {
return selectAlternate(links, new Range(range, true));
}
public static Link[] selectAlternate(List<Link> links, Range range) {
return selectAlternate(links, new Range[] {range});
}
public static Link[] selectAlternate(List<Link> links, Range... ranges) {
List<Link> matching = new ArrayList<Link>();
for (Range range : ranges) {
for (Link link : links) {
String hreflang = link.getHrefLang();
if (hreflang != null) {
Lang lang = new Lang(hreflang);
Range basic = range.toBasicRange();
Lang blang = !basic.toString().equals("*") ? new Lang(basic.toString()) : null;
if (range.matches(lang) || (blang != null && lang.isParentOf(blang)))
matching.add(link);
}
}
Collections.sort(matching, new Comparator<Link>() {
public int compare(Link o1, Link o2) {
Lang l1 = new Lang(o1.getHrefLang());
Lang l2 = new Lang(o2.getHrefLang());
return l1.compareTo(l2);
}
});
}
return matching.toArray(new Link[matching.size()]);
}
}
| 7,789 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/util/EntityProviderRequestEntity.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.client.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.abdera.Abdera;
import org.apache.abdera.protocol.EntityProvider;
import org.apache.commons.httpclient.methods.RequestEntity;
public class EntityProviderRequestEntity implements RequestEntity {
private final Abdera abdera;
private final EntityProvider provider;
private byte[] buf = null;
private boolean use_chunked = true;
private boolean auto_indent = false;
private String encoding = "UTF-8";
public EntityProviderRequestEntity(Abdera abdera, EntityProvider provider, boolean use_chunked) {
this.abdera = abdera;
this.use_chunked = use_chunked;
this.provider = provider;
}
private void write(OutputStream out) {
provider.writeTo(abdera.newStreamWriter().setOutputStream(out, encoding).setAutoIndent(auto_indent));
}
public long getContentLength() {
if (use_chunked)
return -1; // chunk the response
else {
// this is ugly, but some proxies and server configurations (e.g. gdata)
// require that requests contain the Content-Length header. The only
// way to get that is to serialize the document into a byte array, which
// we buffer into memory.
if (buf == null) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
write(out);
buf = out.toByteArray();
} catch (Exception e) {
}
}
return buf.length;
}
}
public String getContentType() {
return provider.getContentType();
}
public boolean isRepeatable() {
return provider.isRepeatable();
}
public void writeRequest(OutputStream out) throws IOException {
if (use_chunked)
write(out);
else {
// if we're not using chunked requests, the getContentLength method
// has likely already been called and we want to just go ahead and
// use the buffered output rather than reserialize
if (buf == null)
getContentLength(); // ensures that the content is buffered
out.write(buf);
out.flush();
}
}
public boolean isAutoIndent() {
return auto_indent;
}
public void setAutoIndent(boolean auto_indent) {
this.auto_indent = auto_indent;
}
public String getEncoding() {
return encoding;
}
public void setEncoding(String encoding) {
this.encoding = encoding;
}
}
| 7,790 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/util/AutoReleasingInputStream.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.client.util;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.httpclient.HttpMethod;
public final class AutoReleasingInputStream extends FilterInputStream {
private final HttpMethod method;
public AutoReleasingInputStream(HttpMethod method, InputStream in) {
super(in);
this.method = method;
}
@Override
public int read() throws IOException {
if (this.in == null)
return -1;
try {
int r = super.read();
if (r == -1) {
method.releaseConnection();
}
return r;
} catch (IOException e) {
if (method != null)
method.releaseConnection();
throw e;
}
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
if (this.in == null)
return -1;
try {
int r = super.read(b, off, len);
if (r == -1) {
method.releaseConnection();
}
return r;
} catch (IOException e) {
if (method != null)
method.releaseConnection();
throw e;
}
}
}
| 7,791 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/util/SimpleSSLProtocolSocketFactory.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.client.util;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
public class SimpleSSLProtocolSocketFactory implements SecureProtocolSocketFactory {
private SSLContext context = null;
public SimpleSSLProtocolSocketFactory(TrustManager trustManager) {
init(trustManager);
}
public SimpleSSLProtocolSocketFactory() {
this(new NonOpTrustManager());
}
private void init(TrustManager trustManager) {
try {
context = SSLContext.getInstance("SSL");
context.init(null, new TrustManager[] {trustManager}, null);
} catch (Exception e) {
}
}
public Socket createSocket(Socket socket, String host, int port, boolean close) throws IOException,
UnknownHostException {
return context.getSocketFactory().createSocket(socket, host, port, close);
}
public Socket createSocket(String host, int port, InetAddress chost, int cport) throws IOException,
UnknownHostException {
return context.getSocketFactory().createSocket(host, port, chost, cport);
}
public Socket createSocket(String host, int port, InetAddress chost, int cport, HttpConnectionParams params)
throws IOException, UnknownHostException, ConnectTimeoutException {
return context.getSocketFactory().createSocket(host, port, chost, cport);
}
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return context.getSocketFactory().createSocket(host, port);
}
}
| 7,792 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/util/ClientAuthSSLProtocolSocketFactory.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.client.util;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import org.apache.abdera.i18n.text.Localizer;
import org.apache.commons.httpclient.ConnectTimeoutException;
import org.apache.commons.httpclient.params.HttpConnectionParams;
import org.apache.commons.httpclient.protocol.SecureProtocolSocketFactory;
public class ClientAuthSSLProtocolSocketFactory implements SecureProtocolSocketFactory {
private static final String DEFAULT_PROTOCOL = "TLS";
private static final String DEFAULT_KMF_FACTORY = "ibmX509";
private final String protocol;
private final String kmfFactory;
private final TrustManager tm;
private final String keyStorePass;
private final KeyStore ks;
public ClientAuthSSLProtocolSocketFactory(KeyStore ks, String keyStorePass) {
this(ks, keyStorePass, DEFAULT_PROTOCOL, DEFAULT_KMF_FACTORY, null);
}
public ClientAuthSSLProtocolSocketFactory(KeyStore ks,
String keyStorePass,
String protocol,
String kmfFactory,
TrustManager tm) {
if (ks == null)
throw new IllegalArgumentException(Localizer.get("INVALID.KEYSTORE"));
this.ks = ks;
this.keyStorePass = keyStorePass;
this.protocol = protocol != null ? protocol : DEFAULT_PROTOCOL;
this.kmfFactory = kmfFactory != null ? kmfFactory : DEFAULT_KMF_FACTORY;
this.tm = tm;
}
public ClientAuthSSLProtocolSocketFactory(String keyStore,
String keyStoreType,
String keyStorePass,
String protocol,
String kmfFactory,
TrustManager tm) {
this(initKeyStore(keyStore, keyStoreType, keyStorePass), keyStorePass, protocol, kmfFactory, tm);
}
private static KeyStore initKeyStore(String keyStore, String keyStoreType, String keyPass) {
KeyStore ks = null;
try {
ks = KeyStore.getInstance(keyStoreType);
ks.load(new FileInputStream(keyStore), keyPass.toCharArray());
} catch (Exception e) {
}
return ks;
}
public Socket createSocket(Socket socket, String host, int port, boolean close) throws IOException,
UnknownHostException {
return createSocket(host, port, null, 0, null);
}
public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
return createSocket(host, port, null, 0, null);
}
public Socket createSocket(String host, int port, InetAddress chost, int cport) throws IOException,
UnknownHostException {
return createSocket(host, port, chost, cport, null);
}
public Socket createSocket(String host, int port, InetAddress chost, int cport, HttpConnectionParams params)
throws IOException, UnknownHostException, ConnectTimeoutException {
SSLContext context;
SSLSocketFactory factory = null;
SSLSocket socket = null;
try {
KeyManagerFactory kmf;
context = SSLContext.getInstance(protocol);
kmf = KeyManagerFactory.getInstance(kmfFactory);
TrustManager tm = (this.tm != null) ? this.tm : new NonOpTrustManager();
kmf.init(ks, keyStorePass.toCharArray());
context.init(kmf.getKeyManagers(), new TrustManager[] {tm}, null);
factory = context.getSocketFactory();
socket = (SSLSocket)factory.createSocket(host, port);
return socket;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| 7,793 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/util/MethodHelper.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.client.util;
import java.util.HashMap;
import java.util.Map;
import org.apache.abdera.protocol.client.ClientResponse;
import org.apache.abdera.protocol.client.RequestOptions;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.URI;
import org.apache.commons.httpclient.methods.DeleteMethod;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.HeadMethod;
import org.apache.commons.httpclient.methods.OptionsMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.PutMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.TraceMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class MethodHelper {
public static enum HopByHop {
Connection, KeepAlive, ProxyAuthenticate, ProxyAuthorization, TE, Trailers, TransferEncoding, Upgrade;
}
public static enum Method {
GET, POST, PUT, DELETE, OPTIONS, TRACE, HEAD, OTHER;
public static Method fromString(String method) {
try {
return Method.valueOf(method.toUpperCase());
} catch (Exception e) {
return OTHER;
}
}
}
public static Map<String, Object[]> getCacheableHeaders(ClientResponse response) {
Map<String, Object[]> map = new HashMap<String, Object[]>();
String[] headers = response.getHeaderNames();
for (String header : headers) {
if (MethodHelper.isCacheableHeader(header, response)) {
Object[] list = response.getHeaders(header);
map.put(header, list);
}
}
return map;
}
public static boolean isCacheableHeader(String header, ClientResponse response) {
return !isNoCacheOrPrivate(header, response) && !isHopByHop(header);
}
public static boolean isNoCacheOrPrivate(String header, ClientResponse response) {
String[] no_cache_headers = response.getNoCacheHeaders();
String[] private_headers = response.getPrivateHeaders();
return contains(no_cache_headers, header) || contains(private_headers, header);
}
private static boolean contains(String[] headers, String header) {
if (headers != null) {
for (String h : headers) {
if (h.equals(header))
return true;
}
}
return false;
}
/**
* We don't cache hop-by-hop headers TODO: There may actually be other hop-by-hop headers we need to filter out.
* They'll be listed in the Connection header. see Section 14.10 of RFC2616 (last paragraph)
*/
public static boolean isHopByHop(String header) {
try {
HopByHop.valueOf(header.replaceAll("-", ""));
return true;
} catch (Exception e) {
return false;
}
}
private static EntityEnclosingMethod getMethod(EntityEnclosingMethod method, RequestEntity entity) {
if (entity != null)
method.setRequestEntity(entity);
return method;
}
public static HttpMethod createMethod(String method, String uri, RequestEntity entity, RequestOptions options) {
if (method == null)
return null;
Method m = Method.fromString(method);
Method actual = null;
HttpMethod httpMethod = null;
if (options.isUsePostOverride()) {
if (m.equals(Method.PUT)) {
actual = m;
} else if (m.equals(Method.DELETE)) {
actual = m;
}
if (actual != null)
m = Method.POST;
}
switch (m) {
case GET:
httpMethod = new GetMethod(uri);
break;
case POST:
httpMethod = getMethod(new PostMethod(uri), entity);
break;
case PUT:
httpMethod = getMethod(new PutMethod(uri), entity);
break;
case DELETE:
httpMethod = new DeleteMethod(uri);
break;
case HEAD:
httpMethod = new HeadMethod(uri);
break;
case OPTIONS:
httpMethod = new OptionsMethod(uri);
break;
case TRACE:
httpMethod = new TraceMethod(uri);
break;
default:
httpMethod = getMethod(new ExtensionMethod(method, uri), entity);
}
if (actual != null) {
httpMethod.addRequestHeader("X-HTTP-Method-Override", actual.name());
}
initHeaders(options, httpMethod);
// by default use expect-continue is enabled on the client
// only disable if explicitly disabled
if (!options.isUseExpectContinue())
httpMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
// should we follow redirects, default is true
if (!(httpMethod instanceof EntityEnclosingMethod))
httpMethod.setFollowRedirects(options.isFollowRedirects());
return httpMethod;
}
private static void initHeaders(RequestOptions options, HttpMethod method) {
String[] headers = options.getHeaderNames();
for (String header : headers) {
Object[] values = options.getHeaders(header);
for (Object value : values) {
method.addRequestHeader(header, value.toString());
}
}
String cc = options.getCacheControl();
if (cc != null && cc.length() != 0)
method.setRequestHeader("Cache-Control", cc);
if (options.getAuthorization() != null)
method.setDoAuthentication(false);
}
public static final class ExtensionMethod extends EntityEnclosingMethod {
private String method = null;
public ExtensionMethod(String method, String uri) {
super(method);
try {
this.setURI(new URI(uri, false));
} catch (Exception e) {
}
this.method = method;
}
@Override
public String getName() {
return method;
}
}
public static RequestOptions createDefaultRequestOptions() {
RequestOptions options = new RequestOptions();
options.setAcceptEncoding("gzip", "deflate");
options.setAccept("application/atom+xml;type=entry",
"application/atom+xml;type=feed",
"application/atom+xml",
"application/atomsvc+xml",
"application/atomcat+xml",
"application/xml;q=0.5",
"text/xml;q=0.5",
"*/*;q=0.01");
options.setAcceptCharset("utf-8", "*;q=0.5");
return options;
}
}
| 7,794 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/util/BaseRequestEntity.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.client.util;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.abdera.model.Base;
import org.apache.abdera.util.MimeTypeHelper;
import org.apache.commons.httpclient.methods.RequestEntity;
/**
* Required for the Apache Commons HTTP AbderaClient.
*/
public class BaseRequestEntity implements RequestEntity {
private final Base base;
private byte[] buf = null;
private boolean use_chunked = true;
public BaseRequestEntity(Base base) {
this.base = base;
}
public BaseRequestEntity(Base base, boolean use_chunked) {
this(base);
this.use_chunked = use_chunked;
}
public boolean isRepeatable() {
return true;
}
public void writeRequest(OutputStream out) throws IOException {
if (use_chunked)
base.writeTo(out);
else {
// if we're not using chunked requests, the getContentLength method
// has likely already been called and we want to just go ahead and
// use the buffered output rather than reserialize
if (buf == null)
getContentLength(); // ensures that the content is buffered
out.write(buf);
out.flush();
}
}
public long getContentLength() {
if (use_chunked)
return -1; // chunk the response
else {
// this is ugly, but some proxies and server configurations (e.g. gdata)
// require that requests contain the Content-Length header. The only
// way to get that is to serialize the document into a byte array, which
// we buffer into memory.
if (buf == null) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
base.writeTo(out);
buf = out.toByteArray();
} catch (Exception e) {
}
}
return buf.length;
}
}
public String getContentType() {
return MimeTypeHelper.getMimeType(base);
}
}
| 7,795 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/util/MultipartRelatedRequestEntity.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.client.util;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.abdera.model.Entry;
import org.apache.abdera.util.MimeTypeHelper;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.httpclient.methods.RequestEntity;
public class MultipartRelatedRequestEntity implements RequestEntity {
static final int BUFF_SIZE = 1024;
static final byte[] buffer = new byte[BUFF_SIZE];
private final Entry entry;
private final InputStream input;
private final String contentType;
private String boundary;
public MultipartRelatedRequestEntity(Entry entry, InputStream input) {
this(entry, input, null);
}
public MultipartRelatedRequestEntity(Entry entry, InputStream input, String contentType) {
this(entry, input, contentType, null);
}
public MultipartRelatedRequestEntity(Entry entry, InputStream input, String contentType, String boundary) {
this.input = input;
this.entry = entry;
this.contentType = contentType != null ? contentType : entry.getContentMimeType().toString();
this.boundary = boundary != null ? boundary : String.valueOf(System.currentTimeMillis());
}
public void writeRequest(OutputStream arg0) throws IOException {
DataOutputStream out = new DataOutputStream(arg0);
out.writeBytes("--" + boundary + "\r\n");
writeEntry(out);
writeInput(out);
}
private void writeEntry(DataOutputStream out) throws IOException {
out.writeBytes("content-type: " + MimeTypeHelper.getMimeType(entry) + "\r\n\r\n");
entry.writeTo(out);
out.writeBytes("--" + boundary + "\r\n");
}
private void writeInput(DataOutputStream out) throws IOException {
if (contentType == null) {
throw new NullPointerException("media content type can't be null");
}
out.writeBytes("content-type: " + contentType + "\r\n");
String contentId = entry.getContentSrc().toString();
if (!contentId.matches("cid:.+")) {
throw new IllegalArgumentException("entry content source is not a correct content-ID");
}
out.writeBytes("content-id: <" + contentId.substring(4) + ">\r\n\r\n");
ByteArrayOutputStream output = new ByteArrayOutputStream();
while (input.read(buffer) != -1) {
output.write(buffer);
}
Base64 base64 = new Base64();
out.write(base64.encode(output.toByteArray()));
out.writeBytes("\r\n" + "--" + boundary + "--");
}
public long getContentLength() {
return -1;
}
public String getContentType() {
return "Multipart/Related; boundary=\"" + boundary + "\";type=\"" + MimeTypeHelper.getMimeType(entry) + "\"";
}
public boolean isRepeatable() {
return true;
}
}
| 7,796 |
0 | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client | Create_ds/abdera/client/src/main/java/org/apache/abdera/protocol/client/util/DataSourceRequestEntity.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.client.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import org.apache.commons.httpclient.methods.RequestEntity;
public class DataSourceRequestEntity implements RequestEntity {
private final DataSource dataSource;
public DataSourceRequestEntity(DataHandler dataHandler) {
this(dataHandler.getDataSource());
}
public DataSourceRequestEntity(DataSource dataSource) {
this.dataSource = dataSource;
}
public long getContentLength() {
return -1;
}
public String getContentType() {
return dataSource.getContentType();
}
public boolean isRepeatable() {
return true;
}
public void writeRequest(OutputStream out) throws IOException {
InputStream in = dataSource.getInputStream();
byte[] buf = new byte[1024];
int n = -1;
while ((n = in.read(buf, 0, 1024)) != -1) {
out.write(buf, 0, n);
out.flush();
}
}
}
| 7,797 |
0 | Create_ds/abdera/spring/src/test/java/org/apache/abdera | Create_ds/abdera/spring/src/test/java/org/apache/abdera/spring/DummyFilter.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.spring;
import org.apache.abdera.protocol.server.Filter;
import org.apache.abdera.protocol.server.FilterChain;
import org.apache.abdera.protocol.server.RequestContext;
import org.apache.abdera.protocol.server.ResponseContext;
public class DummyFilter implements Filter {
public ResponseContext filter(RequestContext request, FilterChain chain) {
return chain.next(request);
}
}
| 7,798 |
0 | Create_ds/abdera/spring/src/test/java/org/apache/abdera | Create_ds/abdera/spring/src/test/java/org/apache/abdera/spring/ProviderDefinitionParserTest.java | /**
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. 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.
*/
package org.apache.abdera.spring;
import java.util.Collection;
import org.apache.abdera.protocol.Resolver;
import org.apache.abdera.protocol.server.CollectionInfo;
import org.apache.abdera.protocol.server.Provider;
import org.apache.abdera.protocol.server.Target;
import org.apache.abdera.protocol.server.WorkspaceInfo;
import org.apache.abdera.protocol.server.WorkspaceManager;
import org.apache.abdera.protocol.server.impl.DefaultProvider;
import org.apache.abdera.protocol.server.impl.RegexTargetResolver;
import org.junit.Test;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
public class ProviderDefinitionParserTest extends AbstractDependencyInjectionSpringContextTests {
@Test
public void testParser() throws Exception {
DefaultProvider p = (DefaultProvider)applicationContext.getBean(Provider.class.getName());
Resolver<Target> tresolver = p.getTargetResolver();
assertTrue(tresolver instanceof RegexTargetResolver);
WorkspaceManager wm = p.getWorkspaceManager();
Collection<WorkspaceInfo> workspaces = wm.getWorkspaces(null);
assertEquals(1, workspaces.size());
WorkspaceInfo w = workspaces.iterator().next();
assertNotNull(w);
assertEquals("Foo Workspace", w.getTitle(null));
Collection<CollectionInfo> collections = w.getCollections(null);
assertEquals(2, collections.size());
assertEquals(2, p.getFilters(null).length); // Parameter isn't used
}
@Override
protected String getConfigPath() {
return "/org/apache/abdera/spring/beans.xml";
}
}
| 7,799 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.