diff --git a/.gitignore b/.gitignore index 0861ab5..20149da 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,5 @@ target */.classpath */.project */.settings +*/build/ +.gradle \ No newline at end of file diff --git a/.idea/.gitignore b/.idea/.gitignore new file mode 100644 index 0000000..cc5c502 --- /dev/null +++ b/.idea/.gitignore @@ -0,0 +1,8 @@ +# デフォルトの無視対象ファイル +/shelf/ +/workspace.xml +# エディターベースの HTTP クライアントリクエスト +/httpRequests/ +# Datasource local storage ignored files +/dataSources/ +/dataSources.local.xml diff --git a/.idea/compiler.xml b/.idea/compiler.xml new file mode 100644 index 0000000..0e763e7 --- /dev/null +++ b/.idea/compiler.xml @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/encodings.xml b/.idea/encodings.xml new file mode 100644 index 0000000..e20b48a --- /dev/null +++ b/.idea/encodings.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/gradle.xml b/.idea/gradle.xml new file mode 100644 index 0000000..616e105 --- /dev/null +++ b/.idea/gradle.xml @@ -0,0 +1,22 @@ + + + + + + + \ No newline at end of file diff --git a/.idea/jarRepositories.xml b/.idea/jarRepositories.xml new file mode 100644 index 0000000..73a6a03 --- /dev/null +++ b/.idea/jarRepositories.xml @@ -0,0 +1,35 @@ + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/kotlinc.xml b/.idea/kotlinc.xml new file mode 100644 index 0000000..c224ad5 --- /dev/null +++ b/.idea/kotlinc.xml @@ -0,0 +1,6 @@ + + + + + \ No newline at end of file diff --git a/.idea/misc.xml b/.idea/misc.xml new file mode 100644 index 0000000..d5e2185 --- /dev/null +++ b/.idea/misc.xml @@ -0,0 +1,20 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/.idea/vcs.xml b/.idea/vcs.xml new file mode 100644 index 0000000..35eb1dd --- /dev/null +++ b/.idea/vcs.xml @@ -0,0 +1,6 @@ + + + + + + \ No newline at end of file diff --git a/actions/build.gradle.kts b/actions/build.gradle.kts new file mode 100644 index 0000000..eecf180 --- /dev/null +++ b/actions/build.gradle.kts @@ -0,0 +1,24 @@ +/* + * This file was generated by the Gradle 'init' task. + */ + +plugins { + kotlin("jvm") +} + +dependencies { + api(project(":core")) + testImplementation(libs.junit.junit) + implementation(kotlin("stdlib-jdk8")) +} + +description = "Activity Streams 2.0 - Actions" +repositories { + mavenCentral() +} +kotlin { + jvmToolchain(11) +} +tasks.test { + useJUnit() +} \ No newline at end of file diff --git a/actions/pom.xml b/actions/pom.xml deleted file mode 100644 index 0d074df..0000000 --- a/actions/pom.xml +++ /dev/null @@ -1,142 +0,0 @@ - - 4.0.0 - - com.ibm.common - activitystreams - 0.0.1-SNAPSHOT - - activitystreams-actions - Activity Streams 2.0 - Actions - - - - Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - UTF-8 - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9.1 - - UTF-8 - UTF-8 - UTF-8 - -XDignore.symbol.file - public - - http://www.joda.org/joda-time/apidocs - http://docs.guava-libraries.googlecode.com/git-history/v16.0.1/javadoc/ - - - - - - maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - - - - - maven-jar-plugin - 2.3.1 - - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - - - - - org.apache.felix - maven-bundle-plugin - 2.3.7 - true - - - bundle-manifest - process-classes - - manifest - - - - - - com.ibm.common.activitystreams.actions.* - - com.ibm.common.activitystreams.*, - com.google.gson.*, - com.google.common.*, - org.joda.time.* - - - - - - - org.apache.maven.plugins - maven-assembly-plugin - 2.2.2 - - - assembly.xml - - - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - org.apache.felix - maven-bundle-plugin - [2.3.7,) - - manifest - - - - - - - - - - - - - - - - - com.ibm.common - activitystreams-core - 0.0.1-SNAPSHOT - - - junit - junit - - - \ No newline at end of file diff --git a/actions/src/main/java/com/ibm/common/activitystreams/actions/ActionHandler.java b/actions/src/main/java/com/ibm/common/activitystreams/actions/ActionHandler.java deleted file mode 100755 index 843581d..0000000 --- a/actions/src/main/java/com/ibm/common/activitystreams/actions/ActionHandler.java +++ /dev/null @@ -1,369 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.actions; - -import java.io.Serializable; - -import com.google.common.base.Predicate; -import com.google.common.base.Supplier; -import com.ibm.common.activitystreams.ASObject; -import com.ibm.common.activitystreams.LinkValue; - -/** - */ -public abstract class ActionHandler - extends ASObject - implements Serializable { - - /** - */ - @SuppressWarnings("unchecked") - public static abstract class Builder> - extends ASObject.AbstractBuilder { - - private final Authentication.Builder auth = - Authentication.make(); - - public Builder() { - writeUsing(ActionMakers.io); - } - - /** - * Method confirm. - * @return B - */ - public B confirm() { - return confirm(true); - } - - /** - * Method confirm. - * @param on boolean - * @return B - */ - public B confirm(boolean on) { - set("confirm", on); - return (B)this; - } - - /** - * Method context. - * @param obj ASObject - * @return B - */ - public B context(ASObject obj) { - set("context", obj); - return (B)this; - } - - /** - * Method context. - * @param obj Supplier - * @return B - */ - public B context(Supplier obj) { - return context(obj.get()); - } - - /** - * Method requires. - * @param iri String - * @return B - */ - public B requires(String iri, String... iris) { - requires(LinkValue.SimpleLinkValue.make(iri)); - if (iris != null) - for (String i : iris) - requires(i); - return (B)this; - } - - /** - * Method requires. - * @param lv LinkValue - * @return B - */ - public B requires(LinkValue lv, LinkValue... lvs) { - link("requires", lv); - if (lvs != null) - for (LinkValue i : lvs) - requires(i); - return (B)this; - } - - /** - * Method requires. - * @param lv Supplier - * @return B - */ - public B requires(Supplier lv) { - return requires(lv.get()); - } - - /** - * Method prefers. - * @param iri String - * @return B - */ - public B prefers(String iri, String... iris) { - prefers(LinkValue.SimpleLinkValue.make(iri)); - if (iris != null) - for (String i : iris) - prefers(i); - return (B) this; - } - - /** - * Method prefers. - * @param lv LinkValue - * @return B - */ - public B prefers(LinkValue lv, LinkValue... lvs) { - link("prefers", lv); - if (lvs != null) - for (LinkValue l : lvs) - prefers(l); - return (B)this; - } - - /** - * Method prefers. - * @param lv Supplier - * @return B - */ - public B prefers(Supplier lv) { - return prefers(lv.get()); - } - - /** - * Method expects. - * @param iri String - * @return B - */ - public B expects(String iri, String... iris) { - expects(LinkValue.SimpleLinkValue.make(iri)); - if (iris != null) - for (String i : iris) - expects(i); - return (B)this; - } - - /** - * Method expects. - * @param tv LinkValue - * @return B - */ - public B expects(LinkValue tv, LinkValue... lvs) { - link("expects", tv); - if (lvs != null) - for (LinkValue lv : lvs) - expects(lv); - return (B)this; - } - - /** - * Method expects. - * @param tv Supplier - * @return B - */ - public B expects(Supplier tv) { - return expects(tv.get()); - } - - /** - * Method returns. - * @param iri String - * @return B - */ - public B returns(String iri, String... iris) { - returns(LinkValue.SimpleLinkValue.make(iri)); - if (iris != null) - for (String i : iris) - returns(i); - return (B)this; - } - - /** - * Method returns. - * @param tv LinkValue - * @return B - */ - public B returns(LinkValue tv, LinkValue... lvs) { - link("returns", tv); - if (lvs != null) - for (LinkValue lv : lvs) - returns(lv); - return (B)this; - } - - /** - * Method returns. - * @param tv Supplier - * @return B - */ - public B returns(Supplier tv) { - return returns(tv.get()); - } - - /** - * Method auth. - * @param key String - * @param obj ASObject - * @return B - */ - public B auth(String key, ASObject obj) { - auth.set(key, obj); - return (B)this; - } - - /** - * Method auth. - * @param key String - * @param obj Supplier - * @return B - */ - public B auth(String key, Supplier obj) { - return auth(key, obj.get()); - } - - /** - * Method get. - * @return A - * @see com.google.common.base.Supplier#get() - */ - public A get() { - if (auth.notEmpty()) - set("auth", auth.get()); - return actualGet(); - } - - /** - * Method actualGet. - * @return A - */ - protected abstract A actualGet(); - } - - /** - * Constructor for ActionHandler. - * @param builder Builder - */ - protected ActionHandler(Builder builder) { - super(builder); - } - - /** - * Method confirm. - * @return boolean - */ - public boolean confirm() { - return this.getBoolean("confirm"); - } - - /** - * Method context. - * @return A - */ - public A context() { - return this.get("context"); - } - - /** - * Method expects. - * @return Iterable - */ - public Iterable expects() { - return this.links("expects"); - } - - public Iterable expects(Predicate filter) { - return this.links("expects", filter); - } - - /** - * Method requires. - * @return Iterable - */ - public Iterable requires() { - return this.links("requires"); - } - - public Iterable requires(Predicate filter) { - return this.links("requires", filter); - } - - /** - * Method prefers. - * @return Iterable - */ - public Iterable prefers() { - return this.links("prefers"); - } - - public Iterable prefers(Predicate filter) { - return this.links("prefers", filter); - } - - /** - * Method returns. - * @return Iterable - */ - public Iterable returns() { - return this.links("returns"); - } - - public Iterable returns(Predicate filter) { - return this.links("returns", filter); - } - - /** - * Method auth. - * @return Authentication - */ - public Authentication auth() { - return this.get("auth"); - } - - /** - * Method hasAuth. - * @param key String - * @return boolean - */ - public boolean hasAuth(String key) { - Authentication auth = auth(); - return auth != null ? - auth.has(key) : false; - } - - /** - * Method auth. - * @param key String - * @return A - */ - @SuppressWarnings("unchecked") - public A auth(String key) { - Authentication auth = auth(); - return auth != null ? - (A)auth.get(key) : null; - } - -} diff --git a/actions/src/main/java/com/ibm/common/activitystreams/actions/ActionMakers.java b/actions/src/main/java/com/ibm/common/activitystreams/actions/ActionMakers.java deleted file mode 100755 index 71bd7fb..0000000 --- a/actions/src/main/java/com/ibm/common/activitystreams/actions/ActionMakers.java +++ /dev/null @@ -1,233 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.actions; - -import static com.ibm.common.activitystreams.Makers.object; - -import com.ibm.common.activitystreams.ASObject; -import com.ibm.common.activitystreams.IO; -import com.ibm.common.activitystreams.actions.ParameterValue.SimpleParameterValue; - -/** - */ -public final class ActionMakers { - - public static final IO io = - IO.makeDefault(ActionsModule.instance); - public static final IO ioPretty = - IO.makeDefaultPrettyPrint(ActionsModule.instance); - - public static final String TARGET_NONE = "NONE"; - public static final String TARGET_DEFAULT = "DEFAULT"; - public static final String TARGET_NEW = "NEW"; - public static final String TARGET_CURRENT = "CURRENT"; - public static final String TARGET_TAB = "TAB"; - public static final String TARGET_DIALOG = "DIALOG"; - public static final String TARGET_MODALDIALOG = "MODALDIALOG"; - public static final String TARGET_FLOAT = "FLOAT"; - public static final String TARGET_SIDEBAR = "SIDEBAR"; - - public static final String METHOD_GET = "GET"; - public static final String METHOD_POST = "POST"; - public static final String METHOD_PUT = "PUT"; - public static final String METHOD_DELETE = "DELETE"; - public static final String METHOD_PATCH = "PATCH"; - - private ActionMakers() {} - - /** - * Method application. - * @return ASObject.Builder - */ - public static ASObject.Builder application() { - return object("application"); - } - - /** - * Method service. - * @return ASObject.Builder - */ - public static ASObject.Builder service() { - return object("service"); - } - - /** - * Method styles. - * @return StylesValue.Builder - */ - public static StylesValue.Builder styles() { - return StylesValue.make(); - } - - /** - * Method styles. - * @param media String - * @return StylesValue.Builder - */ - public static StylesValue.Builder styles(String media) { - return styles().media(media); - } - - /** - * Method httpAction. - * @return HttpActionHandler.Builder - */ - public static HttpActionHandler.Builder httpAction() { - return HttpActionHandler.makeHttpActionHandler(); - } - - /** - * Method httpAction. - * @param url String - * @return HttpActionHandler.Builder - */ - public static HttpActionHandler.Builder httpAction(String url) { - return httpAction().url(url); - } - - /** - * Method httpAction. - * @param url String - * @param method String - * @return HttpActionHandler.Builder - */ - public static HttpActionHandler.Builder httpAction( - String url, - String method) { - return httpAction() - .url(url) - .method(method); - } - - /** - * Method embedAction. - * @return EmbedActionHandler.Builder - */ - public static EmbedActionHandler.Builder embedAction() { - return EmbedActionHandler.makeEmbedActionHandler(); - } - - /** - * Method embedAction. - * @param url String - * @return EmbedActionHandler.Builder - */ - public static EmbedActionHandler.Builder embedAction(String url) { - return embedAction().url(url); - } - - /** - * Method embedAction. - * @param url String - * @param mediaType String - * @return EmbedActionHandler.Builder - */ - public static EmbedActionHandler.Builder embedAction( - String url, - String mediaType) { - return embedAction(url).mediaType(mediaType); - } - - /** - * Method staticEmbedAction. - * @param mediaType String - * @param content String - * @return EmbedActionHandler.Builder - */ - public static EmbedActionHandler.Builder staticEmbedAction( - String mediaType, - String content) { - return embedAction().mediaType(mediaType).content(content); - } - - /** - * Method intentAction. - * @return IntentActionHandler.Builder - */ - public static IntentActionHandler.Builder intentAction() { - return IntentActionHandler.makeIntentActionHandler(); - } - - /** - * Method intentAction. - * @param url String - * @return IntentActionHandler.Builder - */ - public static IntentActionHandler.Builder intentAction(String url) { - return intentAction().url(url); - } - - /** - * Method htmlForm. - * @return HtmlForm.Builder - */ - public static HtmlForm.Builder htmlForm() { - return HtmlForm.makeHtmlForm(); - } - - /** - * Method typedPayload. - * @param mediaType String - * @return TypedPayload.Builder - */ - public static TypedPayload.Builder typedPayload(String mediaType) { - return TypedPayload.makeTypedPayload(mediaType); - } - - public static TypedPayload.Builder typedPayload() { - return TypedPayload.make(); - } - - /** - * Method urlTemplate. - * @return UrlTemplate.Builder - */ - public static UrlTemplate.Builder urlTemplate() { - return UrlTemplate.makeUrlTemplate(); - } - - /** - * Method urlTemplate. - * @param template String - * @return UrlTemplate.Builder - */ - public static UrlTemplate.Builder urlTemplate(String template) { - return urlTemplate().template(template); - } - - /** - * Method parameter. - * @return Parameter.Builder - */ - public static Parameter.Builder parameter() { - return Parameter.makeParameter(); - } - - /** - * Method parameter. - * @param id String - * @return Parameter.Builder - */ - public static SimpleParameterValue parameter(String id) { - return new SimpleParameterValue.Builder().type(id).get(); - } -} diff --git a/actions/src/main/java/com/ibm/common/activitystreams/actions/ActionObjectAdapter.java b/actions/src/main/java/com/ibm/common/activitystreams/actions/ActionObjectAdapter.java deleted file mode 100644 index ef7de7f..0000000 --- a/actions/src/main/java/com/ibm/common/activitystreams/actions/ActionObjectAdapter.java +++ /dev/null @@ -1,106 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.actions; - -import java.lang.reflect.Type; - -import com.google.common.collect.ImmutableSet; -import com.ibm.common.activitystreams.ASObject.AbstractBuilder; -import com.ibm.common.activitystreams.internal.ASObjectAdapter; -import com.ibm.common.activitystreams.internal.Model; -import com.ibm.common.activitystreams.internal.Schema; - -public final class ActionObjectAdapter - extends ASObjectAdapter { - - ActionObjectAdapter(Schema schema) { - super(schema); - } - - private static final ImmutableSet> knownTypes = - ImmutableSet.>of( - HttpActionHandler.class, - IntentActionHandler.class, - EmbedActionHandler.class, - HtmlForm.class, - UrlTemplate.class, - TypedPayload.class - ); - - @Override - protected boolean knowsType(Type type) { - if (super.knowsType(type)) - return true; - return knownTypes.contains(type); - } - - @Override - protected AbstractBuilder builderFor(Type type) { - if (super.knowsType(type)) - return super.builderFor(type); - if (type == HttpActionHandler.class) - return ActionMakers.httpAction(); - else if (type == IntentActionHandler.class) - return ActionMakers.intentAction(); - else if (type == EmbedActionHandler.class) - return ActionMakers.embedAction(); - else if (type == HtmlForm.class) - return ActionMakers.htmlForm(); - else if (type == UrlTemplate.class) - return ActionMakers.urlTemplate(); - else if (type == TypedPayload.class) - return ActionMakers.typedPayload(); - else return null; - } - - @Override - protected Model modelFor(Type type) { - if (super.knowsType(type)) - return super.modelFor(type); - if (type == HttpActionHandler.class) - return schema().forObjectClassOrType( - HttpActionHandler.Builder.class, - "HttpActionHandler"); - else if (type == IntentActionHandler.class) - return schema().forObjectClassOrType( - IntentActionHandler.Builder.class, - "IntentActionHandler"); - else if (type == EmbedActionHandler.class) - return schema().forObjectClassOrType( - EmbedActionHandler.Builder.class, - "EmbedActionHandler"); - else if (type == HtmlForm.class) - return schema().forObjectClassOrType( - HtmlForm.Builder.class, - "HtmlForm"); - else if (type == UrlTemplate.class) - return schema().forObjectClassOrType( - UrlTemplate.Builder.class, - "UrlTemplate"); - else if (type == TypedPayload.class) - return schema().forObjectClassOrType( - TypedPayload.Builder.class, - "TypedPayload"); - else return null; - } - -} diff --git a/actions/src/main/java/com/ibm/common/activitystreams/actions/ActionsModule.java b/actions/src/main/java/com/ibm/common/activitystreams/actions/ActionsModule.java deleted file mode 100644 index 6604b8f..0000000 --- a/actions/src/main/java/com/ibm/common/activitystreams/actions/ActionsModule.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.actions; - -import static com.ibm.common.activitystreams.actions.Adapters.AUTH; -import static com.ibm.common.activitystreams.actions.Adapters.STYLES; - -import com.ibm.common.activitystreams.IO.Builder; -import com.ibm.common.activitystreams.internal.Model; -import com.ibm.common.activitystreams.internal.Schema; -import com.ibm.common.activitystreams.util.Module; - -public final class ActionsModule - implements Module { - - public static final Module instance = new ActionsModule(); - - @Override - public void apply(Builder builder, Schema schema) { - - ActionObjectAdapter base = - new ActionObjectAdapter(schema); - - // Register Adapters - builder.hierarchicalAdapter(ActionHandler.class,base) - .hierarchicalAdapter(HttpActionHandler.class,base) - .hierarchicalAdapter(IntentActionHandler.class,base) - .hierarchicalAdapter(EmbedActionHandler.class,base) - .hierarchicalAdapter(HtmlForm.class,base) - .hierarchicalAdapter(ParametersValue.class, ParametersAdapter.instance) - .hierarchicalAdapter(ParameterValue.class, ParameterAdapter.instance) - .hierarchicalAdapter(UrlTemplate.class,base) - .hierarchicalAdapter(TypedPayload.class,base) - .hierarchicalAdapter(Authentication.class, AUTH) - .hierarchicalAdapter(StylesValue.class, STYLES); - } - - @Override - public void apply(Schema.Builder builder) { - builder.map("HtmlForm", withParameters.template(HtmlForm.class, HtmlForm.Builder.class)) - .map("TypedPayload", typedPayload) - .map("UrlTemplate", withParameters.template(UrlTemplate.class, UrlTemplate.Builder.class)) - .map("HttpActionHandler", actionHandler.template(HttpActionHandler.class, HttpActionHandler.Builder.class)) - .map("IntentActionHandler", actionHandler.template(IntentActionHandler.class, IntentActionHandler.Builder.class)) - .map("EmbedActionHandler", actionHandler.template(EmbedActionHandler.class, EmbedActionHandler.Builder.class)); - } - - public final static Model actionHandler = - Model - .make("object") - .linkValue( - "expects", - "returns", - "requires", - "prefers") - .object("context") - .as("auth", Authentication.class) - .as("style", StylesValue.class) - .get(); - - - public final static Model withParameters = - Model - .make("object") - .as("parameters", ParametersValue.class) - .get(); - - public final static Model typedPayload = - Model - .make("object") - .type(TypedPayload.class, TypedPayload.Builder.class) - .linkValue("schema") - .typeValue("type") - .get(); - - - -} diff --git a/actions/src/main/java/com/ibm/common/activitystreams/actions/Authentication.java b/actions/src/main/java/com/ibm/common/activitystreams/actions/Authentication.java deleted file mode 100755 index 87be702..0000000 --- a/actions/src/main/java/com/ibm/common/activitystreams/actions/Authentication.java +++ /dev/null @@ -1,108 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.actions; - -import java.io.Serializable; -import java.util.Map; - -import com.google.common.collect.ImmutableMap; -import com.ibm.common.activitystreams.ASObject; -import com.ibm.common.activitystreams.util.AbstractDictionaryObject; - -/** - */ -public final class Authentication - extends AbstractDictionaryObject { - - /** - * Method make. - * @return Builder - */ - public static Builder make() { - return new Builder(); - } - - /** - */ - public static final class Builder - extends AbstractDictionaryObject.AbstractBuilder< - ASObject,Authentication,Builder> { - - public Builder() { - writeUsing(ActionMakers.io); - } - - /** - * Method get. - * @return Authentication - * @see com.google.common.base.Supplier#get() - */ - public Authentication get() { - return new Authentication(this); - } - - } - - /** - * Constructor for Authentication. - * @param builder Builder - */ - protected Authentication(Builder builder) { - super(builder); - } - - /** - * Method get. - * @param key String - * @return A - */ - @SuppressWarnings("unchecked") - public A get(String key) { - return (A)this.getSingle(key); - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - implements Serializable { - private static final long serialVersionUID = -1975376657749952999L; - private ImmutableMap map; - SerializedForm(Authentication obj) { - ImmutableMap.Builder builder = - ImmutableMap.builder(); - for (String key : obj) - builder.put(key, obj.get(key)); - this.map = builder.build(); - } - - Object readResolve() - throws java.io.ObjectStreamException { - Authentication.Builder builder = - Authentication.make(); - for (Map.Entry entry : map.entrySet()) - builder.set(entry.getKey(), (ASObject) entry.getValue()); - return builder.get(); - } - } -} diff --git a/actions/src/main/java/com/ibm/common/activitystreams/actions/EmbedActionHandler.java b/actions/src/main/java/com/ibm/common/activitystreams/actions/EmbedActionHandler.java deleted file mode 100755 index 7e5a559..0000000 --- a/actions/src/main/java/com/ibm/common/activitystreams/actions/EmbedActionHandler.java +++ /dev/null @@ -1,234 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.actions; - -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.collect.Iterables.filter; -import static com.google.common.collect.Iterables.getFirst; -import static com.google.common.collect.Iterables.size; - -import java.io.ObjectStreamException; -import java.io.Serializable; - -import com.google.common.base.Predicate; -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableList; - -/** - */ -public class EmbedActionHandler - extends ActionHandler - implements Serializable { - - /** - * Method makeEmbedActionHandler. - * @return Builder - */ - public static Builder makeEmbedActionHandler() { - return new Builder(); - } - - /** - */ - public static final class Builder - extends AbstractBuilder { - - public Builder() { - super("EmbedActionHandler"); - } - - /** - * Method getActual. - * @return EmbedActionHandler - */ - protected EmbedActionHandler getActual() { - return new EmbedActionHandler(this); - } - - } - - /** - */ - @SuppressWarnings("unchecked") - public static abstract class AbstractBuilder> - extends ActionHandler.Builder { - - private boolean styleset = false; - private static ImmutableList.Builder styles = - ImmutableList.builder(); - - /** - * Constructor for AbstractBuilder. - * @param objectType String - */ - protected AbstractBuilder(String objectType) { - objectType(objectType); - } - - /** - * Method target. - * @param target String - * @return B - */ - public B target(String target) { - set("target", target); - return (B)this; - } - - /** - * Method style. - * @param style StylesValue - * @return B - */ - public B style(StylesValue style) { - styleset = true; - styles.add(style); - return (B)this; - } - - /** - * Method style. - * @param style Supplier - * @return B - */ - public B style(Supplier style) { - return style(style.get()); - } - - /** - * Method style. - * @param styles StylesValue[] - * @return B - */ - public B style(StylesValue... styles) { - for (StylesValue s : styles) - style(s); - return (B)this; - } - - /** - * Method style. - * @param styles Supplier[] - * @return B - */ - public B style(Supplier... styles) { - for (Supplier s : styles) - style(s); - return (B)this; - } - - /** - * Method actualGet. - * @return A - */ - protected final A actualGet() { - if (styleset) { - ImmutableList val = styles.build(); - if (size(val) == 1) { - set("style", getFirst(val,null)); - } else { - set("style", val); - } - } - return getActual(); - } - - /** - * Method getActual. - * @return A - */ - protected abstract A getActual(); - } - - /** - * Constructor for EmbedActionHandler. - * @param builder AbstractBuilder - */ - protected EmbedActionHandler(AbstractBuilder builder) { - super(builder); - } - - /** - * Method styles. - * @return Iterable - */ - @SuppressWarnings("unchecked") - public Iterable styles() { - Object styles = get("style"); - if (styles instanceof StylesValue) - return ImmutableList.of((StylesValue)styles); - else if (styles instanceof Iterable) - return (Iterable)styles; - else return ImmutableList.of(); - } - - /** - * Method styles. - * @param media String - * @return Iterable - */ - public Iterable styles(final String media) { - checkNotNull(media); - return styles(new Predicate() { - public boolean apply(StylesValue style) { - return media.equalsIgnoreCase(style.media()); - } - }); - } - - /** - * Method styles. - * @param matcher Predicate - * @return Iterable - */ - public Iterable styles(Predicate matcher) { - return filter(styles(), matcher); - } - - /** - * Method target. - * @return String - */ - public String target() { - return getString( - "target", - ActionMakers.TARGET_DEFAULT); - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936285L; - protected SerializedForm(EmbedActionHandler obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return super.doReadResolve(); - } - protected EmbedActionHandler.Builder builder() { - return ActionMakers.embedAction(); - } - } -} diff --git a/actions/src/main/java/com/ibm/common/activitystreams/actions/HtmlForm.java b/actions/src/main/java/com/ibm/common/activitystreams/actions/HtmlForm.java deleted file mode 100755 index b6fe0ad..0000000 --- a/actions/src/main/java/com/ibm/common/activitystreams/actions/HtmlForm.java +++ /dev/null @@ -1,120 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.actions; - -import java.io.ObjectStreamException; - -import com.google.common.base.Supplier; -import com.ibm.common.activitystreams.ASObject; - -/** - */ -public final class HtmlForm - extends ASObject { - - /** - * Method makeHtmlForm. - * @return Builder - */ - public static Builder makeHtmlForm() { - return new Builder(); - } - - /** - */ - public static final class Builder - extends ASObject.AbstractBuilder { - - private final ParametersValue.Builder params = - ParametersValue.make(); - - public Builder() { - writeUsing(ActionMakers.io); - objectType("HtmlForm"); - mediaType("application/x-www-form-urlencoded"); - } - - public Builder parameter(String name, String iri) { - params.param(name, iri); - return this; - } - - public Builder parameter( - String name, - ParameterValue parameter) { - params.param(name, parameter); - return this; - } - - public Builder parameter( - String name, - Supplier parameter) { - return parameter(name, parameter.get()); - } - - /** - * Method get. - * @return HtmlForm - * @see com.google.common.base.Supplier#get() - */ - public HtmlForm get() { - if (params.notEmpty()) - set("parameters", params.get()); - return new HtmlForm(this); - } - - } - - /** - * Constructor for HtmlForm. - * @param builder Builder - */ - private HtmlForm(Builder builder) { - super(builder); - } - - /** - * Method parameters. - * @return ParametersValue - */ - public ParametersValue parameters() { - return this.get("parameters"); - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936285L; - protected SerializedForm(HtmlForm obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return super.doReadResolve(); - } - protected HtmlForm.Builder builder() { - return ActionMakers.htmlForm(); - } - } -} diff --git a/actions/src/main/java/com/ibm/common/activitystreams/actions/HttpActionHandler.java b/actions/src/main/java/com/ibm/common/activitystreams/actions/HttpActionHandler.java deleted file mode 100755 index 6993011..0000000 --- a/actions/src/main/java/com/ibm/common/activitystreams/actions/HttpActionHandler.java +++ /dev/null @@ -1,137 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.actions; - -import java.io.ObjectStreamException; - - -/** - */ -public class HttpActionHandler - extends ActionHandler { - - /** - * Method makeHttpActionHandler. - * @return Builder - */ - public static Builder makeHttpActionHandler() { - return new Builder(); - } - - /** - */ - public static final class Builder - extends AbstractBuilder { - - public Builder() { - super("HttpActionHandler"); - } - - /** - * Method actualGet. - * @return HttpActionHandler - */ - protected HttpActionHandler actualGet() { - return new HttpActionHandler(this); - } - - } - - /** - */ - @SuppressWarnings("unchecked") - public static abstract class AbstractBuilder - > - extends ActionHandler.Builder { - /** - * Constructor for AbstractBuilder. - * @param objectType String - */ - protected AbstractBuilder(String objectType) { - objectType(objectType); - } - - /** - * Method method. - * @param method String - * @return B - */ - public B method(String method) { - set("method", method); - return (B)this; - } - - /** - * Method target. - * @param target String - * @return B - */ - public B target(String target) { - set("target", target); - return (B)this; - } - } - - /** - * Constructor for HttpActionHandler. - * @param builder AbstractBuilder - */ - protected HttpActionHandler(AbstractBuilder builder) { - super(builder); - } - - /** - * Method method. - * @return String - */ - public String method() { - return this.getString("method"); - } - - /** - * Method target. - * @return String - */ - public String target() { - return has("target") ? - this.get("target") : - ActionMakers.TARGET_DEFAULT; - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936285L; - protected SerializedForm(HttpActionHandler obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return super.doReadResolve(); - } - protected HttpActionHandler.Builder builder() { - return ActionMakers.httpAction(); - } - } -} diff --git a/actions/src/main/java/com/ibm/common/activitystreams/actions/IntentActionHandler.java b/actions/src/main/java/com/ibm/common/activitystreams/actions/IntentActionHandler.java deleted file mode 100755 index ab8eee4..0000000 --- a/actions/src/main/java/com/ibm/common/activitystreams/actions/IntentActionHandler.java +++ /dev/null @@ -1,98 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.actions; - -import java.io.ObjectStreamException; - - -/** - */ -public class IntentActionHandler - extends ActionHandler { - - /** - * Method makeIntentActionHandler. - * @return Builder - */ - public static Builder makeIntentActionHandler() { - return new Builder(); - } - - /** - */ - public static final class Builder - extends AbstractBuilder { - - public Builder() { - super("IntentActionHandler"); - } - - /** - * Method actualGet. - * @return IntentActionHandler - */ - protected IntentActionHandler actualGet() { - return new IntentActionHandler(this); - } - - } - - /** - */ - public static abstract class AbstractBuilder - > - extends ActionHandler.Builder { - /** - * Constructor for AbstractBuilder. - * @param objectType String - */ - protected AbstractBuilder(String objectType) { - objectType(objectType); - } - } - - /** - * Constructor for IntentActionHandler. - * @param builder AbstractBuilder - */ - protected IntentActionHandler(AbstractBuilder builder) { - super(builder); - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936285L; - protected SerializedForm(IntentActionHandler obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return super.doReadResolve(); - } - protected IntentActionHandler.Builder builder() { - return ActionMakers.intentAction(); - } - } -} diff --git a/actions/src/main/java/com/ibm/common/activitystreams/actions/Parameter.java b/actions/src/main/java/com/ibm/common/activitystreams/actions/Parameter.java deleted file mode 100755 index d692442..0000000 --- a/actions/src/main/java/com/ibm/common/activitystreams/actions/Parameter.java +++ /dev/null @@ -1,744 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.actions; - -import static com.ibm.common.activitystreams.Makers.nlv; -import static com.ibm.common.activitystreams.util.Util.DEFAULT_LOCALE; - -import java.io.Serializable; -import java.util.Map; -import java.util.regex.Pattern; - -import com.google.common.base.Objects; -import com.google.common.base.Supplier; -import com.google.common.collect.BoundType; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.common.collect.Maps; -import com.google.common.collect.Ordering; -import com.google.common.collect.Range; -import com.ibm.common.activitystreams.Makers; -import com.ibm.common.activitystreams.NLV; -import com.ibm.common.activitystreams.ValueType; -import com.ibm.common.activitystreams.NLV.MapNLV; -import com.ibm.common.activitystreams.NLV.SimpleNLV; -import com.ibm.common.activitystreams.util.AbstractWritable; - -@SuppressWarnings("unchecked") -public class Parameter - extends AbstractWritable - implements ParameterValue { - - /** - * Method makeParameter. - * @return Builder - */ - public static Builder makeParameter() { - return new Builder(); - } - - public static class Builder - extends AbstractWritable.AbstractWritableBuilder { - - protected Builder() { - writeUsing(ActionMakers.io); - } - - private final Map map = - Maps.newHashMap(); - - public Builder language(String lang) { - if (lang != null) - map.put("language", lang); - else - map.remove("language"); - return this; - } - - protected Builder _nlv(String key, String value) { - if (value != null) - map.put(key, nlv(value)); - else - map.remove(key); - return this; - } - - protected Builder _nlv(String key, NLV nlv) { - if (nlv != null) - map.put(key, nlv); - else - map.remove(key); - return this; - } - - protected Builder _nlv(String key, Supplier nlv) { - return _nlv(key,nlv.get()); - } - - protected Builder _nlv(String key, Map map) { - if (map != null) - for (Map.Entry entry : map.entrySet()) - _nlv(key,entry.getKey(),entry.getValue()); - else - this.map.remove(key); - return this; - } - - protected Builder _nlv(String key, String lang, String value) { - if (map.containsKey(key)) { - Object obj = map.get(key); - if (obj instanceof NLV) { - NLV nlv = (NLV) obj; - switch(nlv.valueType()) { - case SIMPLE: - String l = (String) map.get("language"); - if (l == null) - l = DEFAULT_LOCALE; - NLV.MapNLV.Builder b = - Makers.nlv(); - if (lang.equals(l)) - b.set(lang, value); - else - b.set(l, ((NLV.SimpleNLV)obj).value()) - .set(lang, value); - map.put(key, b); - return this; - case OBJECT: - map.put(key, - Makers.nlv() - .from((NLV.MapNLV)obj, lang) - .set(lang, value)); - return this; - default: - throw new IllegalArgumentException(); - } - } else if (obj instanceof NLV.MapNLV.Builder) { - ((NLV.MapNLV.Builder) obj).set(lang, value); - return this; - } - } - map.put(key, Makers.nlv().set(lang,value)); - return this; - } - - public Builder displayName(String val) { - return _nlv("displayName",val); - } - - public Builder displayName(NLV nlv) { - return _nlv("displayName", nlv); - } - - public Builder displayName(Supplier nlv) { - return _nlv("displayName", nlv); - } - - public Builder displayName(String lang, String val) { - return _nlv("displayName", lang, val); - } - - public Builder placeholder(String placeholder) { - return _nlv("placeholder", placeholder); - } - - public Builder placeholder(NLV placeholder) { - return _nlv("placeholder", placeholder); - } - - public Builder placeholder(Supplier nlv) { - return _nlv("placeholder", nlv); - } - - public Builder placeholder(String lang, String val) { - return _nlv("placeholder", lang, val); - } - - public Builder type(String type) { - if (type != null) - map.put("type", type); - else - map.remove("type"); - return this; - } - - public Builder required() { - map.remove("required"); - return this; - } - - public Builder optional() { - map.put("required", false); - return this; - } - - public Builder repeated() { - map.put("repeated", true); - return this; - } - - public Builder notRepeated() { - map.remove("repeated"); - return this; - } - - public Builder value(Object value) { - if (value != null) - map.put("value", value); - else - map.remove("value"); - return this; - } - - public Builder defaultValue(Object value) { - if (value != null) - map.put("default", value); - else - map.remove("default"); - return this; - } - - public Builder pattern(Pattern... pattern) { - if (pattern != null && pattern.length > 0) { - ImmutableSet.Builder patterns = - ImmutableSet.builder(); - for (Pattern p : pattern) - patterns.add(p.pattern()); - map.put("pattern",patterns.build()); - } else { - map.remove("pattern"); - } - return this; - } - - public Builder pattern(String... pattern) { - if (pattern != null && pattern.length > 0) { - ImmutableSet patterns = - ImmutableSet.copyOf(pattern); - map.put("pattern",patterns); - } else { - map.remove("pattern"); - } - return this; - } - - public Builder pattern(Iterable patterns) { - if (patterns != null && Iterables.size(patterns) > 0) { - map.put("pattern", ImmutableSet.copyOf(patterns)); - } else - map.remove("pattern"); - return this; - } - - public Builder minInclusive(Object min) { - if (min != null) - map.put("minInclusive", min); - else - map.remove("minInclusive"); - return this; - } - - public Builder minExclusive(Object min) { - if (min != null) - map.put("minExclusive", min); - else - map.remove("minExclusive"); - return this; - } - - public Builder maxInclusive(Object max) { - if (max != null) - map.put("maxInclusive", max); - else - map.remove("maxInclusive"); - return this; - } - - public Builder maxExclusive(Object max) { - if (max != null) - map.put("maxExclusive", max); - else - map.remove("maxExclusive"); - return this; - } - - public Builder bound(Range range) { - if (range != null) { - if (range.hasLowerBound()) { - switch(range.lowerBoundType()) { - case CLOSED: - minInclusive(range.lowerEndpoint()); - break; - case OPEN: - minExclusive(range.lowerEndpoint()); - break; - default: - break; - } - } else { - minInclusive(null); - minExclusive(null); - } - if (range.hasUpperBound()) { - switch(range.upperBoundType()) { - case CLOSED: - maxInclusive(range.upperEndpoint()); - break; - case OPEN: - maxExclusive(range.upperEndpoint()); - break; - default: - break; - } - } else { - maxInclusive(null); - maxExclusive(null); - } - } - return this; - } - - public Builder step(Number step) { - if (step != null) - map.put("step", step); - else - map.remove("step"); - return this; - } - - public Builder enumeration(Object... vals) { - if (vals != null && vals.length > 0) - map.put("enumeration", ImmutableList.copyOf(vals)); - else - map.remove("enumeration"); - return this; - } - - public Builder maxLength(int length) { - if (length > -1) - map.put("maxLength", length); - else - map.remove("maxLength"); - return this; - } - - public Builder minLength(int length) { - if (length > -1) - map.put("minLength", length); - else - map.remove("minLength"); - return this; - } - - public Builder totalDigits(int num) { - if (num > -1) - map.put("totalDigits", num); - else - map.remove("totalDigits"); - return this; - } - - public Builder fractionDigits(int num) { - if (num > -1) - map.put("fractionDigits", num); - else - map.remove("fractionDigits"); - return this; - } - - public Parameter get() { - return new Parameter(this); - } - - } - - private final ImmutableMap map; - - /** - * Constructor for Parameter. - * @param builder Builder - */ - protected Parameter(Builder builder) { - super(builder); - this.map = ImmutableMap.copyOf(builder.map); - } - - /** - * Method required. - * @return boolean - */ - public boolean required() { - return !has("required") ? - true : (Boolean)map.get("required"); - } - - /** - * Method repeated. - * @return boolean - */ - public boolean repeated() { - return !has("repeated") ? - false : (Boolean)map.get("repeated"); - } - - /** - * Method value. - * @return O - */ - public O value() { - return (O)map.get("value"); - } - - /** - * Method value. - * @param defaultValue O - * @return O - */ - public O value(O defaultValue) { - O val = value(); - return val != null ? val : defaultValue; - } - - /** - * Method defaultValue. - * @return O - */ - public O defaultValue() { - return (O)map.get("default"); - } - - /** - * Method defaultValue. - * @param defaultValue O - * @return O - */ - public O defaultValue(O defaultValue) { - O val = defaultValue(); - return val != null ? val : defaultValue; - } - - public String type() { - return (String)map.get("type"); - } - - /** - * Method pattern. - * @return String - */ - public Iterable pattern() { - return (Iterable)map.get("pattern"); - } - - public O maxInclusive() { - return (O)map.get("maxInclusive"); - } - - public O maxExclusive() { - return (O)map.get("maxExclusive"); - } - - public O minInclusive() { - return (O)map.get("minInclusive"); - } - - public O minExclusive() { - return (O)map.get("minExclusive"); - } - - public boolean has(String key) { - return map.containsKey(key); - } - - public boolean hasUpperBound() { - return has("maxInclusive") || has("maxExclusive"); - } - - public >Range bounds() { - O mini = minInclusive(); - O mine = minExclusive(); - O maxi = maxInclusive(); - O maxe = maxExclusive(); - Ordering ordering = Ordering.natural(); - O min = ordering.nullsLast().min(mini,mine); - O max = ordering.nullsFirst().max(maxi,maxe); - BoundType lower = - min == null ? null : - min == mini ? BoundType.CLOSED : - BoundType.OPEN; - BoundType upper = - max == null ? null : - max == maxi ? BoundType.CLOSED : - BoundType.OPEN; - if (lower == null && upper == null) - return Range.all(); - else if (lower != null && upper == null) - return lower == BoundType.CLOSED ? - Range.atLeast(min) : - Range.greaterThan(min); - else if (lower == null && upper != null) - return upper == BoundType.CLOSED ? - Range.atMost(max) : - Range.lessThan(max); - else { - return Range.range(min, lower, max, upper); - } - } - - public N step() { - return (N)map.get("step"); - } - - public N step(N defaultValue) { - N n = (N)map.get("step"); - return n != null ? n : defaultValue; - } - - /** - * Method stepInt. - * @return int - */ - public int stepInt() { - return step(); - } - - /** - * Method stepInt. - * @param defaultValue int - * @return int - */ - public int stepInt(int defaultValue) { - return step(defaultValue); - } - - /** - * Method stepLong. - * @return long - */ - public long stepLong() { - return step(); - } - - /** - * Method getLong. - * @param defaultValue long - * @return long - */ - public long stepLong(long defaultValue) { - return step(defaultValue); - } - - /** - * Method stepShort. - * @return short - */ - public short stepShort() { - return step(); - } - - /** - * Method stepShort. - * @param defaultValue short - * @return short - */ - public short stepShort(short defaultValue) { - return step(defaultValue); - } - - /** - * Method stepDouble. - * @return double - */ - public double stepDouble() { - return step(); - } - - /** - * Method stepDouble. - * @param defaultValue double - * @return double - */ - public double stepDouble(double defaultValue) { - return step(defaultValue); - } - - /** - * Method stepFloat. - * @return float - */ - public float stepFloat() { - return step(); - } - - /** - * Method stepFloat. - * @param defaultValue float - * @return float - */ - public float stepFloat(float defaultValue) { - return step(defaultValue); - } - - /** - * Method enumVals. - * @return Iterable - */ - public Iterable enumeration() { - if (has("enumeration")) - return (Iterable)map.get("enumeration"); - else - return ImmutableSet.of(); - } - - /** - * Method placeholder. - * @return NLV - */ - public NLV placeholder() { - return (NLV)map.get("placeholder"); - } - - /** - * Method placeholderString. - * @return String - */ - public String placeholderString() { - return _nlv("placeholder"); - } - - /** - * Method placeholderString. - * @param lang String - * @return String - */ - public String placeholderString(String lang) { - return _nlv("placeholder", lang); - } - - public int maxLength() { - Integer i = (Integer) map.get("maxLength"); - return i != null ? i : -1; - } - - public int minLength() { - Integer i = (Integer) map.get("minLength"); - return i != null ? i : -1; - } - - public int totalDigits() { - Integer i = (Integer) map.get("totalDigits"); - return i != null ? i : -1; - } - - public int fractionDigits() { - Integer i = (Integer) map.get("fractionDigits"); - return i != null ? i : -1; - } - - /** - * Method placeholder. - * @return NLV - */ - public NLV displayName() { - return (NLV)map.get("displayName"); - } - - /** - * Method placeholderString. - * @return String - */ - public String displayNameString() { - return _nlv("displayName"); - } - - /** - * Method placeholderString. - * @param lang String - * @return String - */ - public String displayNameString(String lang) { - return _nlv("displayName", lang); - } - - public String language() { - return (String)map.get("language"); - } - - /** - * Method _nlv. - * @param key String - * @return String - **/ - protected String _nlv(String key) { - String lang = language(); - return _nlv(key, lang != null ? lang : DEFAULT_LOCALE); - } - - /** - * Method _nlv. - * @param key String - * @param lang String - * @return String - **/ - protected String _nlv(String key, String lang) { - NLV nlv = - (NLV)map.get(key); - switch(nlv.valueType()) { - case SIMPLE: - NLV.SimpleNLV sim = - (SimpleNLV) nlv; - String l = language(); - return l == null || Objects.equal(l,lang) ? sim.value() : null; - case OBJECT: - NLV.MapNLV map = - (MapNLV) nlv; - return map.value(lang); - default: - return null; - } - } - - public ValueType valueType() { - return ValueType.OBJECT; - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - implements Serializable { - private static final long serialVersionUID = -1975376657749952999L; - private ImmutableMap map; - SerializedForm(Parameter obj) { - this.map = obj.map; - } - - Object readResolve() - throws java.io.ObjectStreamException { - Parameter.Builder builder = new Parameter.Builder(); - builder.map.putAll(map); - return builder.get(); - } - - } -} diff --git a/actions/src/main/java/com/ibm/common/activitystreams/actions/ParameterAdapter.java b/actions/src/main/java/com/ibm/common/activitystreams/actions/ParameterAdapter.java deleted file mode 100644 index e75bd13..0000000 --- a/actions/src/main/java/com/ibm/common/activitystreams/actions/ParameterAdapter.java +++ /dev/null @@ -1,260 +0,0 @@ -package com.ibm.common.activitystreams.actions; - -import java.lang.reflect.Type; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.common.collect.Iterables; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.ibm.common.activitystreams.ASObject; -import com.ibm.common.activitystreams.NLV; -import com.ibm.common.activitystreams.actions.ParameterValue.SimpleParameterValue; -import com.ibm.common.activitystreams.internal.Adapter; - -public final class ParameterAdapter - extends Adapter { - - public static final ParameterAdapter instance = - new ParameterAdapter(); - - @Override - public JsonElement serialize( - ParameterValue src, - Type typeOfSrc, - JsonSerializationContext context) { - - if (src == null) return null; - switch(src.valueType()) { - case OBJECT: - if (src instanceof Parameter) { - Parameter parameter = (Parameter) src; - JsonObject obj = new JsonObject(); - if (parameter.has("type")) { - String type = parameter.type(); - if (type != null) - obj.addProperty("type", type); - } - if (parameter.has("displayName")) { - NLV nlv = parameter.displayName(); - if (nlv != null) - obj.add("displayName", context.serialize(nlv, NLV.class)); - } - if (parameter.has("placeholder")) { - NLV nlv = parameter.placeholder(); - if (nlv != null) - obj.add("placeholder", context.serialize(nlv, NLV.class)); - } - if (parameter.has("enumeration")) { - Iterable e = parameter.enumeration(); - if (e != null) - obj.add("enumeration", context.serialize(e,e.getClass())); - } - if (parameter.has("language")) { - String lang = parameter.language(); - if (lang != null) - obj.addProperty("language", lang); - } - if (parameter.has("maxInclusive")) { - Object max = parameter.maxInclusive(); - if (max != null) - obj.add("maxInclusive", context.serialize(max, max.getClass())); - } - if (parameter.has("maxExclusive")) { - Object max = parameter.maxExclusive(); - if (max != null) - obj.add("maxExclusive", context.serialize(max, max.getClass())); - } - if (parameter.has("minInclusive")) { - Object max = parameter.minInclusive(); - if (max != null) - obj.add("minInclusive", context.serialize(max, max.getClass())); - } - if (parameter.has("minExclusive")) { - Object max = parameter.minExclusive(); - if (max != null) - obj.add("minExclusive", context.serialize(max, max.getClass())); - } - if (parameter.has("pattern")) { - Iterable pattern = parameter.pattern(); - if (pattern != null) { - if (Iterables.size(pattern) == 0) { - String first = Iterables.getFirst(pattern, null); - if (first != null) - obj.addProperty("pattern", first); - } else - obj.add("pattern", context.serialize(pattern, pattern.getClass())); - } - } - if (parameter.has("repeated")) { - boolean repeated = parameter.repeated(); - if (repeated) - obj.addProperty("repeated", repeated); - } - if (parameter.has("required")) { - boolean required = parameter.required(); - if (!required) - obj.addProperty("required", required); - } - if (parameter.has("step")) { - Number n = parameter.step(); - if (n != null) - obj.add("step", context.serialize(n,n.getClass())); - } - if (parameter.has("default")) { - Object def = parameter.defaultValue(); - if (def != null) - obj.add("default",context.serialize(def, def.getClass())); - } - if (parameter.has("minLength")) { - int len = parameter.minLength(); - if (len > -1) - obj.addProperty("minLength", len); - } - if (parameter.has("maxLength")) { - int len = parameter.maxLength(); - if (len > -1) - obj.addProperty("maxLength", len); - } - if (parameter.has("totalDigits")) { - int len = parameter.totalDigits(); - if (len > -1) - obj.addProperty("totalDigits", len); - } - if (parameter.has("fractionDigits")) { - int len = parameter.fractionDigits(); - if (len > -1) - obj.addProperty("fractionDigits", len); - } - if (parameter.has("value")) { - Object val = parameter.value(); - if (val != null) - obj.add("value", context.serialize(val, val.getClass())); - } - return obj; - } else if (src instanceof UrlTemplate) { - return context.serialize(src, UrlTemplate.class); - } else if (src instanceof TypedPayload) { - return context.serialize(src, TypedPayload.class); - } else if (src instanceof ASObject) { - return context.serialize(src, ASObject.class); - } else throw new IllegalArgumentException(); - case SIMPLE: - SimpleParameterValue spv = (SimpleParameterValue) src; - return context.serialize(spv.type(), String.class); - default: - throw new IllegalArgumentException(); - } - } - - private Object deserialize( - JsonDeserializationContext context, - JsonElement el) { - if (el.isJsonArray()) { - return context.deserialize(el, Iterable.class); - } else if (el.isJsonObject()) { - return context.deserialize(el, ASObject.class); - } else if (el.isJsonPrimitive()) { - JsonPrimitive p = el.getAsJsonPrimitive(); - if (p.isBoolean()) - return p.getAsBoolean(); - else if (p.isNumber()) - return p.getAsNumber(); - else - return p.getAsString(); - } else return null; - } - - @Override - public ParameterValue deserialize( - JsonElement json, - Type typeOfT, - JsonDeserializationContext context) - throws JsonParseException { - - checkArgument(json.isJsonPrimitive() || json.isJsonObject()); - - if (json.isJsonPrimitive()) { - JsonPrimitive jp = json.getAsJsonPrimitive(); - checkArgument(jp.isString()); - return ActionMakers.parameter(jp.getAsString()); - } else { - JsonObject obj = json.getAsJsonObject(); - if (obj.has("objectType")) { - ASObject as = context.deserialize(obj, ASObject.class); - checkArgument(as instanceof ParameterValue); - return (ParameterValue) as; - } else { - Parameter.Builder builder = - ActionMakers.parameter(); - if (obj.has("default")) - builder.defaultValue( - deserialize(context, obj.get("default"))); - if (obj.has("displayName")) - builder.displayName( - context.deserialize( - obj.get("displayName"), - NLV.class)); - if (obj.has("enumeration")) - builder.enumeration( - context.>deserialize( - obj.get("enumeration"), - Iterable.class)); - if (obj.has("fractionDigits")) - builder.fractionDigits( - obj.get("fractionDigits").getAsInt()); - if (obj.has("language")) - builder.language( - obj.get("language").getAsString()); - if (obj.has("maxExclusive")) - builder.maxExclusive( - deserialize(context, obj.get("maxExclusive"))); - if (obj.has("maxInclusive")) - builder.maxInclusive( - deserialize(context, obj.get("maxInclusive"))); - if (obj.has("minExclusive")) - builder.minExclusive( - deserialize(context, obj.get("minExclusive"))); - if (obj.has("minInclusive")) - builder.minInclusive( - deserialize(context, obj.get("minInclusive"))); - if (obj.has("maxLength")) - builder.maxLength( - obj.get("maxLength").getAsInt()); - if (obj.has("minLength")) - builder.minLength( - obj.get("minLength").getAsInt()); - if (obj.has("pattern")) - builder.pattern( - context.>deserialize( - obj.get("pattern"), Iterable.class)); - if (obj.has("placeholder")) - builder.placeholder( - context.deserialize( - obj.get("placeholder"), NLV.class)); - if (obj.has("repeated") && obj.get("repeated").getAsBoolean()) - builder.repeated(); - if (obj.has("required") && !obj.get("required").getAsBoolean()) - builder.optional(); - if (obj.has("step")) - builder.step( - obj.get("step").getAsNumber()); - if (obj.has("totalDigits")) - builder.totalDigits( - obj.get("totalDigits").getAsInt()); - if (obj.has("type")) - builder.type( - obj.get("type").getAsString()); - if (obj.has("value")) - builder.value( - deserialize(context, obj.get("value"))); - return builder.get(); - } - } - } - -} diff --git a/actions/src/main/java/com/ibm/common/activitystreams/actions/ParameterValue.java b/actions/src/main/java/com/ibm/common/activitystreams/actions/ParameterValue.java deleted file mode 100644 index 9722b4b..0000000 --- a/actions/src/main/java/com/ibm/common/activitystreams/actions/ParameterValue.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.ibm.common.activitystreams.actions; - -import java.io.Serializable; - -import com.google.common.base.Objects; -import com.ibm.common.activitystreams.IO; -import com.ibm.common.activitystreams.ValueType; -import com.ibm.common.activitystreams.Writable; -import com.ibm.common.activitystreams.util.AbstractWritable; - -public interface ParameterValue - extends Writable, Serializable { - - ValueType valueType(); - - String toString(IO io); - - public static final class SimpleParameterValue - extends AbstractWritable - implements ParameterValue { - - static final class Builder - extends AbstractWritable.AbstractWritableBuilder { - - private String type; - - public Builder() { - writeUsing(ActionMakers.io); - } - - public Builder type(String type) { - this.type = type; - return this; - } - - @Override - public SimpleParameterValue get() { - return new SimpleParameterValue(this); - } - - } - - private final String type; - - private SimpleParameterValue(Builder b) { - super(b); - this.type = b.type; - } - - public ValueType valueType() { - return ValueType.SIMPLE; - } - - public String type() { - return type; - } - - @Override - public int hashCode() { - return Objects.hashCode(type); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - SimpleParameterValue other = (SimpleParameterValue) obj; - return Objects.equal(type,other.type); - } - - public String toString(IO io) { - return super.toString(io); - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - implements Serializable { - private static final long serialVersionUID = -1975376657749952999L; - private String type; - SerializedForm(SimpleParameterValue obj) { - this.type = obj.type; - } - - Object readResolve() - throws java.io.ObjectStreamException { - return new SimpleParameterValue.Builder().type(type).get(); - } - } - - } - -} diff --git a/actions/src/main/java/com/ibm/common/activitystreams/actions/ParametersAdapter.java b/actions/src/main/java/com/ibm/common/activitystreams/actions/ParametersAdapter.java deleted file mode 100644 index f65726a..0000000 --- a/actions/src/main/java/com/ibm/common/activitystreams/actions/ParametersAdapter.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.ibm.common.activitystreams.actions; - -import java.lang.reflect.Type; -import java.util.Map; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonSerializationContext; -import com.ibm.common.activitystreams.internal.Adapter; - -public final class ParametersAdapter - extends Adapter { - - public static final ParametersAdapter instance = - new ParametersAdapter(); - - @Override - public JsonElement serialize( - ParametersValue params, - Type type, - JsonSerializationContext context) { - if (params == null) return null; - JsonObject obj = new JsonObject(); - for (String param : params) { - obj.add( - param, - context.serialize( - params.get(param), - ParameterValue.class)); - } - return obj; - } - - @Override - public ParametersValue deserialize( - JsonElement json, - Type type, - JsonDeserializationContext context) - throws JsonParseException { - checkArgument(json.isJsonObject()); - JsonObject obj = json.getAsJsonObject(); - ParametersValue.Builder builder = - ParametersValue.make(); - for (Map.Entry entry : obj.entrySet()) - builder.param( - entry.getKey(), - context.deserialize( - entry.getValue(), - ParameterValue.class)); - return builder.get(); - } - -} diff --git a/actions/src/main/java/com/ibm/common/activitystreams/actions/ParametersValue.java b/actions/src/main/java/com/ibm/common/activitystreams/actions/ParametersValue.java deleted file mode 100755 index c11a701..0000000 --- a/actions/src/main/java/com/ibm/common/activitystreams/actions/ParametersValue.java +++ /dev/null @@ -1,134 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.actions; - -import java.io.Serializable; -import java.util.Iterator; -import java.util.Map; - -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import com.ibm.common.activitystreams.util.AbstractWritable; - -/** - * The value of the "parameters" property... - * @author james - * @version $Revision: 1.0 $ - */ -public final class ParametersValue - extends AbstractWritable - implements Serializable, Iterable { - - public static Builder make() { - return new Builder(); - } - - /** - * @author james - * @version $Revision: 1.0 $ - */ - public static final class Builder - extends AbstractWritable.AbstractWritableBuilder - { - - private final Map params = - Maps.newHashMap(); - - public Builder() { - writeUsing(ActionMakers.io); - } - - public boolean notEmpty() { - return !params.isEmpty(); - } - - public Builder param(String param, String iri) { - params.put(param, ActionMakers.parameter(iri)); - return this; - } - - public Builder param( - String param, - ParameterValue parameter) { - params.put(param, parameter); - return this; - } - - public Builder param( - String param, - Supplier parameter) { - params.put(param, parameter); - return this; - } - - public ParametersValue get() { - return new ParametersValue(this); - } - - } - - private final ImmutableMap params; - - /** - * Constructor for ParametersValue. - * @param builder Builder - */ - ParametersValue(Builder builder) { - super(builder); - this.params = ImmutableMap.copyOf(builder.params); - } - - public Iterator iterator() { - return params.keySet().iterator(); - } - - @SuppressWarnings("unchecked") - public O get(String param) { - return (O)params.get(param); - } - - public boolean has(String param) { - return params.containsKey(param); - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - implements Serializable { - private static final long serialVersionUID = -1975376657749952999L; - private ImmutableMap map; - SerializedForm(ParametersValue obj) { - map = obj.params; - } - - Object readResolve() - throws java.io.ObjectStreamException { - ParametersValue.Builder builder = - ParametersValue.make(); - builder.params.putAll(map); - return builder.get(); - } - } -} diff --git a/actions/src/main/java/com/ibm/common/activitystreams/actions/StylesValue.java b/actions/src/main/java/com/ibm/common/activitystreams/actions/StylesValue.java deleted file mode 100755 index 8f42a92..0000000 --- a/actions/src/main/java/com/ibm/common/activitystreams/actions/StylesValue.java +++ /dev/null @@ -1,155 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.actions; - -import static com.google.common.base.Preconditions.checkArgument; - -import java.io.Serializable; -import java.util.Map; - -import com.google.common.collect.ImmutableMap; -import com.ibm.common.activitystreams.util.AbstractDictionaryObject; - -/** - * The value of the "parameters" property... - * @author james - * @version $Revision: 1.0 $ - */ -public final class StylesValue - extends AbstractDictionaryObject - implements Serializable { - - /** - * Method make. - - * @return Builder */ - public static Builder make() { - return new Builder(); - } - - - /** - * @author james - * @version $Revision: 1.0 $ - */ - public static final class Builder - extends AbstractDictionaryObject.AbstractBuilder - { - - public Builder() { - writeUsing(ActionMakers.io); - } - - /** - * Method media. - * @param query String - * @return Builder - */ - public Builder media(String query) { - return super.set("media", query); - } - - /** - * Method set. - - - - * @param name String - * @param value String - * @return Builder */ - public Builder set(String name, String value) { - checkArgument(!name.equalsIgnoreCase("query")); - return super.set(name, value); - } - - /** - * Method get. - - - * @return ParametersValue * @see com.google.common.base.Supplier#get() */ - public StylesValue get() { - return new StylesValue(this); - } - - } - - /** - * Constructor for ParametersValue. - * @param builder Builder - */ - StylesValue(Builder builder) { - super(builder); - } - - /** - * Method media. - * @return String - */ - public String media() { - return getSingle("media"); - } - - /** - * Method get. - * @param key String - * @return String - */ - public String get(String key) { - return super.getSingle(key); - } - - /** - * Method get. - * @param key String - * @param defaultValue String - * @return String - */ - public String get(String key, String defaultValue) { - return super.getSingle(key, defaultValue); - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - implements Serializable { - private static final long serialVersionUID = -1975376657749952999L; - private ImmutableMap map; - SerializedForm(StylesValue obj) { - ImmutableMap.Builder builder = - ImmutableMap.builder(); - for (String key : obj) - builder.put(key, obj.get(key)); - this.map = builder.build(); - } - - Object readResolve() - throws java.io.ObjectStreamException { - StylesValue.Builder builder = - StylesValue.make(); - for (Map.Entry entry : map.entrySet()) - builder.set(entry.getKey(), entry.getValue()); - return builder.get(); - } - } -} diff --git a/actions/src/main/java/com/ibm/common/activitystreams/actions/TypedPayload.java b/actions/src/main/java/com/ibm/common/activitystreams/actions/TypedPayload.java deleted file mode 100755 index d7dd26f..0000000 --- a/actions/src/main/java/com/ibm/common/activitystreams/actions/TypedPayload.java +++ /dev/null @@ -1,181 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.actions; - -import java.io.ObjectStreamException; - -import com.google.common.base.Predicate; -import com.google.common.base.Supplier; -import com.google.common.net.MediaType; -import com.ibm.common.activitystreams.ASObject; -import com.ibm.common.activitystreams.LinkValue; -import com.ibm.common.activitystreams.TypeValue; - -public final class TypedPayload - extends ASObject - implements ParameterValue { - - /** - * Method makeTypedPayload. - * @param mediaType MediaType - * @return Builder - */ - public static Builder makeTypedPayload(MediaType mediaType) { - return new Builder().mediaType(mediaType); - } - - /** - * Method makeTypedPayload. - * @param mediaType String - * @return Builder - */ - public static Builder makeTypedPayload(String mediaType) { - return new Builder().mediaType(mediaType); - } - - public static Builder make() { - return new Builder(); - } - - /** - */ - public static final class Builder - extends ASObject.AbstractBuilder { - - public Builder() { - writeUsing(ActionMakers.io); - objectType("TypedPayload"); - } - - /** - * Method schema. - * @param iri String - * @return Builder - */ - public Builder schema(String iri) { - return schema(LinkValue.SimpleLinkValue.make(iri)); - } - - /** - * Method schema. - * @param lv LinkValue - * @return Builder - */ - public Builder schema(LinkValue lv) { - return link("schema", lv); - } - - /** - * Method schema. - * @param lv Supplier - * @return Builder - */ - public Builder schema(Supplier lv) { - return schema(lv.get()); - } - - /** - * Method type. - * @param iri String - * @return Builder - */ - public Builder type(String iri) { - return type(TypeValue.SimpleTypeValue.make(iri)); - } - - /** - * Method type. - * @param tv TypeValue - * @return Builder - */ - public Builder type(TypeValue tv) { - return set("type", tv); - } - - /** - * Method type. - * @param tv Supplier - * @return Builder - */ - public Builder type(Supplier tv) { - return type(tv.get()); - } - - /** - * Method get. - * @return TypedPayload - * @see com.google.common.base.Supplier#get() - */ - public TypedPayload get() { - return new TypedPayload(this); - } - - } - - /** - * Constructor for TypedPayload. - * @param builder Builder - */ - private TypedPayload(Builder builder) { - super(builder); - } - - /** - * Method schema. - * @return L - */ - public Iterable schema() { - return this.links("schema"); - } - - public Iterable schema(Predicate filter) { - return this.links("schema", filter); - } - - /** - * Method type. - * @return TypeValue - */ - public TypeValue type() { - return this.get("type"); - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936285L; - private String mediaType; - protected SerializedForm(TypedPayload obj) { - super(obj); - this.mediaType = obj.mediaType().toString(); - } - Object readResolve() throws ObjectStreamException { - return super.doReadResolve(); - } - protected TypedPayload.Builder builder() { - return ActionMakers.typedPayload(mediaType); - } - } -} diff --git a/actions/src/main/java/com/ibm/common/activitystreams/actions/UrlTemplate.java b/actions/src/main/java/com/ibm/common/activitystreams/actions/UrlTemplate.java deleted file mode 100755 index 6221109..0000000 --- a/actions/src/main/java/com/ibm/common/activitystreams/actions/UrlTemplate.java +++ /dev/null @@ -1,133 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.actions; - -import java.io.ObjectStreamException; - -import com.google.common.base.Supplier; -import com.ibm.common.activitystreams.ASObject; - -/** - */ -public final class UrlTemplate - extends ASObject - implements ParameterValue { - - /** - * Method makeUrlTemplate. - * @return Builder - */ - public static Builder makeUrlTemplate() { - return new Builder(); - } - - /** - */ - public static final class Builder - extends ASObject.AbstractBuilder { - - private final ParametersValue.Builder params = - ParametersValue.make(); - - public Builder() { - writeUsing(ActionMakers.io); - objectType("UrlTemplate"); - } - - public Builder template(String template) { - set("template", template); - return this; - } - - public Builder parameter(String name, String iri) { - params.param(name, iri); - return this; - } - - public Builder parameter( - String name, - ParameterValue parameter) { - params.param(name, parameter); - return this; - } - - public Builder parameter( - String name, - Supplier parameter) { - return parameter(name, parameter.get()); - } - - /** - * Method get. - * @return UrlTemplate - * @see com.google.common.base.Supplier#get() - */ - public UrlTemplate get() { - if (params.notEmpty()) - set("parameters", params.get()); - return new UrlTemplate(this); - } - - } - - /** - * Constructor for UrlTemplate. - * @param builder Builder - */ - private UrlTemplate(Builder builder) { - super(builder); - } - - /** - * Method parameters. - * @return ParametersValue - */ - public ParametersValue parameters() { - return this.get("parameters"); - } - - /** - * Method template. - * @return String - */ - public String template() { - return this.getString("template"); - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936285L; - protected SerializedForm(UrlTemplate obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return super.doReadResolve(); - } - protected UrlTemplate.Builder builder() { - return ActionMakers.urlTemplate(); - } - } -} diff --git a/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ActionHandler.kt b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ActionHandler.kt new file mode 100644 index 0000000..bcc28ac --- /dev/null +++ b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ActionHandler.kt @@ -0,0 +1,337 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.actions + +import com.google.common.base.Predicate +import com.google.common.base.Supplier +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.LinkValue +import java.io.Serializable + +/** + */ +abstract class ActionHandler + +/** + * Constructor for ActionHandler. + * @param builder Builder + */ +protected constructor(builder: Builder<*, *>) : ASObject(builder), + Serializable { + /** + */ + abstract class Builder?> + : AbstractBuilder() { + private val auth: Authentication.Builder = Authentication.Companion.make() + + init { + writeUsing(ActionMakers.io) + } + + /** + * Method confirm. + * @param on boolean + * @return B + */ + /** + * Method confirm. + * @return B + */ + @JvmOverloads + fun confirm(on: Boolean = true): B { + set("confirm", on) + return this as B + } + + /** + * Method context. + * @param obj ASObject + * @return B + */ + fun context(obj: ASObject?): B { + set("context", obj) + return this as B + } + + /** + * Method context. + * @param obj Supplier + * @return B + */ + fun context(obj: Supplier): B { + return context(obj.get()) + } + + /** + * Method requires. + * @param iri String + * @return B + */ + fun requires(iri: String?, vararg iris: String?): B { + requires(LinkValue.SimpleLinkValue.make(iri)) + if (iris != null) for (i in iris) requires(i) + return this as B + } + + /** + * Method requires. + * @param lv LinkValue + * @return B + */ + fun requires(lv: LinkValue?, vararg lvs: LinkValue?): B { + link("requires", lv) + if (lvs != null) for (i in lvs) requires(i) + return this as B + } + + /** + * Method requires. + * @param lv Supplier + * @return B + */ + fun requires(lv: Supplier): B { + return requires(lv.get()) + } + + /** + * Method prefers. + * @param iri String + * @return B + */ + fun prefers(iri: String?, vararg iris: String?): B { + prefers(LinkValue.SimpleLinkValue.make(iri)) + if (iris != null) for (i in iris) prefers(i) + return this as B + } + + /** + * Method prefers. + * @param lv LinkValue + * @return B + */ + fun prefers(lv: LinkValue?, vararg lvs: LinkValue?): B { + link("prefers", lv) + if (lvs != null) for (l in lvs) prefers(l) + return this as B + } + + /** + * Method prefers. + * @param lv Supplier + * @return B + */ + fun prefers(lv: Supplier): B { + return prefers(lv.get()) + } + + /** + * Method expects. + * @param iri String + * @return B + */ + fun expects(iri: String?, vararg iris: String?): B { + expects(LinkValue.SimpleLinkValue.make(iri)) + if (iris != null) for (i in iris) expects(i) + return this as B + } + + /** + * Method expects. + * @param tv LinkValue + * @return B + */ + fun expects(tv: LinkValue?, vararg lvs: LinkValue?): B { + link("expects", tv) + if (lvs != null) for (lv in lvs) expects(lv) + return this as B + } + + /** + * Method expects. + * @param tv Supplier + * @return B + */ + fun expects(tv: Supplier): B { + return expects(tv.get()) + } + + /** + * Method returns. + * @param iri String + * @return B + */ + fun returns(iri: String?, vararg iris: String?): B { + returns(LinkValue.SimpleLinkValue.make(iri)) + if (iris != null) for (i in iris) returns(i) + return this as B + } + + /** + * Method returns. + * @param tv LinkValue + * @return B + */ + fun returns(tv: LinkValue?, vararg lvs: LinkValue?): B { + link("returns", tv) + if (lvs != null) for (lv in lvs) returns(lv) + return this as B + } + + /** + * Method returns. + * @param tv Supplier + * @return B + */ + fun returns(tv: Supplier): B { + return returns(tv.get()) + } + + /** + * Method auth. + * @param key String + * @param obj ASObject + * @return B + */ + fun auth(key: String, obj: ASObject): B { + auth[key] = obj + return this as B + } + + /** + * Method auth. + * @param key String + * @param obj Supplier + * @return B + */ + fun auth(key: String, obj: Supplier): B { + return auth(key, obj.get()) + } + + /** + * Method get. + * @return A + * @see com.google.common.base.Supplier.get + */ + override fun get(): A { + if (auth.notEmpty()) set("auth", auth.get()) + return actualGet() + } + + /** + * Method actualGet. + * @return A + */ + protected abstract fun actualGet(): A + } + + /** + * Method confirm. + * @return boolean + */ + fun confirm(): Boolean { + return this.getBoolean("confirm") + } + + /** + * Method context. + * @return A + */ + fun context(): A? { + return this.get("context") + } + + /** + * Method expects. + * @return Iterable + */ + fun expects(): Iterable { + return this.links("expects") + } + + fun expects(filter: Predicate): Iterable { + return this.links("expects", filter) + } + + /** + * Method requires. + * @return Iterable + */ + fun requires(): Iterable { + return this.links("requires") + } + + fun requires(filter: Predicate): Iterable { + return this.links("requires", filter) + } + + /** + * Method prefers. + * @return Iterable + */ + fun prefers(): Iterable { + return this.links("prefers") + } + + fun prefers(filter: Predicate): Iterable { + return this.links("prefers", filter) + } + + /** + * Method returns. + * @return Iterable + */ + fun returns(): Iterable { + return this.links("returns") + } + + fun returns(filter: Predicate): Iterable { + return this.links("returns", filter) + } + + /** + * Method auth. + * @return Authentication + */ + fun auth(): Authentication? { + return this.get("auth") + } + + /** + * Method hasAuth. + * @param key String + * @return boolean + */ + fun hasAuth(key: String?): Boolean { + val auth = auth() + return auth?.has(key) ?: false + } + + /** + * Method auth. + * @param key String + * @return A + */ + fun auth(key: String?): A? { + val auth = auth() + return if (auth != null) auth.get(key) as A else null + } +} diff --git a/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ActionMakers.kt b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ActionMakers.kt new file mode 100644 index 0000000..c3eb770 --- /dev/null +++ b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ActionMakers.kt @@ -0,0 +1,250 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.actions + +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.IO +import com.ibm.common.activitystreams.IO.Companion.makeDefault +import com.ibm.common.activitystreams.IO.Companion.makeDefaultPrettyPrint +import com.ibm.common.activitystreams.Makers.`object` +import com.ibm.common.activitystreams.actions.ParameterValue.SimpleParameterValue + +/** + */ +object ActionMakers { + @JvmField + val io: IO = makeDefault(ActionsModule.Companion.instance) + val ioPretty: IO = makeDefaultPrettyPrint(ActionsModule.Companion.instance) + + const val TARGET_NONE: String = "NONE" + const val TARGET_DEFAULT: String = "DEFAULT" + const val TARGET_NEW: String = "NEW" + const val TARGET_CURRENT: String = "CURRENT" + const val TARGET_TAB: String = "TAB" + const val TARGET_DIALOG: String = "DIALOG" + const val TARGET_MODALDIALOG: String = "MODALDIALOG" + const val TARGET_FLOAT: String = "FLOAT" + const val TARGET_SIDEBAR: String = "SIDEBAR" + + const val METHOD_GET: String = "GET" + const val METHOD_POST: String = "POST" + const val METHOD_PUT: String = "PUT" + const val METHOD_DELETE: String = "DELETE" + const val METHOD_PATCH: String = "PATCH" + + /** + * Method application. + * @return ASObject.Builder + */ + fun application(): ASObject.Builder? { + return `object`("application") + } + + /** + * Method service. + * @return ASObject.Builder + */ + fun service(): ASObject.Builder? { + return `object`("service") + } + + /** + * Method styles. + * @return StylesValue.Builder + */ + @JvmStatic + fun styles(): StylesValue.Builder { + return StylesValue.Companion.make() + } + + /** + * Method styles. + * @param media String + * @return StylesValue.Builder + */ + @JvmStatic + fun styles(media: String?): StylesValue.Builder? { + return styles().media(media) + } + + /** + * Method httpAction. + * @return HttpActionHandler.Builder + */ + @JvmStatic + fun httpAction(): HttpActionHandler.Builder { + return HttpActionHandler.Companion.makeHttpActionHandler() + } + + /** + * Method httpAction. + * @param url String + * @return HttpActionHandler.Builder + */ + @JvmStatic + fun httpAction(url: String?): HttpActionHandler.Builder? { + return httpAction().url(url) + } + + /** + * Method httpAction. + * @param url String + * @param method String + * @return HttpActionHandler.Builder + */ + @JvmStatic + fun httpAction( + url: String?, + method: String? + ): HttpActionHandler.Builder? { + return httpAction() + .url(url) + ?.method(method) + } + + /** + * Method embedAction. + * @return EmbedActionHandler.Builder + */ + @JvmStatic + fun embedAction(): EmbedActionHandler.Builder { + return EmbedActionHandler.Companion.makeEmbedActionHandler() + } + + /** + * Method embedAction. + * @param url String + * @return EmbedActionHandler.Builder + */ + @JvmStatic + fun embedAction(url: String?): EmbedActionHandler.Builder? { + return embedAction().url(url) + } + + /** + * Method embedAction. + * @param url String + * @param mediaType String + * @return EmbedActionHandler.Builder + */ + @JvmStatic + fun embedAction( + url: String?, + mediaType: String + ): EmbedActionHandler.Builder? { + return embedAction(url)!!.mediaType(mediaType) + } + + /** + * Method staticEmbedAction. + * @param mediaType String + * @param content String + * @return EmbedActionHandler.Builder + */ + fun staticEmbedAction( + mediaType: String, + content: String? + ): EmbedActionHandler.Builder? { + return embedAction().mediaType(mediaType)!!.content(content) + } + + /** + * Method intentAction. + * @return IntentActionHandler.Builder + */ + @JvmStatic + fun intentAction(): IntentActionHandler.Builder { + return IntentActionHandler.Companion.makeIntentActionHandler() + } + + /** + * Method intentAction. + * @param url String + * @return IntentActionHandler.Builder + */ + @JvmStatic + fun intentAction(url: String?): IntentActionHandler.Builder? { + return intentAction().url(url) + } + + /** + * Method htmlForm. + * @return HtmlForm.Builder + */ + @JvmStatic + fun htmlForm(): HtmlForm.Builder { + return HtmlForm.Companion.makeHtmlForm() + } + + /** + * Method typedPayload. + * @param mediaType String + * @return TypedPayload.Builder + */ + @JvmStatic + fun typedPayload(mediaType: String): TypedPayload.Builder? { + return TypedPayload.Companion.makeTypedPayload(mediaType) + } + + @JvmStatic + fun typedPayload(): TypedPayload.Builder { + return TypedPayload.Companion.make() + } + + /** + * Method urlTemplate. + * @return UrlTemplate.Builder + */ + @JvmStatic + fun urlTemplate(): UrlTemplate.Builder { + return UrlTemplate.Companion.makeUrlTemplate() + } + + /** + * Method urlTemplate. + * @param template String + * @return UrlTemplate.Builder + */ + @JvmStatic + fun urlTemplate(template: String?): UrlTemplate.Builder { + return urlTemplate().template(template) + } + + /** + * Method parameter. + * @return Parameter.Builder + */ + @JvmStatic + fun parameter(): Parameter.Builder { + return Parameter.Companion.makeParameter() + } + + /** + * Method parameter. + * @param id String + * @return Parameter.Builder + */ + @JvmStatic + fun parameter(id: String?): SimpleParameterValue { + return SimpleParameterValue.Builder().type(id).get() + } +} diff --git a/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ActionObjectAdapter.kt b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ActionObjectAdapter.kt new file mode 100644 index 0000000..ae9e631 --- /dev/null +++ b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ActionObjectAdapter.kt @@ -0,0 +1,88 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.actions + +import com.google.common.collect.ImmutableSet +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.i.ASObjectAdapter +import com.ibm.common.activitystreams.i.Model +import com.ibm.common.activitystreams.i.Schema +import java.lang.reflect.Type + +class ActionObjectAdapter +internal constructor(schema: Schema) : ASObjectAdapter(schema) { + override fun knowsType(type: Type?): Boolean { + if (super.knowsType(type)) return true + return knownTypes.contains(type) + } + + override fun builderFor(type: Type): ASObject.AbstractBuilder<*, *>? { + if (super.knowsType(type)) return super.builderFor(type) + return if (type === HttpActionHandler::class.java) ActionMakers.httpAction() + else if (type === IntentActionHandler::class.java) ActionMakers.intentAction() + else if (type === EmbedActionHandler::class.java) ActionMakers.embedAction() + else if (type === HtmlForm::class.java) ActionMakers.htmlForm() + else if (type === UrlTemplate::class.java) ActionMakers.urlTemplate() + else if (type === TypedPayload::class.java) ActionMakers.typedPayload() + else null + } + + override fun modelFor(type: Type): Model? { + if (super.knowsType(type)) return super.modelFor(type) + return if (type === HttpActionHandler::class.java) schema().forObjectClassOrType( + HttpActionHandler.Builder::class.java, + "HttpActionHandler" + ) + else if (type === IntentActionHandler::class.java) schema().forObjectClassOrType( + IntentActionHandler.Builder::class.java, + "IntentActionHandler" + ) + else if (type === EmbedActionHandler::class.java) schema().forObjectClassOrType( + EmbedActionHandler.Builder::class.java, + "EmbedActionHandler" + ) + else if (type === HtmlForm::class.java) schema().forObjectClassOrType( + HtmlForm.Builder::class.java, + "HtmlForm" + ) + else if (type === UrlTemplate::class.java) schema().forObjectClassOrType( + UrlTemplate.Builder::class.java, + "UrlTemplate" + ) + else if (type === TypedPayload::class.java) schema().forObjectClassOrType( + TypedPayload.Builder::class.java, + "TypedPayload" + ) + else null + } + + companion object { + private val knownTypes: ImmutableSet> = ImmutableSet.of( + HttpActionHandler::class.java, + IntentActionHandler::class.java, + EmbedActionHandler::class.java, + HtmlForm::class.java, + UrlTemplate::class.java, + TypedPayload::class.java + ) + } +} diff --git a/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ActionsModule.kt b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ActionsModule.kt new file mode 100644 index 0000000..06e270a --- /dev/null +++ b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ActionsModule.kt @@ -0,0 +1,115 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.actions + +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.IO +import com.ibm.common.activitystreams.i.Model +import com.ibm.common.activitystreams.i.Schema +import com.ibm.common.activitystreams.util.Module + +class ActionsModule + + : Module { + override fun apply(builder: IO.Builder, schema: Schema) { + val base = + ActionObjectAdapter(schema) + + + // Register Adapters + builder.hierarchicalAdapter(ActionHandler::class.java, base) + .hierarchicalAdapter(HttpActionHandler::class.java, base) + .hierarchicalAdapter(IntentActionHandler::class.java, base) + .hierarchicalAdapter(EmbedActionHandler::class.java, base) + .hierarchicalAdapter(HtmlForm::class.java, base) + .hierarchicalAdapter(ParametersValue::class.java, ParametersAdapter.instance) + .hierarchicalAdapter(ParameterValue::class.java, ParameterAdapter.instance) + .hierarchicalAdapter(UrlTemplate::class.java, base) + .hierarchicalAdapter(TypedPayload::class.java, base) + .hierarchicalAdapter(Authentication::class.java, Adapters.AUTH) + .hierarchicalAdapter(StylesValue::class.java, Adapters.STYLES) + } + + override fun apply(builder: Schema.Builder) { + builder.map( + "HtmlForm", withParameters.template( + HtmlForm::class.java, + HtmlForm.Builder::class.java + ) + ) + .map("TypedPayload", typedPayload) + .map( + "UrlTemplate", withParameters.template( + UrlTemplate::class.java, + UrlTemplate.Builder::class.java + ) + ) + .map( + "HttpActionHandler", actionHandler.template( + HttpActionHandler::class.java, + HttpActionHandler.Builder::class.java + ) + ) + .map( + "IntentActionHandler", actionHandler.template( + IntentActionHandler::class.java, + IntentActionHandler.Builder::class.java + ) + ) + .map( + "EmbedActionHandler", actionHandler.template( + EmbedActionHandler::class.java, + EmbedActionHandler.Builder::class.java + ) + ) + } + + companion object { + val instance: Module = ActionsModule() + + val actionHandler: Model = Model + .make("object") + .linkValue( + "expects", + "returns", + "requires", + "prefers" + ) + .`object`("context") + .`as`("auth", Authentication::class.java) + .`as`("style", StylesValue::class.java) + .get() + + + val withParameters: Model = Model + .make("object") + .`as`("parameters", ParametersValue::class.java) + .get() + + val typedPayload: Model = Model + .make("object") + .type(TypedPayload::class.java, TypedPayload.Builder::class.java) + .linkValue("schema") + .typeValue("type") + .get() + } +} diff --git a/actions/src/main/java/com/ibm/common/activitystreams/actions/Adapters.java b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/Adapters.kt similarity index 50% rename from actions/src/main/java/com/ibm/common/activitystreams/actions/Adapters.java rename to actions/src/main/kotlin/com/ibm/common/activitystreams/actions/Adapters.kt index e42ea55..2ac0c64 100644 --- a/actions/src/main/java/com/ibm/common/activitystreams/actions/Adapters.java +++ b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/Adapters.kt @@ -19,37 +19,28 @@ * * @author James M Snell (jasnell@us.ibm.com) */ -package com.ibm.common.activitystreams.actions; +package com.ibm.common.activitystreams.actions -import com.ibm.common.activitystreams.ASObject; -import com.ibm.common.activitystreams.actions.StylesValue.Builder; -import com.ibm.common.activitystreams.internal.Adapter; -import com.ibm.common.activitystreams.util.AbstractDictionaryObjectAdapter; +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.i.Adapter +import com.ibm.common.activitystreams.util.AbstractDictionaryObjectAdapter -final class Adapters { +internal object Adapters { + val AUTH: Adapter = + object : AbstractDictionaryObjectAdapter( + ASObject::class.java + ) { + override fun builder(): Authentication.Builder { + return Authentication.Companion.make() + } + } - private Adapters() {} - - static final Adapter AUTH = - new AbstractDictionaryObjectAdapter - (ASObject.class) { - @Override - protected Authentication.Builder builder() { - return Authentication.make(); - } - }; - - static final Adapter STYLES = - new AbstractDictionaryObjectAdapter - (String.class) { - @Override - protected Builder builder() { - return StylesValue.make(); - } - }; - + val STYLES: Adapter = + object : AbstractDictionaryObjectAdapter( + String::class.java + ) { + override fun builder(): StylesValue.Builder { + return StylesValue.Companion.make() + } + } } diff --git a/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/Authentication.kt b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/Authentication.kt new file mode 100644 index 0000000..62f3131 --- /dev/null +++ b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/Authentication.kt @@ -0,0 +1,107 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.actions + +import com.google.common.collect.ImmutableMap +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.util.AbstractDictionaryObject +import java.io.ObjectStreamException +import java.io.Serializable + +/** + */ +class Authentication + +/** + * Constructor for Authentication. + * @param builder Builder + */ +protected constructor(builder: Builder) : + AbstractDictionaryObject(builder) { + /** + */ + class Builder + + : AbstractBuilder() { + init { + writeUsing(ActionMakers.io) + } + + /** + * Method get. + * @return Authentication + * @see com.google.common.base.Supplier.get + */ + override fun get(): Authentication { + return Authentication(this) + } + } + + /** + * Method get. + * @param key String + * @return A + */ + fun get(key: String?): A? { + return getSingle(key) as A? + } + + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: Authentication) : Serializable { + private val map: ImmutableMap + + init { + val builder = + ImmutableMap.builder() + for (key in obj) builder.put(key, obj.get(key)) + this.map = builder.build() + } + + @Throws(ObjectStreamException::class) + fun readResolve(): Any { + val builder = + make() + for ((key, value) in map) builder[key] = + value as ASObject + return builder.get() + } + + companion object { + private const val serialVersionUID = -1975376657749952999L + } + } + + companion object { + /** + * Method make. + * @return Builder + */ + fun make(): Builder { + return Builder() + } + } +} diff --git a/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/EmbedActionHandler.kt b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/EmbedActionHandler.kt new file mode 100644 index 0000000..20d9c92 --- /dev/null +++ b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/EmbedActionHandler.kt @@ -0,0 +1,218 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.actions + +import com.google.common.base.Preconditions +import com.google.common.base.Predicate +import com.google.common.base.Supplier +import com.google.common.collect.ImmutableList +import com.google.common.collect.Iterables +import java.io.ObjectStreamException +import java.io.Serializable + +/** + */ +class EmbedActionHandler + +/** + * Constructor for EmbedActionHandler. + * @param builder AbstractBuilder + */ +protected constructor(builder: AbstractBuilder<*, *>) : + ActionHandler(builder), Serializable { + /** + */ + class Builder + + : AbstractBuilder("EmbedActionHandler") { + override val actual: EmbedActionHandler + /** + * Method getActual. + * @return EmbedActionHandler + */ + get() = EmbedActionHandler(this) + } + + /** + */ + abstract class AbstractBuilder?> + protected constructor(objectType: String?) : + ActionHandler.Builder() { + private var styleset = false + + /** + * Constructor for AbstractBuilder. + * @param objectType String + */ + init { + objectType(objectType) + } + + /** + * Method target. + * @param target String + * @return B + */ + fun target(target: String?): B { + set("target", target) + return this as B + } + + /** + * Method style. + * @param style StylesValue + * @return B + */ + fun style(style: StylesValue): B { + styleset = true + styles.add(style) + return this as B + } + + /** + * Method style. + * @param style Supplier + * @return B + */ + fun style(style: Supplier): B { + return style(style.get()!!) + } + + /** + * Method style. + * @param styles StylesValue[] + * @return B + */ + fun style(vararg styles: StylesValue): B { + for (s in styles) style(s) + return this as B + } + + /** + * Method style. + * @param styles Supplier[] + * @return B + */ + fun style(vararg styles: Supplier): B { + for (s in styles) style(s) + return this as B + } + + /** + * Method actualGet. + * @return A + */ + override fun actualGet(): A { + if (styleset) { + val `val` = styles.build() + if (Iterables.size(`val`) == 1) { + set("style", Iterables.getFirst(`val`, null)) + } else { + set("style", `val`) + } + } + return actual + } + + /** + * Method getActual. + * @return A + */ + protected abstract val actual: A + + companion object { + private val styles: ImmutableList.Builder = ImmutableList.builder() + } + } + + /** + * Method styles. + * @return Iterable + */ + fun styles(): Iterable { + val styles = get("style") + return if (styles is StylesValue) ImmutableList.of(styles) + else if (styles is Iterable<*>) styles as Iterable + else ImmutableList.of() + } + + /** + * Method styles. + * @param media String + * @return Iterable + */ + fun styles(media: String): Iterable { + Preconditions.checkNotNull(media) + return styles { style -> media.equals(style?.media(), ignoreCase = true) } + } + + /** + * Method styles. + * @param matcher Predicate + * @return Iterable + */ + fun styles(matcher: Predicate): Iterable { + return Iterables.filter(styles(), matcher) + } + + /** + * Method target. + * @return String + */ + fun target(): String? { + return getString( + "target", + ActionMakers.TARGET_DEFAULT + ) + } + + @Throws(ObjectStreamException::class) + override fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: EmbedActionHandler?) : AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + override fun builder(): Builder { + return ActionMakers.embedAction() + } + + companion object { + private const val serialVersionUID = -2060301713159936285L + } + } + + companion object { + /** + * Method makeEmbedActionHandler. + * @return Builder + */ + fun makeEmbedActionHandler(): Builder { + return Builder() + } + } +} diff --git a/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/HtmlForm.kt b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/HtmlForm.kt new file mode 100644 index 0000000..ac8a52a --- /dev/null +++ b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/HtmlForm.kt @@ -0,0 +1,119 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.actions + +import com.google.common.base.Supplier +import com.ibm.common.activitystreams.ASObject +import java.io.ObjectStreamException + +/** + */ +class HtmlForm + +/** + * Constructor for HtmlForm. + * @param builder Builder + */ +private constructor(builder: Builder) : ASObject(builder) { + /** + */ + class Builder + + : AbstractBuilder() { + private val params: ParametersValue.Builder = ParametersValue.Companion.make() + + init { + writeUsing(ActionMakers.io) + objectType("HtmlForm") + mediaType("application/x-www-form-urlencoded") + } + + fun parameter(name: String, iri: String?): Builder { + params.param(name, iri) + return this + } + + fun parameter( + name: String, + parameter: ParameterValue? + ): Builder { + params.param(name, parameter) + return this + } + + fun parameter( + name: String, + parameter: Supplier + ): Builder { + return parameter(name, parameter.get()) + } + + /** + * Method get. + * @return HtmlForm + * @see com.google.common.base.Supplier.get + */ + override fun get(): HtmlForm { + if (params.notEmpty()) set("parameters", params.get()) + return HtmlForm(this) + } + } + + /** + * Method parameters. + * @return ParametersValue + */ + fun parameters(): ParametersValue? { + return this.get("parameters") + } + + @Throws(ObjectStreamException::class) + override fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: HtmlForm?) : AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + override fun builder(): Builder { + return ActionMakers.htmlForm() + } + + companion object { + private const val serialVersionUID = -2060301713159936285L + } + } + + companion object { + /** + * Method makeHtmlForm. + * @return Builder + */ + fun makeHtmlForm(): Builder { + return Builder() + } + } +} diff --git a/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/HttpActionHandler.kt b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/HttpActionHandler.kt new file mode 100644 index 0000000..d5b4d53 --- /dev/null +++ b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/HttpActionHandler.kt @@ -0,0 +1,131 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.actions + +import java.io.ObjectStreamException + +/** + */ +class HttpActionHandler + +/** + * Constructor for HttpActionHandler. + * @param builder AbstractBuilder + */ +protected constructor(builder: AbstractBuilder<*, *>) : + ActionHandler(builder) { + /** + */ + class Builder + + : AbstractBuilder("HttpActionHandler") { + /** + * Method actualGet. + * @return HttpActionHandler + */ + override fun actualGet(): HttpActionHandler { + return HttpActionHandler(this) + } + } + + /** + */ + abstract class AbstractBuilder + ?> + protected constructor(objectType: String?) : + ActionHandler.Builder() { + /** + * Constructor for AbstractBuilder. + * @param objectType String + */ + init { + objectType(objectType) + } + + /** + * Method method. + * @param method String + * @return B + */ + fun method(method: String?): B { + set("method", method) + return this as B + } + + /** + * Method target. + * @param target String + * @return B + */ + fun target(target: String?): B { + set("target", target) + return this as B + } + } + + /** + * Method method. + * @return String + */ + fun method(): String? { + return this.getString("method") + } + + /** + * Method target. + * @return String + */ + fun target(): String? { + return if (has("target")) this.get("target") else ActionMakers.TARGET_DEFAULT + } + + @Throws(ObjectStreamException::class) + override fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: HttpActionHandler?) : AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + override fun builder(): Builder { + return ActionMakers.httpAction() + } + + companion object { + private const val serialVersionUID = -2060301713159936285L + } + } + + companion object { + /** + * Method makeHttpActionHandler. + * @return Builder + */ + fun makeHttpActionHandler(): Builder { + return Builder() + } + } +} diff --git a/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/IntentActionHandler.kt b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/IntentActionHandler.kt new file mode 100644 index 0000000..2ce7b13 --- /dev/null +++ b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/IntentActionHandler.kt @@ -0,0 +1,95 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.actions + +import java.io.ObjectStreamException + +/** + */ +class IntentActionHandler + +/** + * Constructor for IntentActionHandler. + * @param builder AbstractBuilder + */ +protected constructor(builder: AbstractBuilder<*, *>) : + ActionHandler(builder) { + /** + */ + class Builder + + : AbstractBuilder("IntentActionHandler") { + /** + * Method actualGet. + * @return IntentActionHandler + */ + override fun actualGet(): IntentActionHandler { + return IntentActionHandler(this) + } + } + + /** + */ + abstract class AbstractBuilder + ?> + protected constructor(objectType: String?) : + ActionHandler.Builder() { + /** + * Constructor for AbstractBuilder. + * @param objectType String + */ + init { + objectType(objectType) + } + } + + @Throws(ObjectStreamException::class) + override fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: IntentActionHandler?) : AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + override fun builder(): Builder { + return ActionMakers.intentAction() + } + + companion object { + private const val serialVersionUID = -2060301713159936285L + } + } + + companion object { + /** + * Method makeIntentActionHandler. + * @return Builder + */ + fun makeIntentActionHandler(): Builder { + return Builder() + } + } +} diff --git a/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/Parameter.kt b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/Parameter.kt new file mode 100644 index 0000000..933c912 --- /dev/null +++ b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/Parameter.kt @@ -0,0 +1,670 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.actions + +import com.google.common.base.Objects +import com.google.common.base.Supplier +import com.google.common.collect.* +import com.ibm.common.activitystreams.* +import com.ibm.common.activitystreams.Makers.nlv +import com.ibm.common.activitystreams.NLV.MapNLV +import com.ibm.common.activitystreams.NLV.SimpleNLV +import com.ibm.common.activitystreams.util.AbstractWritable +import com.ibm.common.activitystreams.util.Util.DEFAULT_LOCALE +import java.io.ObjectStreamException +import java.io.Serializable +import java.util.regex.Pattern + +class Parameter +protected constructor(builder: Builder) : AbstractWritable(builder), + ParameterValue { + class Builder + + : AbstractWritableBuilder() { + val map: MutableMap = Maps.newHashMap() + + init { + writeUsing(ActionMakers.io) + } + + fun language(lang: String?): Builder { + if (lang != null) map["language"] = lang + else map.remove("language") + return this + } + + protected fun _nlv(key: String, value: String?): Builder { + if (value != null) map[key] = nlv(value) + else map.remove(key) + return this + } + + protected fun _nlv(key: String, nlv: NLV?): Builder { + if (nlv != null) map[key] = nlv + else map.remove(key) + return this + } + + protected fun _nlv(key: String, nlv: Supplier): Builder { + return _nlv(key, nlv.get()) + } + + protected fun _nlv(key: String, map: Map?): Builder { + if (map != null) for ((key1, value) in map) _nlv( + key, + key1, + value + ) + else this.map.remove(key) + return this + } + + protected fun _nlv(key: String, lang: String, value: String?): Builder { + if (map.containsKey(key)) { + val obj = map[key] + if (obj is NLV) { + when (obj.valueType()) { + ValueType.SIMPLE -> { + var l = map["language"] as String? + if (l == null) l = DEFAULT_LOCALE + val b = + nlv() + if (lang == l) b[lang] = value + else b.set(l, (obj as SimpleNLV).value())[lang] = value + map[key] = b + return this + } + + ValueType.OBJECT -> { + map[key] = nlv() + .from(obj as MapNLV, lang) + .set(lang, value) + return this + } + + else -> throw IllegalArgumentException() + } + } else if (obj is MapNLV.Builder) { + obj[lang] = value + return this + } + } + map[key] = nlv().set(lang, value) + return this + } + + fun displayName(`val`: String?): Builder { + return _nlv("displayName", `val`) + } + + fun displayName(nlv: NLV?): Builder { + return _nlv("displayName", nlv) + } + + fun displayName(nlv: Supplier): Builder { + return _nlv("displayName", nlv) + } + + fun displayName(lang: String, `val`: String?): Builder { + return _nlv("displayName", lang, `val`) + } + + fun placeholder(placeholder: String?): Builder { + return _nlv("placeholder", placeholder) + } + + fun placeholder(placeholder: NLV?): Builder { + return _nlv("placeholder", placeholder) + } + + fun placeholder(nlv: Supplier): Builder { + return _nlv("placeholder", nlv) + } + + fun placeholder(lang: String, `val`: String?): Builder { + return _nlv("placeholder", lang, `val`) + } + + fun type(type: String?): Builder { + if (type != null) map["type"] = type + else map.remove("type") + return this + } + + fun required(): Builder { + map.remove("required") + return this + } + + fun optional(): Builder { + map["required"] = false + return this + } + + fun repeated(): Builder { + map["repeated"] = true + return this + } + + fun notRepeated(): Builder { + map.remove("repeated") + return this + } + + fun value(value: Any?): Builder { + if (value != null) map["value"] = value + else map.remove("value") + return this + } + + fun defaultValue(value: Any?): Builder { + if (value != null) map["default"] = value + else map.remove("default") + return this + } + + fun pattern(vararg pattern: Pattern): Builder { + if (pattern != null && pattern.size > 0) { + val patterns = + ImmutableSet.builder() + for (p in pattern) patterns.add(p.pattern()) + map["pattern"] = patterns.build() + } else { + map.remove("pattern") + } + return this + } + + fun pattern(vararg pattern: String): Builder { + if (pattern != null && pattern.size > 0) { + val patterns = + ImmutableSet.copyOf(pattern) + map["pattern"] = patterns + } else { + map.remove("pattern") + } + return this + } + + fun pattern(patterns: Iterable?): Builder { + if (patterns != null && Iterables.size(patterns) > 0) { + map["pattern"] = ImmutableSet.copyOf(patterns) + } else map.remove("pattern") + return this + } + + fun minInclusive(min: Any?): Builder { + if (min != null) map["minInclusive"] = min + else map.remove("minInclusive") + return this + } + + fun minExclusive(min: Any?): Builder { + if (min != null) map["minExclusive"] = min + else map.remove("minExclusive") + return this + } + + fun maxInclusive(max: Any?): Builder { + if (max != null) map["maxInclusive"] = max + else map.remove("maxInclusive") + return this + } + + fun maxExclusive(max: Any?): Builder { + if (max != null) map["maxExclusive"] = max + else map.remove("maxExclusive") + return this + } + + fun bound(range: Range<*>?): Builder { + if (range != null) { + if (range.hasLowerBound()) { + when (range.lowerBoundType()) { + BoundType.CLOSED -> minInclusive(range.lowerEndpoint()) + BoundType.OPEN -> minExclusive(range.lowerEndpoint()) + else -> {} + } + } else { + minInclusive(null) + minExclusive(null) + } + if (range.hasUpperBound()) { + when (range.upperBoundType()) { + BoundType.CLOSED -> maxInclusive(range.upperEndpoint()) + BoundType.OPEN -> maxExclusive(range.upperEndpoint()) + else -> {} + } + } else { + maxInclusive(null) + maxExclusive(null) + } + } + return this + } + + fun step(step: Number?): Builder { + if (step != null) map["step"] = step + else map.remove("step") + return this + } + + fun enumeration(vararg vals: Any): Builder { + if (vals != null && vals.size > 0) map["enumeration"] = + ImmutableList.copyOf(vals) + else map.remove("enumeration") + return this + } + + fun maxLength(length: Int): Builder { + if (length > -1) map["maxLength"] = length + else map.remove("maxLength") + return this + } + + fun minLength(length: Int): Builder { + if (length > -1) map["minLength"] = length + else map.remove("minLength") + return this + } + + fun totalDigits(num: Int): Builder { + if (num > -1) map["totalDigits"] = num + else map.remove("totalDigits") + return this + } + + fun fractionDigits(num: Int): Builder { + if (num > -1) map["fractionDigits"] = num + else map.remove("fractionDigits") + return this + } + + override fun get(): Parameter { + return Parameter(this) + } + } + + private val map: ImmutableMap = + ImmutableMap.copyOf(builder.map) + + /** + * Method required. + * @return boolean + */ + fun required(): Boolean { + return if (!has("required")) true else (map["required"] as Boolean?)!! + } + + /** + * Method repeated. + * @return boolean + */ + fun repeated(): Boolean { + return if (!has("repeated")) false else (map["repeated"] as Boolean?)!! + } + + /** + * Method value. + * @return O + */ + fun value(): O? { + return map["value"] as O? + } + + /** + * Method value. + * @param defaultValue O + * @return O + */ + fun value(defaultValue: O): O { + val `val` = value() + return `val` ?: defaultValue + } + + /** + * Method defaultValue. + * @return O + */ + fun defaultValue(): O? { + return map["default"] as O? + } + + /** + * Method defaultValue. + * @param defaultValue O + * @return O + */ + fun defaultValue(defaultValue: O): O { + val `val` = defaultValue() + return `val` ?: defaultValue + } + + fun type(): String? { + return map["type"] as String? + } + + /** + * Method pattern. + * @return String + */ + fun pattern(): Iterable? { + return map["pattern"] as Iterable? + } + + fun maxInclusive(): O? { + return map["maxInclusive"] as O? + } + + fun maxExclusive(): O? { + return map["maxExclusive"] as O? + } + + fun minInclusive(): O? { + return map["minInclusive"] as O? + } + + fun minExclusive(): O? { + return map["minExclusive"] as O? + } + + fun has(key: String?): Boolean { + return map.containsKey(key) + } + + fun hasUpperBound(): Boolean { + return has("maxInclusive") || has("maxExclusive") + } + + fun ?> bounds(): Range { + val mini: O? = minInclusive() + val mine: O? = minExclusive() + val maxi: O? = maxInclusive() + val maxe: O? = maxExclusive() + val ordering = Ordering.natural() + val min = ordering.nullsLast().min(mini, mine) + val max = ordering.nullsFirst().max(maxi, maxe) + val lower = + if (min == null) null else if (min === mini) BoundType.CLOSED else BoundType.OPEN + val upper = + if (max == null) null else if (max === maxi) BoundType.CLOSED else BoundType.OPEN + return if (lower == null && upper == null) Range.all() + else if (lower != null && upper == null) if (lower === BoundType.CLOSED) Range.atLeast( + min + ) else Range.greaterThan(min) + else if (lower == null && upper != null) if (upper === BoundType.CLOSED) Range.atMost( + max + ) else Range.lessThan(max) + else { + Range.range(min, lower, max, upper) + } + } + + fun step(): N? { + return map["step"] as N? + } + + fun step(defaultValue: N): N { + val n = map["step"] as N? + return n ?: defaultValue + } + + /** + * Method stepInt. + * @return int + */ + fun stepInt(): Int { + return step()!! + } + + /** + * Method stepInt. + * @param defaultValue int + * @return int + */ + fun stepInt(defaultValue: Int): Int { + return step(defaultValue) + } + + /** + * Method stepLong. + * @return long + */ + fun stepLong(): Long { + return step()!! + } + + /** + * Method getLong. + * @param defaultValue long + * @return long + */ + fun stepLong(defaultValue: Long): Long { + return step(defaultValue) + } + + /** + * Method stepShort. + * @return short + */ + fun stepShort(): Short { + return step()!! + } + + /** + * Method stepShort. + * @param defaultValue short + * @return short + */ + fun stepShort(defaultValue: Short): Short { + return step(defaultValue) + } + + /** + * Method stepDouble. + * @return double + */ + fun stepDouble(): Double { + return step()!! + } + + /** + * Method stepDouble. + * @param defaultValue double + * @return double + */ + fun stepDouble(defaultValue: Double): Double { + return step(defaultValue) + } + + /** + * Method stepFloat. + * @return float + */ + fun stepFloat(): Float { + return step()!! + } + + /** + * Method stepFloat. + * @param defaultValue float + * @return float + */ + fun stepFloat(defaultValue: Float): Float { + return step(defaultValue) + } + + /** + * Method enumVals. + * @return Iterable + */ + fun enumeration(): Iterable? { + return if (has("enumeration")) map["enumeration"] as Iterable? + else ImmutableSet.of() + } + + /** + * Method placeholder. + * @return NLV + */ + fun placeholder(): NLV? { + return map["placeholder"] as NLV? + } + + /** + * Method placeholderString. + * @return String + */ + fun placeholderString(): String? { + return _nlv("placeholder") + } + + /** + * Method placeholderString. + * @param lang String + * @return String + */ + fun placeholderString(lang: String?): String? { + return _nlv("placeholder", lang) + } + + fun maxLength(): Int { + val i = map["maxLength"] as Int? + return i ?: -1 + } + + fun minLength(): Int { + val i = map["minLength"] as Int? + return i ?: -1 + } + + fun totalDigits(): Int { + val i = map["totalDigits"] as Int? + return i ?: -1 + } + + fun fractionDigits(): Int { + val i = map["fractionDigits"] as Int? + return i ?: -1 + } + + /** + * Method placeholder. + * @return NLV + */ + fun displayName(): NLV? { + return map["displayName"] as NLV? + } + + /** + * Method placeholderString. + * @return String + */ + fun displayNameString(): String? { + return _nlv("displayName") + } + + /** + * Method placeholderString. + * @param lang String + * @return String + */ + fun displayNameString(lang: String?): String? { + return _nlv("displayName", lang) + } + + fun language(): String? { + return map["language"] as String? + } + + /** + * Method _nlv. + * @param key String + * @return String + */ + protected fun _nlv(key: String?): String? { + val lang = language() + return _nlv(key, lang ?: DEFAULT_LOCALE) + } + + /** + * Method _nlv. + * @param key String + * @param lang String + * @return String + */ + protected fun _nlv(key: String?, lang: String?): String? { + val nlv = + (map[key] as NLV?)!! + when (nlv.valueType()) { + ValueType.SIMPLE -> { + val sim = + nlv as SimpleNLV + val l = language() + return if (l == null || Objects.equal(l, lang)) sim.value() else null + } + + ValueType.OBJECT -> { + val map = + nlv as MapNLV + return map.value(lang) + } + + else -> return null + } + } + + override fun valueType(): ValueType { + return ValueType.OBJECT + } + + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: Parameter) : Serializable { + private val map = obj.map + + @Throws(ObjectStreamException::class) + fun readResolve(): Any { + val builder = Builder() + builder.map.putAll(map) + return builder.get() + } + + companion object { + private const val serialVersionUID = -1975376657749952999L + } + } + + companion object { + /** + * Method makeParameter. + * @return Builder + */ + fun makeParameter(): Builder { + return Builder() + } + } +} diff --git a/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ParameterAdapter.kt b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ParameterAdapter.kt new file mode 100644 index 0000000..27e8bea --- /dev/null +++ b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ParameterAdapter.kt @@ -0,0 +1,231 @@ +package com.ibm.common.activitystreams.actions + +import com.google.common.base.Preconditions +import com.google.common.collect.Iterables +import com.google.gson.* +import com.ibm.common.activitystreams.* +import com.ibm.common.activitystreams.actions.ParameterValue.SimpleParameterValue +import com.ibm.common.activitystreams.i.Adapter +import java.lang.reflect.Type + +class ParameterAdapter + + : Adapter() { + override fun serialize( + src: ParameterValue?, + typeOfSrc: Type, + context: JsonSerializationContext + ): JsonElement? { + if (src == null) return null + when (src.valueType()) { + ValueType.OBJECT -> if (src is Parameter) { + val parameter = src + val obj = JsonObject() + if (parameter.has("type")) { + val type = parameter.type() + if (type != null) obj.addProperty("type", type) + } + if (parameter.has("displayName")) { + val nlv = parameter.displayName() + if (nlv != null) obj.add("displayName", context.serialize(nlv, NLV::class.java)) + } + if (parameter.has("placeholder")) { + val nlv = parameter.placeholder() + if (nlv != null) obj.add("placeholder", context.serialize(nlv, NLV::class.java)) + } + if (parameter.has("enumeration")) { + val e = parameter.enumeration() + if (e != null) obj.add("enumeration", context.serialize(e, e.javaClass)) + } + if (parameter.has("language")) { + val lang = parameter.language() + if (lang != null) obj.addProperty("language", lang) + } + if (parameter.has("maxInclusive")) { + val max = parameter.maxInclusive() + if (max != null) obj.add("maxInclusive", context.serialize(max, max.javaClass)) + } + if (parameter.has("maxExclusive")) { + val max = parameter.maxExclusive() + if (max != null) obj.add("maxExclusive", context.serialize(max, max.javaClass)) + } + if (parameter.has("minInclusive")) { + val max = parameter.minInclusive() + if (max != null) obj.add("minInclusive", context.serialize(max, max.javaClass)) + } + if (parameter.has("minExclusive")) { + val max = parameter.minExclusive() + if (max != null) obj.add("minExclusive", context.serialize(max, max.javaClass)) + } + if (parameter.has("pattern")) { + val pattern = parameter.pattern() + if (pattern != null) { + if (Iterables.size(pattern) == 0) { + val first = Iterables.getFirst(pattern, null) + if (first != null) obj.addProperty("pattern", first) + } else obj.add("pattern", context.serialize(pattern, pattern.javaClass)) + } + } + if (parameter.has("repeated")) { + val repeated = parameter.repeated() + if (repeated) obj.addProperty("repeated", repeated) + } + if (parameter.has("required")) { + val required = parameter.required() + if (!required) obj.addProperty("required", required) + } + if (parameter.has("step")) { + val n = parameter.step() + if (n != null) obj.add("step", context.serialize(n, n.javaClass)) + } + if (parameter.has("default")) { + val def = parameter.defaultValue() + if (def != null) obj.add("default", context.serialize(def, def.javaClass)) + } + if (parameter.has("minLength")) { + val len = parameter.minLength() + if (len > -1) obj.addProperty("minLength", len) + } + if (parameter.has("maxLength")) { + val len = parameter.maxLength() + if (len > -1) obj.addProperty("maxLength", len) + } + if (parameter.has("totalDigits")) { + val len = parameter.totalDigits() + if (len > -1) obj.addProperty("totalDigits", len) + } + if (parameter.has("fractionDigits")) { + val len = parameter.fractionDigits() + if (len > -1) obj.addProperty("fractionDigits", len) + } + if (parameter.has("value")) { + val `val` = parameter.value() + if (`val` != null) obj.add("value", context.serialize(`val`, `val`.javaClass)) + } + return obj + } else if (src is UrlTemplate) { + return context.serialize(src, UrlTemplate::class.java) + } else if (src is TypedPayload) { + return context.serialize(src, TypedPayload::class.java) + } else if (src is ASObject) { + return context.serialize(src, ASObject::class.java) + } else throw IllegalArgumentException() + + ValueType.SIMPLE -> { + val spv = src as SimpleParameterValue + return context.serialize(spv.type(), String::class.java) + } + + else -> throw IllegalArgumentException() + } + } + + private fun deserialize( + context: JsonDeserializationContext, + el: JsonElement + ): Any? { + if (el.isJsonArray) { + return context.deserialize(el, Iterable::class.java) + } else if (el.isJsonObject) { + return context.deserialize(el, ASObject::class.java) + } else if (el.isJsonPrimitive) { + val p = el.asJsonPrimitive + return if (p.isBoolean) p.asBoolean + else if (p.isNumber) p.asNumber + else p.asString + } else return null + } + + @Throws(JsonParseException::class) + override fun deserialize( + json: JsonElement, + typeOfT: Type, + context: JsonDeserializationContext + ): ParameterValue { + Preconditions.checkArgument(json.isJsonPrimitive || json.isJsonObject) + + if (json.isJsonPrimitive) { + val jp = json.asJsonPrimitive + Preconditions.checkArgument(jp.isString) + return ActionMakers.parameter(jp.asString) + } else { + val obj = json.asJsonObject + if (obj.has("objectType")) { + val `as` = context.deserialize(obj, ASObject::class.java) + Preconditions.checkArgument(`as` is ParameterValue) + return `as` as ParameterValue + } else { + val builder = + ActionMakers.parameter() + if (obj.has("default")) builder.defaultValue( + deserialize(context, obj["default"]) + ) + if (obj.has("displayName")) builder.displayName( + context.deserialize( + obj["displayName"], + NLV::class.java + ) + ) + if (obj.has("enumeration")) builder.enumeration( + context.deserialize>( + obj["enumeration"], + Iterable::class.java + ) + ) + if (obj.has("fractionDigits")) builder.fractionDigits( + obj["fractionDigits"].asInt + ) + if (obj.has("language")) builder.language( + obj["language"].asString + ) + if (obj.has("maxExclusive")) builder.maxExclusive( + deserialize(context, obj["maxExclusive"]) + ) + if (obj.has("maxInclusive")) builder.maxInclusive( + deserialize(context, obj["maxInclusive"]) + ) + if (obj.has("minExclusive")) builder.minExclusive( + deserialize(context, obj["minExclusive"]) + ) + if (obj.has("minInclusive")) builder.minInclusive( + deserialize(context, obj["minInclusive"]) + ) + if (obj.has("maxLength")) builder.maxLength( + obj["maxLength"].asInt + ) + if (obj.has("minLength")) builder.minLength( + obj["minLength"].asInt + ) + if (obj.has("pattern")) builder.pattern( + context.deserialize>( + obj["pattern"], Iterable::class.java + ) + ) + if (obj.has("placeholder")) builder.placeholder( + context.deserialize( + obj["placeholder"], NLV::class.java + ) + ) + if (obj.has("repeated") && obj["repeated"].asBoolean) builder.repeated() + if (obj.has("required") && !obj["required"].asBoolean) builder.optional() + if (obj.has("step")) builder.step( + obj["step"].asNumber + ) + if (obj.has("totalDigits")) builder.totalDigits( + obj["totalDigits"].asInt + ) + if (obj.has("type")) builder.type( + obj["type"].asString + ) + if (obj.has("value")) builder.value( + deserialize(context, obj["value"]) + ) + return builder.get() + } + } + } + + companion object { + val instance: ParameterAdapter = ParameterAdapter() + } +} diff --git a/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ParameterValue.kt b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ParameterValue.kt new file mode 100644 index 0000000..6b85866 --- /dev/null +++ b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ParameterValue.kt @@ -0,0 +1,87 @@ +package com.ibm.common.activitystreams.actions + +import com.google.common.base.Objects +import com.ibm.common.activitystreams.* +import com.ibm.common.activitystreams.util.AbstractWritable +import java.io.ObjectStreamException +import java.io.Serializable + +interface ParameterValue + + : Writable, Serializable { + fun valueType(): ValueType + + fun toString(io: IO): String + + class SimpleParameterValue + private constructor(b: Builder) : + AbstractWritable(b), ParameterValue { + internal class Builder + + : AbstractWritableBuilder() { + var type: String? = null + + init { + writeUsing(ActionMakers.io) + } + + fun type(type: String?): Builder { + this.type = type + return this + } + + override fun get(): SimpleParameterValue { + return SimpleParameterValue(this) + } + } + + private val type: String? + + init { + this.type = b.type + } + + override fun valueType(): ValueType { + return ValueType.SIMPLE + } + + fun type(): String? { + return type + } + + override fun hashCode(): Int { + return Objects.hashCode(type) + } + + override fun equals(obj: Any?): Boolean { + if (this === obj) return true + if (obj == null) return false + if (javaClass != obj.javaClass) return false + val other = obj as SimpleParameterValue + return Objects.equal(type, other.type) + } + + override fun toString(io: IO): String { + return super.toString(io) + } + + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: SimpleParameterValue) : Serializable { + private val type = obj.type + + @Throws(ObjectStreamException::class) + fun readResolve(): Any { + return Builder().type(type).get() + } + + companion object { + private const val serialVersionUID = -1975376657749952999L + } + } + } +} diff --git a/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ParametersAdapter.kt b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ParametersAdapter.kt new file mode 100644 index 0000000..83d7b3c --- /dev/null +++ b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ParametersAdapter.kt @@ -0,0 +1,53 @@ +package com.ibm.common.activitystreams.actions + +import com.google.common.base.Preconditions +import com.google.gson.* +import com.ibm.common.activitystreams.i.Adapter +import java.lang.reflect.Type + +class ParametersAdapter + + : Adapter() { + override fun serialize( + params: ParametersValue?, + type: Type, + context: JsonSerializationContext + ): JsonElement? { + if (params == null) return null + val obj = JsonObject() + for (param in params) { + obj.add( + param, + context.serialize( + params.get(param), + ParameterValue::class.java + ) + ) + } + return obj + } + + @Throws(JsonParseException::class) + override fun deserialize( + json: JsonElement, + type: Type, + context: JsonDeserializationContext + ): ParametersValue { + Preconditions.checkArgument(json.isJsonObject) + val obj = json.asJsonObject + val builder: ParametersValue.Builder = + ParametersValue.Companion.make() + for ((key, value) in obj.entrySet()) builder.param( + key, + context.deserialize( + value, + ParameterValue::class.java + ) + ) + return builder.get() + } + + companion object { + val instance: ParametersAdapter = ParametersAdapter() + } +} diff --git a/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ParametersValue.kt b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ParametersValue.kt new file mode 100644 index 0000000..32aab55 --- /dev/null +++ b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/ParametersValue.kt @@ -0,0 +1,124 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.actions + +import com.google.common.base.Supplier +import com.google.common.collect.ImmutableMap +import com.google.common.collect.Maps +import com.ibm.common.activitystreams.util.AbstractWritable +import java.io.ObjectStreamException +import java.io.Serializable + +/** + * The value of the "parameters" property... + * @author james + * @version $Revision: 1.0 $ + */ +class ParametersValue +internal constructor(builder: Builder) : AbstractWritable(builder), + Serializable, Iterable { + /** + * @author james + * @version $Revision: 1.0 $ + */ + class Builder + + : AbstractWritableBuilder() { + val params: MutableMap = Maps.newHashMap() + + init { + writeUsing(ActionMakers.io) + } + + fun notEmpty(): Boolean { + return !params.isEmpty() + } + + fun param(param: String, iri: String?): Builder { + params[param] = ActionMakers.parameter(iri) + return this + } + + fun param( + param: String, + parameter: ParameterValue? + ): Builder { + params[param] = parameter + return this + } + + fun param( + param: String, + parameter: Supplier? + ): Builder { + params[param] = parameter + return this + } + + override fun get(): ParametersValue { + return ParametersValue(this) + } + } + + private val params: ImmutableMap = + ImmutableMap.copyOf(builder.params) + + override fun iterator(): MutableIterator { + return params.keys.iterator() + } + + fun get(param: String?): O? { + return params[param] as O? + } + + fun has(param: String?): Boolean { + return params.containsKey(param) + } + + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: ParametersValue) : Serializable { + private val map = obj.params + + @Throws(ObjectStreamException::class) + fun readResolve(): Any { + val builder = + make() + builder.params.putAll(map) + return builder.get() + } + + companion object { + private const val serialVersionUID = -1975376657749952999L + } + } + + companion object { + fun make(): Builder { + return Builder() + } + } +} diff --git a/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/StylesValue.kt b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/StylesValue.kt new file mode 100644 index 0000000..96b80ea --- /dev/null +++ b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/StylesValue.kt @@ -0,0 +1,155 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.actions + +import com.google.common.base.Preconditions +import com.google.common.collect.ImmutableMap +import com.ibm.common.activitystreams.util.AbstractDictionaryObject +import java.io.ObjectStreamException +import java.io.Serializable + +/** + * The value of the "parameters" property... + * @author james + * @version $Revision: 1.0 $ + */ +class StylesValue + +/** + * Constructor for ParametersValue. + * @param builder Builder + */ +internal constructor(builder: Builder) : + AbstractDictionaryObject(builder), Serializable { + /** + * @author james + * @version $Revision: 1.0 $ + */ + class Builder + + : AbstractBuilder() { + init { + writeUsing(ActionMakers.io) + } + + /** + * Method media. + * @param query String + * @return Builder + */ + fun media(query: String?): Builder { + return super.set("media", query)!! + } + + /** + * Method set. + * + * + * + * @param name String + * @param value String + * @return Builder + */ + override fun set(name: String, value: String?): Builder { + Preconditions.checkArgument(!name.equals("query", ignoreCase = true)) + return super.set(name, value)!! + } + + /** + * Method get. + * + * + * @return ParametersValue * @see com.google.common.base.Supplier#get() + */ + override fun get(): StylesValue { + return StylesValue(this) + } + } + + /** + * Method media. + * @return String + */ + fun media(): String? { + return getSingle("media") + } + + /** + * Method get. + * @param key String + * @return String + */ + fun get(key: String?): String? { + return super.getSingle(key) + } + + /** + * Method get. + * @param key String + * @param defaultValue String + * @return String + */ + fun get(key: String?, defaultValue: String): String { + return super.getSingle(key, defaultValue) + } + + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: StylesValue) : Serializable { + private val map: ImmutableMap + + init { + val builder = + ImmutableMap.builder() + for (key in obj) builder.put(key, obj.get(key)) + this.map = builder.build() + } + + @Throws(ObjectStreamException::class) + fun readResolve(): Any { + val builder = + make() + for ((key, value) in map) builder[key] = + value + return builder.get() + } + + companion object { + private const val serialVersionUID = -1975376657749952999L + } + } + + companion object { + /** + * Method make. + * + * @return Builder + */ + fun make(): Builder { + return Builder() + } + } +} diff --git a/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/TypedPayload.kt b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/TypedPayload.kt new file mode 100644 index 0000000..411bbae --- /dev/null +++ b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/TypedPayload.kt @@ -0,0 +1,180 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.actions + +import com.google.common.base.Predicate +import com.google.common.base.Supplier +import com.google.common.net.MediaType +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.LinkValue +import com.ibm.common.activitystreams.TypeValue +import java.io.ObjectStreamException + +class TypedPayload + +/** + * Constructor for TypedPayload. + * @param builder Builder + */ +private constructor(builder: Builder) : ASObject(builder), + ParameterValue { + /** + */ + class Builder + + : AbstractBuilder() { + init { + writeUsing(ActionMakers.io) + objectType("TypedPayload") + } + + /** + * Method schema. + * @param iri String + * @return Builder + */ + fun schema(iri: String?): Builder? { + return schema(LinkValue.SimpleLinkValue.make(iri)) + } + + /** + * Method schema. + * @param lv LinkValue + * @return Builder + */ + fun schema(lv: LinkValue?): Builder? { + return link("schema", lv) + } + + /** + * Method schema. + * @param lv Supplier + * @return Builder + */ + fun schema(lv: Supplier): Builder? { + return schema(lv.get()) + } + + /** + * Method type. + * @param iri String + * @return Builder + */ + fun type(iri: String?): Builder? { + return type(TypeValue.SimpleTypeValue.make(iri)) + } + + /** + * Method type. + * @param tv TypeValue + * @return Builder + */ + fun type(tv: TypeValue?): Builder? { + return set("type", tv) + } + + /** + * Method type. + * @param tv Supplier + * @return Builder + */ + fun type(tv: Supplier): Builder? { + return type(tv.get()) + } + + /** + * Method get. + * @return TypedPayload + * @see com.google.common.base.Supplier.get + */ + override fun get(): TypedPayload { + return TypedPayload(this) + } + } + + /** + * Method schema. + * @return L + */ + fun schema(): Iterable { + return this.links("schema") + } + + fun schema(filter: Predicate): Iterable { + return this.links("schema", filter) + } + + /** + * Method type. + * @return TypeValue + */ + fun type(): TypeValue? { + return this.get("type") + } + + @Throws(ObjectStreamException::class) + override fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: TypedPayload) : AbstractSerializedForm(obj) { + private val mediaType = obj.mediaType().toString() + + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + override fun builder(): Builder { + return ActionMakers.typedPayload(mediaType)!! + } + + companion object { + private const val serialVersionUID = -2060301713159936285L + } + } + + companion object { + /** + * Method makeTypedPayload. + * @param mediaType MediaType + * @return Builder + */ + fun makeTypedPayload(mediaType: MediaType?): Builder? { + return Builder().mediaType(mediaType) + } + + /** + * Method makeTypedPayload. + * @param mediaType String + * @return Builder + */ + fun makeTypedPayload(mediaType: String): Builder? { + return Builder().mediaType(mediaType) + } + + fun make(): Builder { + return Builder() + } + } +} diff --git a/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/UrlTemplate.kt b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/UrlTemplate.kt new file mode 100644 index 0000000..8ec96b1 --- /dev/null +++ b/actions/src/main/kotlin/com/ibm/common/activitystreams/actions/UrlTemplate.kt @@ -0,0 +1,132 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.actions + +import com.google.common.base.Supplier +import com.ibm.common.activitystreams.ASObject +import java.io.ObjectStreamException + +/** + */ +class UrlTemplate + +/** + * Constructor for UrlTemplate. + * @param builder Builder + */ +private constructor(builder: Builder) : ASObject(builder), + ParameterValue { + /** + */ + class Builder + + : AbstractBuilder() { + private val params: ParametersValue.Builder = ParametersValue.Companion.make() + + init { + writeUsing(ActionMakers.io) + objectType("UrlTemplate") + } + + fun template(template: String?): Builder { + set("template", template) + return this + } + + fun parameter(name: String, iri: String?): Builder { + params.param(name, iri) + return this + } + + fun parameter( + name: String, + parameter: ParameterValue? + ): Builder { + params.param(name, parameter) + return this + } + + fun parameter( + name: String, + parameter: Supplier + ): Builder { + return parameter(name, parameter.get()) + } + + /** + * Method get. + * @return UrlTemplate + * @see com.google.common.base.Supplier.get + */ + override fun get(): UrlTemplate { + if (params.notEmpty()) set("parameters", params.get()) + return UrlTemplate(this) + } + } + + /** + * Method parameters. + * @return ParametersValue + */ + fun parameters(): ParametersValue? { + return this.get("parameters") + } + + /** + * Method template. + * @return String + */ + fun template(): String? { + return this.getString("template") + } + + @Throws(ObjectStreamException::class) + override fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: UrlTemplate?) : AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + override fun builder(): Builder { + return ActionMakers.urlTemplate() + } + + companion object { + private const val serialVersionUID = -2060301713159936285L + } + } + + companion object { + /** + * Method makeUrlTemplate. + * @return Builder + */ + fun makeUrlTemplate(): Builder { + return Builder() + } + } +} diff --git a/assembly/assembly.xml b/assembly/assembly.xml deleted file mode 100644 index 9b35761..0000000 --- a/assembly/assembly.xml +++ /dev/null @@ -1,17 +0,0 @@ - - bin - - tar.gz - zip - - false - - - - - * - - false - - - \ No newline at end of file diff --git a/assembly/pom.xml b/assembly/pom.xml deleted file mode 100644 index 846818f..0000000 --- a/assembly/pom.xml +++ /dev/null @@ -1,49 +0,0 @@ - - 4.0.0 - - com.ibm.common - activitystreams - 0.0.1-SNAPSHOT - - assembly - Activity Streams 2.0 - Assembly - pom - - - com.ibm.common - activitystreams-core - 0.0.1-SNAPSHOT - - - com.ibm.common - activitystreams-actions - 0.0.1-SNAPSHOT - - - com.ibm.common - activitystreams-geo - 0.0.1-SNAPSHOT - - - com.ibm.common - activitystreams-legacy - 0.0.1-SNAPSHOT - - - - - - - org.apache.maven.plugins - maven-assembly-plugin - 2.2.2 - - - assembly.xml - - - - - - - \ No newline at end of file diff --git a/core/build.gradle.kts b/core/build.gradle.kts new file mode 100644 index 0000000..cedf434 --- /dev/null +++ b/core/build.gradle.kts @@ -0,0 +1,26 @@ +/* + * This file was generated by the Gradle 'init' task. + */ + +plugins { + kotlin("jvm") version "2.0.21" +} + +dependencies { + api(libs.com.google.code.gson.gson) + api(libs.com.google.guava.guava) + api(libs.joda.time.joda.time) + testImplementation(libs.junit.junit) + implementation(kotlin("stdlib-jdk8")) +} + +description = "Activity Streams 2.0 - Core" +repositories { + mavenCentral() +} +kotlin { + jvmToolchain(11) +} +tasks.test { + useJUnit() +} \ No newline at end of file diff --git a/core/pom.xml b/core/pom.xml deleted file mode 100755 index 3866b60..0000000 --- a/core/pom.xml +++ /dev/null @@ -1,131 +0,0 @@ - - - - com.ibm.common - activitystreams - 0.0.1-SNAPSHOT - - - 4.0.0 - activitystreams-core - jar - - Activity Streams 2.0 - Core - http://github.org/opensocial/activitystreams - - - - Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - UTF-8 - - - - - com.google.code.gson - gson - - - com.google.guava - guava - - - joda-time - joda-time - - - - junit - junit - test - - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9.1 - - UTF-8 - UTF-8 - UTF-8 - -XDignore.symbol.file - public - - http://www.joda.org/joda-time/apidocs - http://docs.guava-libraries.googlecode.com/git-history/v16.0.1/javadoc/ - - - - - - maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - - - - - maven-jar-plugin - 2.3.1 - - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - - - - - org.apache.felix - maven-bundle-plugin - 2.3.7 - true - - - bundle-manifest - process-classes - - manifest - - - - - - com.ibm.common.activitystreams.* - - com.google.gson.*, - com.google.common.*, - org.joda.time.* - - - - - - - org.apache.maven.plugins - maven-assembly-plugin - 2.2.2 - - - assembly.xml - - - - - - - - - diff --git a/core/src/main/java/com/ibm/common/activitystreams/ASObject.java b/core/src/main/java/com/ibm/common/activitystreams/ASObject.java deleted file mode 100755 index 005bf07..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/ASObject.java +++ /dev/null @@ -1,2647 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams; - -import static com.google.common.base.Enums.getIfPresent; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.base.Throwables.propagate; -import static com.google.common.collect.ImmutableList.of; -import static com.google.common.collect.Iterables.filter; -import static com.google.common.collect.Iterables.getFirst; -import static com.google.common.collect.Maps.difference; -import static com.google.common.collect.Maps.newLinkedHashMap; -import static com.google.common.net.MediaType.parse; -import static com.ibm.common.activitystreams.Makers.linkValue; -import static com.ibm.common.activitystreams.Makers.linkValues; -import static com.ibm.common.activitystreams.Makers.nlv; -import static com.ibm.common.activitystreams.Makers.type; -import static com.ibm.common.activitystreams.util.Converters.toBoolean; -import static com.ibm.common.activitystreams.util.Converters.toDateTime; -import static com.ibm.common.activitystreams.util.Converters.toDouble; -import static com.ibm.common.activitystreams.util.Converters.toDuration; -import static com.ibm.common.activitystreams.util.Converters.toFloat; -import static com.ibm.common.activitystreams.util.Converters.toInt; -import static com.ibm.common.activitystreams.util.Converters.toInterval; -import static com.ibm.common.activitystreams.util.Converters.toLong; -import static com.ibm.common.activitystreams.util.Converters.toPeriod; -import static com.ibm.common.activitystreams.util.Converters.toShort; -import static com.ibm.common.activitystreams.util.Util.DEFAULT_LOCALE; -import static java.lang.Math.ceil; -import static java.lang.Math.floor; -import static org.joda.time.DateTimeZone.UTC; -import static org.joda.time.Duration.standardSeconds; - -import java.io.ObjectStreamException; -import java.io.Serializable; -import java.util.Iterator; -import java.util.Map; -import java.util.concurrent.Callable; -import java.util.concurrent.TimeUnit; - -import org.joda.time.DateTime; -import org.joda.time.Duration; -import org.joda.time.Interval; -import org.joda.time.Period; -import org.joda.time.ReadableDuration; -import org.joda.time.ReadablePeriod; - -import com.google.common.base.Converter; -import com.google.common.base.Function; -import com.google.common.base.Objects; -import com.google.common.base.Optional; -import com.google.common.base.Predicate; -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import com.google.common.net.MediaType; -import com.ibm.common.activitystreams.NLV.MapNLV; -import com.ibm.common.activitystreams.NLV.SimpleNLV; -import com.ibm.common.activitystreams.util.AbstractWritable; - -/** - * The Base for all Activity Streams objects. - * - *

Creating an object:

- *
- *   import static com.ibm.common.activitystreams.Makers.object;
- * 
- *   ASObject obj = object()
- *     .id("urn:example:object:1")
- *     .displayName("My Note")
- *     .objectType("note")
- *     .content("en", "This is my note in english")
- *     .get();
- * 
- * @author james - * @version $Revision: 1.0 $ - */ -@SuppressWarnings("unchecked") -public class ASObject - extends AbstractWritable - implements Iterable, LinkValue, TypeValue, Serializable { - - /** - * Builder for concrete ASObject instances - */ - public static class Builder - extends AbstractBuilder { - /** - * Returns the built ASObject instance - * @return ASObject - * @see com.google.common.base.Supplier#get() - **/ - public ASObject get() { - return new ASObject(this); - } - } - - /** - * Verifies that the rating value is within the proper range - * @param d double - * @return double - **/ - private static double checkRating(double d) { - checkArgument(floor(d) >= 1 && ceil(d) <= 5); - return d; - } - - /** - * Verifies that the value is non-negative - * @param i int - * @return int - **/ - private static int checkNotNegative(int i) { - checkArgument(i >= 0); - return i; - } - - /** - * Method checkNotNegative. - * @param l long - * @return long - */ - private static long checkNotNegative(long l) { - checkArgument(l >= 0); - return l; - } - - /** - * Abstract base builder for ASObject instances. - */ - public static abstract class AbstractBuilder -
> - extends AbstractWritable.AbstractWritableBuilder - implements Supplier, Writable { - - private final Map map = - newLinkedHashMap(); - private final ActionsValue.Builder actions = - Makers.actions(); - - /** - * Method _dt. - * @param key String - * @param dt DateTime - * @return B - **/ - protected B _dt(String key, DateTime dt) { - return set(key, dt); - } - - /** - * Method _dt. - * @param key String - * @param dt String - * @return B - **/ - protected B _dt(String key, String dt) { - return _dt(key, DateTime.parse(dt)); - } - - /** - * Method _dtNow. - * @param key String - * @return B - **/ - protected B _dtNow(String key) { - return _dt(key, DateTime.now(UTC)); - } - - /** - * Method _dtFromNow. - * @param key String - * @param duration Duration - * @return B - **/ - protected B _dtFromNow(String key, ReadableDuration duration) { - return _dt(key, DateTime.now(UTC).plus(duration)); - } - - /** - * Method _dtFromNow. - * @param key String - * @param period ReadablePeriod - * @return B - **/ - protected B _dtFromNow(String key, ReadablePeriod period) { - return _dt(key, DateTime.now(UTC).plus(period)); - } - - /** - * Method _dtFromNow. - * @param key String - * @param v long - * @param unit TimeUnit - * @return B - **/ - protected B _dtFromNow(String key, long v, TimeUnit unit) { - return _dtFromNow(key, toDuration(v,unit)); - } - - /** - * Method _dtFrom. - * @param key String - * @param dt DateTime - * @param duration Duration - * @return B - **/ - protected B _dtFrom(String key, DateTime dt, ReadableDuration duration) { - return _dt(key, dt.plus(duration)); - } - - /** - * Method _dtFrom. - * @param key String - * @param dt DateTime - * @param period ReadablePeriod - * @return B - */ - protected B _dtFrom(String key, DateTime dt, ReadablePeriod period) { - return _dt(key, dt.plus(period)); - } - - /** - * Method _dtFrom. - * @param key String - * @param dt DateTime - * @param v long - * @param unit TimeUnit - * @return B - **/ - protected B _dtFrom(String key, DateTime dt, long v, TimeUnit unit) { - return _dtFrom(key, dt, toDuration(v,unit)); - } - - /** - * Set the published timestamp - * @param dt DateTime - * @return B - **/ - public B published(DateTime dt) { - return _dt("published", dt); - } - - /** - * Set the published timestamp equal to the current time - * @return B - **/ - public B publishedNow() { - return _dtNow("published"); - } - - /** - * Set the published timestamp as a given duration from the current time. - * For instance: - *
-     * // Published one day ago
-     * ASObject obj = Makers.object()
-     *   .publishedFromNow(Duration.standardDays(-1))
-     *   .get();
-     * 
-     * @param duration Duration
-     * @return B 
-     **/
-    public B publishedFromNow(ReadableDuration duration) {
-      return _dtFromNow("published", duration);
-    }
-    
-    /**
-     * Set the published timestamp as a given period of time from the current time
-     * 
-     * // Published one day ago
-     * ASObject obj = Makers.object()
-     *   .publishedFromNow(Period.days(-1))
-     *   .get();
-     * 
-     * @param period ReadablePeriod
-     * @return B 
-     **/
-    public B publishedFromNow(ReadablePeriod period) {
-      return _dtFromNow("published", period);
-    }
-    
-    /**
-     * Set the published timestamp as a given period of time from the current time
-     * @param v long
-     * @param unit TimeUnit
-     * @return B 
-     **/
-    public B publishedFromNow(long v, TimeUnit unit) {
-      return _dtFromNow("published", v, unit);
-    }
-    
-    /**
-     * Set the updated timestamp
-     * @param dt DateTime
-     * @return B 
-     **/
-    public B updated(DateTime dt) {
-      return _dt("updated", dt);
-    }
-    
-    /**
-     * Set the updated timestamp equal to the current time
-     * @return B 
-     **/
-    public B updatedNow() {
-      return _dtNow("updated");
-    }
-    
-    /**
-     * Set the updated timestamp as a given duration from the current time.
-     * For instance:
-     * 
-     * // Published one day ago
-     * ASObject obj = Makers.object()
-     *   .updatedFromNow(Duration.standardDays(-1))
-     *   .get();
-     * 
-     * @param duration Duration
-     * @return B
-     **/
-    public B updatedFromNow(ReadableDuration duration) {
-      return _dtFromNow("updated", duration);
-    }
-    
-    /**
-     * Set the updated timestamp as a given period from the current time.
-     * For instance:
-     * 
-     * // Published one day ago
-     * ASObject obj = Makers.object()
-     *   .updatedFromNow(Period.days(-1))
-     *   .get();
-     * 
-     * @param period ReadablePeriod
-     * @return B
-     **/
-    public B updatedFromNow(ReadablePeriod period) {
-      return _dtFromNow("updated", period);
-    }
-    
-    /**
-     * Set the updated timestamp as a given period from the current time
-     * @param v long
-     * @param unit TimeUnit
-     * @return B 
-     **/
-    public B updatedFromNow(long v, TimeUnit unit) {
-      return _dtFromNow("updated", v, unit);
-    }
-    
-    /**
-     * Set the start time
-     * @param dt DateTime
-     * @return B 
-     **/
-    public B startTime(DateTime dt) {
-      return _dt("startTime", dt);
-    }
-    
-    /**
-     * Set the startTime timestamp as a given duration from the current time.
-     * For instance:
-     * 
-     * // Published one day ago
-     * ASObject obj = Makers.object()
-     *   .startTimeFromNow(Duration.standardDays(-1))
-     *   .get();
-     * 
-     * @param duration Duration
-     * @return B 
-     **/
-    public B startTimeFromNow(ReadableDuration duration) {
-      return _dtFromNow("startTime", duration);
-    }
-    
-    /**
-     * Set the startTime timestamp as a given period from the current time.
-     * For instance:
-     * 
-     * // Published one day ago
-     * ASObject obj = Makers.object()
-     *   .startTimeFromNow(Period.days(-1))
-     *   .get();
-     * 
-     * @param period ReadablePeriod
-     * @return B 
-     **/
-    public B startTimeFromNow(ReadablePeriod period) {
-      return _dtFromNow("startTime", period);
-    }
-    
-    /**
-     * Set the startTime timestamp as a given period from the current time.
-     * @param v long
-     * @param unit TimeUnit
-     * @return B 
-     **/
-    public B startTimeFromNow(long v, TimeUnit unit) {
-      return _dtFromNow("startTime", v, unit);
-    }
-    
-    /**
-     * Set the start time to the current time
-     * @return B 
-     **/
-    public B startTimeNow() {
-      return _dtNow("startTime");
-    }
-    
-    /**
-     * Set the end time
-     * @param dt DateTime
-     * @return B
-     **/
-    public B endTime(DateTime dt) {
-      return _dt("endTime", dt);
-    }
-    
-    /**
-     * Set the endTime timestamp as a given duration from the current time.
-     * For instance:
-     * 
-     * // Published one day ago
-     * ASObject obj = Makers.object()
-     *   .startTimeFromNow(Duration.standardDays(-1))
-     *   .get();
-     * 
-     * @param duration Duration
-     * @return B 
-     **/
-    public B endTimeFromNow(ReadableDuration duration) {
-      return _dtFromNow("endTime", duration);
-    }
-    
-    /**
-     * Set the endTime timestamp as a given period from the current time.
-     * For instance:
-     * 
-     * // Published one day ago
-     * ASObject obj = Makers.object()
-     *   .startTimeFromNow(Period.days(-1))
-     *   .get();
-     * 
-     * @param period ReadablePeriod
-     * @return B
-     **/
-    public B endTimeFromNow(ReadablePeriod period) {
-      return _dtFromNow("endTime", period);
-    }
-    
-    /**
-     * Set the endTime timestamp as a given period from the current time
-     * @param v long
-     * @param unit TimeUnit
-     * @return B 
-     **/
-    public B endTimeFromNow(long v, TimeUnit unit) {
-      return _dtFromNow("endTime", v, unit);
-    }
-    
-    /**
-     * Set the end time 
-     * @return B
-     **/
-    public B endTimeNow() {
-      return _dtNow("endTimeNow");
-    }
-    
-    /**
-     * Set the rating as a value in the range 0.00-1.00;
-     * @param d double
-     * @return B 
-     * @throws IllegalArgumentException if the value is not 
-     *         within the proper range 
-     **/
-    public B rating(double d) {
-      return set("rating", checkRating(d));
-    }
-    
-    /**
-     * Set the duration
-     * @param s int
-     * @return B 
-     * @throws IllegalArgumentException if the value 
-     *         is less than zero 
-     **/
-    public B duration(long s) {
-      return duration(standardSeconds(checkNotNegative(s)));
-    }
-    
-    /**
-     * Set the duration as a Joda-Time Duration
-     * @param d Duration
-     * @return B 
-     **/
-    public B duration(ReadableDuration d) {
-      return set("duration", d);
-    }
-    
-    /**
-     * Set the duration as a Joda-Time Period
-     * @param period ReadablePeriod
-     * @return B
-     */
-    public B duration(ReadablePeriod period) {
-      return duration(period.toPeriod().toStandardDuration());
-    }
-    
-    /**
-     * Set the duration
-     * @param v long
-     * @param unit TimeUnit
-     * @return B 
-     **/
-    public B duration(long v, TimeUnit unit) {
-      return duration(toDuration(v,unit));
-    }
-    
-    /**
-     * Set the duration as a given period of time from the given reference
-     * @param p ReadablePeriod
-     * @param dt DateTime
-     * @return B
-     */
-    public B durationFrom(ReadablePeriod p, DateTime dt) {
-      return duration(p.toPeriod().toDurationFrom(dt));
-    }
-    
-    /**
-     * Set the duration as a given period of time from the current time
-     * @param p ReadablePeriod
-     * @return B
-     */
-    public B durationFromNow(ReadablePeriod p) {
-      return duration(p.toPeriod().toDurationFrom(DateTime.now(UTC)));
-    }
-    
-    /**
-     * Set the height of the object in terms of number of device-independent
-     * pixels.
-     * @param h int
-     * @return B 
-     **/
-    public B height(int h) {
-      return set("height", checkNotNegative(h));
-    }
-    
-    /**
-     * Set the width of the object in terms of number of device-independent
-     * pixels.
-     * @param h int
-     * @return B 
-     **/
-    public B width(int h) {
-      return set("width", checkNotNegative(h));
-    }
-    
-    /**
-     * Set the MIME Media Type of the object
-     * @param mt String
-     * @return B 
-     **/
-    public B mediaType(String mt) {
-      return mediaType(parse(mt));
-    }
-    
-    /**
-     * Set the MIME Media Type of the object
-     * @param mt com.google.common.net.MediaType
-     * @return B 
-     **/
-    public B mediaType(MediaType mt) {
-      return set("mediaType", mt);
-    }
-    
-    /**
-     * Set the link relation
-     * @param rel String
-     * @return B 
-     **/
-    public B rel(String rel) {
-      return set("rel", rel);
-    }
-    
-    /**
-     * An objects alias is an alternative to it's "id".
-     * @param iri String
-     * @return B 
-     **/
-    public B alias(String iri) {
-      return set("alias", iri);
-    }
-    
-    /**
-     * Add an attachment
-     * @param url String
-     * @return B 
-     **/
-    public B attachments(String url, String... urls) {
-      if (url != null)
-        link("attachments", linkValue(url));
-      if (urls != null)
-        for (String u : urls)
-          link("attachments", linkValue(u));
-      return (B)this;
-    }
-  
-    /**
-     * Add an attachment.
-     * @param link LinkValue
-     * @return B 
-     **/
-    public B attachments(LinkValue link, LinkValue... links) {
-      if (link != null)
-        link("attachments", link);
-      if (links != null) 
-        for (LinkValue l : links)
-          link("attachments", l);
-      return (B)this;
-    }
-    
-    /**
-     * Add an attachment
-     * @param link Supplier
-     * @return B 
-     **/
-    public B attachments(Supplier link) {
-      return link("attachments", link.get());
-    }
-    
-    /**
-     * Set the author
-     * @param url String
-     * @return B 
-     **/
-    public B author(String url, String... urls) {
-      if (url != null)
-        link("author", linkValue(url));
-      if (urls != null) 
-        for (String u : urls)
-          link("author", linkValue(u));
-      return (B)this;
-    }
-  
-    /**
-     * Set the author
-     * @param link LinkValue
-     * @return B 
-     **/
-    public B author(LinkValue link, LinkValue... links) {
-      if (link != null)
-        link("author", link);
-      if (links != null)
-        for (LinkValue l : links)
-          link("author", l);
-      return (B)this;
-    }
-  
-    /**
-     * Set the author
-     * @param link Supplier
-     * @return B 
-     **/
-    public B author(Supplier link) {
-      return link("author", link.get());
-    }
-
-    /**
-     * Add a duplicate
-     * @param url String
-     * @return B 
-     **/
-    public B duplicates(String url, String... urls) {
-      if (url != null)
-        link("duplicates", linkValue(url));
-      if (urls != null)
-        for (String u : urls)
-          link("duplicates", linkValue(u));
-      return (B)this;
-    }
-  
-    /**
-     * Add a duplicate
-     * @param link LinkValue
-     * @return B 
-     **/
-    public B duplicates(LinkValue link, LinkValue... links) {
-      if (link != null)
-        link("duplicates", link);
-      if (links != null)
-        for (LinkValue l : links)
-          link("duplicates", l);
-      return (B)this;
-    }
-  
-    /**
-     * Add a duplicate
-     * @param link Supplier
-     * @return B 
-     **/
-    public B duplicates(Supplier link) {
-      return link("duplicates", link.get());
-    }
-
-    /**
-     * Set the icon
-     * @param url String
-     * @return B
-     **/
-    public B icon(String url, String... urls) {
-      if (url != null)
-        link("icon", linkValue(url));
-      if (urls != null)
-        for (String u : urls)
-          link("icon", linkValue(u));
-      return (B)this;
-    }
-  
-    /**
-     * Set the icon
-     * @param link LinkValue
-     * @return B */
-    public B icon(LinkValue link, LinkValue... links) {
-      if (link != null)
-        link("icon", link);
-      if (links != null)
-        for (LinkValue l : links)
-          link("icon", l);
-      return (B)this;
-    }
-  
-    /**
-     * Set the icon
-     * @param link Supplier
-     * @return B */
-    public B icon(Supplier link) {
-      return link("icon", link.get());
-    }
-
-    /**
-     * Set the image
-     * @param url String   
-     * @return B */
-    public B image(String url, String... urls) {
-      if (url != null)
-        link("image", linkValue(url));
-      if (urls != null)
-        for (String u : urls)
-          link("image", linkValue(u));
-      return (B)this;
-    }
-  
-    /**
-     * Set the image.
-     * @param link LinkValue 
-     * @return B */
-    public B image(LinkValue link, LinkValue... links) {
-      if (link != null)
-        link("image", link);
-      if (links != null)
-        for (LinkValue l : links)
-          link("image", l);
-      return (B)this;
-    }
-  
-    /**
-     * Set the image
-     * @param link Supplier 
-     * @return B */
-    public B image(Supplier link) {
-      return link("image", link.get());
-    }
-    
-    /**
-     * Set the location
-     * @param url String
-     * @return B */
-    public B location(String url, String... urls) {
-      if (url != null)
-        link("location", linkValue(url));
-      if (urls != null)
-        for (String u : urls)
-          link("location", linkValue(u));
-      return (B)this;
-    }
-  
-    /**
-     * Set the location
-     * @param link LinkValue  
-     * @return B */
-    public B location(LinkValue link, LinkValue... links) {
-      if (link != null)
-        link("location", link);
-      if (links != null)
-        for (LinkValue u : links)
-          link("location", u);
-      return (B)this;
-    }
-  
-    /**
-     * Set the location
-     * @param link Supplier  
-     * @return B */
-    public B location(Supplier link) {
-      return link("location", link.get());
-    }
-    
-    /**
-     * Set the generator
-     * @param url String  
-     * @return B */
-    public B generator(String url, String... urls) {
-      if (url != null)
-        link("generator", linkValue(url));
-      if (urls != null)
-        for (String u : urls)
-          link("generator", linkValue(u));
-      return (B)this;
-    }
-  
-    /**
-     * Set the generator
-     * @param link LinkValue 
-     * @return B */
-    public B generator(LinkValue link, LinkValue... links) {
-      if (link != null)
-        link("generator", link);
-      if (links != null)
-        for (LinkValue u : links)
-          link("generator", u);
-      return (B)this;
-    }
-  
-    /**
-     * Set the generator.
-     * @param link Supplier  
-     * @return B */
-    public B generator(Supplier link) {
-      return link("generator", link.get());
-    }
-    
-    /**
-     * Set the provider
-     * @param url String   
-     * @return B */
-    public B provider(String url, String... urls) {
-      if (url != null)
-        link("provider", linkValue(url));
-      if (urls != null)
-        for (String u : urls)
-          link("provider", linkValue(u));
-      return (B)this;
-    }
-  
-    /**
-     * Set the provider
-     * @param link LinkValue  
-     * @return B */
-    public B provider(LinkValue link, LinkValue... links) {
-      if (link != null)
-        link("provider", link);
-      if (links != null)
-        for (LinkValue l : links)
-          link("provider",l);
-      return (B)this;
-    }
-  
-    /**
-     * Set the provider
-     * @param link Supplier 
-     * @return B */
-    public B provider(Supplier link) {
-      return link("provider", link.get());
-    }
-    
-    /**
-     * Add a tag
-     * @param url String 
-     * @return B */
-    public B tags(String url, String... urls) {
-      if (url != null)
-        link("tags", linkValue(url));
-      if (urls != null)
-        for (String u : urls)
-          link("tags", linkValue(u));
-      return (B)this;
-    }
-  
-    /**
-     * Add a tag
-     * @param link LinkValue  
-     * @return B */
-    public B tags(LinkValue link, LinkValue... links) {
-      if (link != null)
-        link("tags", link);
-      if (links != null)
-        for (LinkValue l : links)
-          link("tags", l);
-      return (B)this;
-    }
-  
-    /**
-     * Add a tag
-     * @param link Supplier  
-     * @return B */
-    public B tags(Supplier link) {
-      return link("tags", link.get());
-    }
-
-    /**
-     * Add in-reply-to
-     * @param url String  
-     * @return B 
-     **/
-    public B inReplyTo(String url, String... urls) {
-      if (url != null)
-        link("inReplyTo", linkValue(url));
-      if (urls != null)
-        for (String u : urls)
-          link("inReplyTo", linkValue(u));
-      return (B)this;
-    }
-  
-    /**
-     * Add in-reply-to
-     * @param link LinkValue   
-     * @return B */
-    public B inReplyTo(LinkValue link, LinkValue... links) {
-      if (link != null)
-        link("inReplyTo", link);
-      if (links != null)
-        for (LinkValue l : links)
-          link("inReplyTo", l);
-      return (B)this;
-    }
-  
-    /**
-     * Add in-reply-to
-     * @param link Supplier 
-     * @return B 
-     **/
-    public B inReplyTo(Supplier link) {
-      return link("inReplyTo", link.get());
-    }
-    
-    /**
-     * Add a replies collection
-     * @param collection Collection 
-     * @return B */
-    public B replies(Collection collection) {
-      return set("replies", collection);
-    }
-    
-    /**
-     * Add a replies collection
-     * @param collection Supplier
-     * @return B */
-    public B replies(Supplier collection) {
-      return set("replies", collection.get());
-    }
-     
-    /**
-     * Set the ID
-     * @param iri String
-     * @return B 
-     **/
-    public B id(String iri) {
-      return set("id", iri);
-    }
-  
-    /**
-     * Set the objectType
-     * @param iri String
-     * @return B 
-     **/
-    public B objectType(String iri) {
-      return set("objectType", type(iri));
-    }
-    
-    /**
-     * Set the objectType
-     * @param tv TypeValue
-     * @return B 
-     **/
-    public B objectType(TypeValue tv) {
-      return set("objectType", tv);
-    }
-    
-    /**
-     * Set the objectType
-     * @param tv Supplier
-     * @return B 
-     **/
-    public B objectType(Supplier tv) {
-      return objectType(tv.get());
-    }
-  
-    /**
-     * Set the language
-     * @param lang String 
-     * @return B 
-     **/
-    public B language(String lang) {
-      return set("language", lang);
-    }
-  
-    /**
-     * Set the displayName
-     * @param name String 
-     * @return B 
-     **/
-    public B displayName(String name) {
-      return _nlv("displayName", name);
-    }
-  
-    /**
-     * Set the displayName
-     * @param nlv NLV  
-     * @return B 
-     **/
-    public B displayName(NLV nlv) {
-      return _nlv("displayName", nlv);
-    }
-  
-    /**
-     * Set the displayName
-     * @param nlv Supplier 
-     * @return B 
-     **/
-    public B displayName(Supplier nlv) {
-      return _nlv("displayName", nlv);
-    }
-  
-    /**
-     * Set the displayName
-     * @param lang String
-     * @param name String   
-     * @return B 
-     **/
-    public B displayName(String lang, String name) {
-      return _nlv("displayName",lang, name);
-    }
-  
-    /**
-     * Set the displayName
-     * @param map Map   
-     * @return B 
-     **/
-    public B displayName(Map map) {
-      return _nlv("displayName", map);
-    }
-
-    /**
-     * Set the content
-     * @param name String    
-     * @return B 
-     **/
-    public B content(String name) {
-      return _nlv("content", name);
-    }
-  
-    /**
-     * Set the content
-     * @param nlv NLV 
-     * @return B 
-     **/
-    public B content(NLV nlv) {
-      return _nlv("content", nlv);
-    }
-  
-    /**
-     * Set the content
-     * @param nlv Supplier
-     * @return B 
-     **/
-    public B content(Supplier nlv) {
-      return _nlv("content", nlv);
-    }
-  
-    /**
-     * Set the content
-     * @param lang String
-     * @param name String
-     * @return B 
-     **/
-    public B content(String lang, String name) {
-      return _nlv("content",lang, name);
-    }
-  
-    /**
-     * Set the content
-     * @param map Map
-     * @return B 
-     **/
-    public B content(Map map) {
-      return _nlv("content", map);
-    }
-
-    /**
-     * Set the summary
-     * @param name String
-     * @return B 
-     **/
-    public B summary(String name) {
-      return _nlv("summary", name);
-    }
-  
-    /**
-     * Set the summary
-     * @param nlv NLV
-     * @return B 
-     **/
-    public B summary(NLV nlv) {
-      return _nlv("summary", nlv);
-    }
-  
-    /**
-     * Set the summary
-     * @param nlv Supplier
-     * @return B 
-     **/
-    public B summary(Supplier nlv) {
-      return _nlv("summary", nlv);
-    }
-  
-    /**
-     * Set the summary
-     * @param lang String
-     * @param name String
-     * @return B 
-     **/
-    public B summary(String lang, String name) {
-      return _nlv("summary",lang, name);
-    }
-    
-    /**
-     * Set the summary
-     * @param map Map
-     * @return B 
-     **/
-    public B summary(Map map) {
-      return _nlv("summary", map);
-    }
-
-    /**
-     * Set the title
-     * @param name String
-     * @return B 
-     **/
-    public B title(String name) {
-      return _nlv("title", name);
-    }
-  
-    /**
-     * Set the title
-     * @param nlv NLV
-     * @return B 
-     **/
-    public B title(NLV nlv) {
-      return _nlv("title", nlv);
-    }
-  
-    /**
-     * Set the title
-     * @param nlv Supplier
-     * @return B 
-     **/
-    public B title(Supplier nlv) {
-      return _nlv("title", nlv);
-    }
-  
-    /**
-     * Set the title
-     * @param lang String
-     * @param value String
-     * @return B 
-     **/
-    public B title(String lang, String value) {
-      return _nlv("title",lang, value);
-    }
-  
-    /**
-     * Set the title
-     * @param map Map
-     * @return B 
-     **/
-    public B title(Map map) {
-      return _nlv("title", map);
-    }
-    
-    /**
-     * Add an action handler
-     * @param verb String
-     * @param iri String
-     * @return B
-     */
-    public B action(String verb, String iri, String... iris) {
-      if (iri != null)
-        actions.set(verb, iri);
-      if (iris != null)
-        for (String i : iris)
-          actions.set(verb, i);
-      return (B)this;
-    }
-    
-    /**
-     * Add an action handler
-     * @param verb String
-     * @param lv LinkValue
-     * @return B
-     */
-    public B action(String verb, LinkValue lv, LinkValue... links) {
-      if (lv != null)
-        actions.set(verb, lv);
-      if (links != null)
-        for (LinkValue l : links)
-          actions.set(verb, l);
-      return (B)this;
-    }
-    
-    /**
-     * Add an action handler
-     * @param verb String
-     * @param lv Supplier
-     * @return B
-     */
-    public B action(String verb, Supplier lv) {
-      return action(verb, lv.get());
-    }
-        
-    /**
-     * Method _nlv.
-     * @param key String
-     * @param value String
-     * @return B
-     **/
-    protected B _nlv(String key, String value) {
-      return set(key, nlv(value));
-    }
-  
-    /**
-     * Method _nlv.
-     * @param key String
-     * @param nlv NLV
-     * @return B 
-     **/
-    protected B _nlv(String key, NLV nlv) {
-      return set(key, nlv);
-    }
-  
-    /**
-     * Method _nlv.
-     * @param key String
-     * @param nlv Supplier
-     * @return B 
-     **/
-    protected B _nlv(String key, Supplier nlv) {
-      return set(key, nlv.get());
-    }
-  
-    /**
-     * Method _nlv.
-     * @param key String
-     * @param map Map
-     * @return B 
-     **/
-    protected B _nlv(String key, Map map) {
-      for (Map.Entry entry : map.entrySet())
-        _nlv(key,entry.getKey(),entry.getValue());
-      return (B)this;
-    }
-    
-    /**
-     * Method _nlv.
-     * @param key String
-     * @param lang String
-     * @param value String
-     * @return B 
-     **/
-    protected B _nlv(String key, String lang, String value) {
-      if (map.containsKey(key)) {
-        Object obj = map.get(key);
-        if (obj instanceof NLV) {
-          NLV nlv = (NLV) obj;
-          switch(nlv.valueType()) {
-          case SIMPLE:
-            String l = (String) map.get("language");
-            if (l == null)
-              l = DEFAULT_LOCALE;
-            NLV.MapNLV.Builder b = 
-              Makers.nlv();
-            if (lang.equals(l))
-              b.set(lang, value);
-            else
-              b.set(l, ((NLV.SimpleNLV)obj).value())
-                 .set(lang, value);
-            return set(key, b);
-          case OBJECT:
-            return set(key, 
-              Makers.nlv()
-                .from((NLV.MapNLV)obj, lang)
-                .set(lang, value)); 
-          default:
-            throw new IllegalArgumentException();
-          }
-        } else if (obj instanceof NLV.MapNLV.Builder) {
-          ((NLV.MapNLV.Builder) obj).set(lang, value);
-          return (B)this;
-        }
-      }
-      set(key, Makers.nlv().set(lang,value));      
-      return (B)this;
-    }
-    
-    /**
-     * Set the "url"
-     * @param url String
-     * @return B 
-     **/
-    public B url(String url, String... urls) {
-      if (url != null)
-        link("url", linkValue(url));
-      if (urls != null)
-        for (String u : urls)
-          link("url", linkValue(u));
-      return (B)this;
-    }
-    
-    /**
-     * Set the "url"
-     * @param link Supplier
-     * @return B 
-     **/
-    public B url(Supplier link) {
-      return url(link.get());
-    }
-  
-    /**
-     * Set the "url"
-     * @param link LinkValue
-     * @return B 
-     **/
-    public B url(LinkValue link, LinkValue... links) {
-      if (link != null)
-        link("url", link);
-      if (links != null)
-        for (LinkValue l : links)
-          link("url", l);
-      return (B)this;
-    }
-    
-    /**
-     * Add a link
-     * @param name String
-     * @param url String
-     * @return B 
-     **/
-    public B link(String name, String url) {
-      return link(name, linkValue(url));
-    }
-    
-    /**
-     * Add a link
-     * @param name String
-     * @param link LinkValue   
-     * @return B 
-     **/
-    public B link(String name, LinkValue link) {
-      if (link == null)
-        return (B)this;
-      Object obj = map.get(name);
-      if (link.valueType() != ValueType.ARRAY) {
-        if (obj instanceof LinkValue)
-          link = 
-            ((LinkValue) obj).valueType() == ValueType.ARRAY ?
-              linkValues()
-                .add((LinkValue.ArrayLinkValue)obj)
-                .add(link)
-                .get() :
-              linkValues()
-                .add((LinkValue)obj, link)
-                .get();
-        map.put(name, link);
-      } else set(name, link);
-      return (B)this;
-    }
-  
-    /**
-     * Add a link
-     * @param name String
-     * @param link Supplier
-     * @return B 
-     **/
-    public B link(String name, Supplier link) {
-      return link(name,link.get());
-    }
-
-    /**
-     * Add a link
-     * @param name String
-     * @param links Object[]
-     * @return B 
-     **/
-    protected B link(String name, Object... links) {
-      if (links == null) return (B)this;
-      ArrayLinkValue.Builder b = 
-        ArrayLinkValue.make();
-      for (Object obj : links)
-        _add(b, obj);
-      return link(name,b.get());
-    }
-    
-    /**
-     * Method _add.
-     * @param builder ArrayLinkValue.Builder
-     * @param obj Object
-     */
-    private void _add(ArrayLinkValue.Builder builder, Object obj) {
-      if (obj == null)
-        return;
-      else if (obj instanceof String)
-        builder.add((String)obj);
-      else if (obj instanceof ASObject)
-        builder.add((ASObject)obj);
-      else if (obj instanceof Supplier)
-        _add(builder,((Supplier)obj).get());
-      else throw new IllegalArgumentException();
-    }
-  
-    /**
-     * Set a property
-     * @param key String
-     * @param value V
-     * @return B 
-     **/
-    public B set(String key, Object value) {
-      if (value == null) 
-        return (B)this;
-      if (value instanceof Supplier)
-        map.put(key, ((Supplier)value).get());
-      else
-        map.put(key, value);
-      return (B)this;
-    }
-    
-    /**
-     * Set a property
-     * @param key String
-     * @param value Supplier
-     * @return B 
-     **/
-    public B set(String key, Supplier value) {
-      try {
-        return value == null ?
-          (B)this : set(key,value.get());
-      } catch (Throwable t) {
-        throw propagate(t);
-      }
-    }
-    
-    /**
-     * Set a property from a given callable
-     * @param key String
-     * @param value Callable
-     * @return B 
-     **/
-    public B set(String key, Callable value) {
-      try {
-        return value == null ?
-          (B)this : 
-          set(key,value.call());
-      } catch (Throwable t) {
-        throw propagate(t);
-      }
-    }
-    
-    /**
-     * Set the scope
-     * @param url String
-     * @return B 
-     **/
-    public B scope(String url, String... urls) {
-      if (url != null)
-        link("scope", linkValue(url));
-      if (urls != null)
-        for (String u : urls)
-          link("scope", linkValue(u));
-      return (B)this;
-    }
-  
-    /**
-     * Set the scope
-     * @param link LinkValue
-     * @return B 
-     **/
-    public B scope(LinkValue link, LinkValue... links) {
-      if (link != null)
-        link("scope", link);
-      if (links != null)
-        for (LinkValue l : links)
-          link("scope", l);
-      return (B)this;
-    }
-  
-    /**
-     * Set the scope
-     * @param link Supplier
-    
-     * @return B */
-    public B scope(Supplier link) {
-      return link("scope", link.get());
-    }   
-  }
-  
-  protected final ImmutableMap map;
-  private transient int hash = 1;
-  
-  /**
-   * Constructor for ASObject.
-   * @param builder ASObject.AbstractBuilder
-   */
-  public ASObject(ASObject.AbstractBuilder builder) {
-    super(builder);
-    if (builder.actions.notEmpty())
-      builder.map.put("actions", builder.actions.get());
-    this.map = ImmutableMap.copyOf(builder.map);
-  }
-  
-  /**
-   * Returns true if the given property exists, does not 
-   * determine if the value is non-null
-   * @param key String
-   * @return boolean 
-   **/
-  public boolean has(String key) {
-    return map.containsKey(key);
-  }
-  
-  /**
-   * Return the value of the property if it exists, null otherwise
-   * @param key String
-   * @return V 
-   **/
-  public V get(String key) {
-    return this._get(key).orNull();
-  }
-  
-  /**
-   * Return the value of the property if it exists, casting to a DateTime
-   * object.
-   * @param key String
-   * @return DateTime
-   */
-  public DateTime getDateTime(String key) {
-    return this.get(key,toDateTime,Optional.absent()).orNull();
-  }
-  
-  /**
-   * Return the value of the property if it exists, converting the value
-   * to the given Enum class. 
-   * @param key String
-   * @param _enumClass Class
-   * @return E
-   */
-  public >E getEnum(String key, Class _enumClass) {
-    return getEnum(key, _enumClass, (E)null);
-  }
-  
-  /**
-   * Method getEnum.
-   * @param key String
-   * @param _enumClass Class
-   * @param or E
-   * @return E
-   */
-  public >E getEnum(String key, Class _enumClass, E or) {
-    String val = getString(key);
-    Optional op = getIfPresent(_enumClass, val);
-    return or != null ?
-      op.or(or) : op.orNull();
-  }
-  
-  /**
-   * Return the value of the property if it exists, casting to a String
-   * object.
-   * @param key String
-   * @return String
-   */
-  public String getString(String key) {
-    return getString(key, null);
-  }
-  
-  /**
-   * Method getDuration.
-   * @param key String
-   * @return Duration
-   */
-  public Duration getDuration(String key) {
-    return this.get(key, toDuration, Optional.absent()).orNull();
-  }
-  
-  /**
-   * Method getPeriod.
-   * @param key String
-   * @return Period
-   */
-  public Period getPeriod(String key) {
-    return this.get(key, toPeriod, Optional.absent()).orNull();
-  }
-  
-  /**
-   * Method getInterval.
-   * @param key String
-   * @return Interval
-   */
-  public Interval getInterval(String key) {
-    return this.get(key, toInterval, Optional.absent()).orNull();
-  }
-  
-  /**
-   * Return the value of the property as a string if it exists or defaultValue if 
-   * it does not. 
-   * @param key String
-   * @param defaultValue String
-   * @return String
-   */
-  public String getString(String key, String defaultValue) {
-    return defaultValue != null ?
-      this._get(key).or(defaultValue) :
-      this._get(key).orNull();
-  }
-  
-  /**
-   * Return the value of the property as an int if it exists or 0 if it does not.
-   * @param key String
-   * @return int
-   */
-  public int getInt(String key) {
-    return getInt(key, 0);
-  }
-  
-  /**
-   * Return the value of the property as an int if it exists or defaultValue if
-   * it does not
-   * @param key String
-   * @param defaultValue int
-   * @return int
-   */
-  public int getInt(String key, int defaultValue) {
-    return get(key, toInt, Optional.absent()).or(defaultValue);
-  }
-  
-  /**
-   * Return the value of the property as a long if it exists or 0 if it does not
-   * @param key String
-   * @return long
-   */
-  public long getLong(String key) {
-    return getLong(key,0L);
-  }
-  
-  /**
-   * Return the value of the property as a long if it exists or defaultValue if
-   * it does not
-   * @param key String
-   * @param defaultValue long
-   * @return long
-   */
-  public long getLong(String key, long defaultValue) {
-    return get(key, toLong, Optional.absent()).or(defaultValue);
-  }
-  
-  /**
-   * Return the value of the property as a double if it exists, or 0.0 if it
-   * does not
-   * @param key String
-   * @return double
-   */
-  public double getDouble(String key) {
-    return getDouble(key, 0.0);
-  }
-  
-  /**
-   * Return the value of the property as a double if it exists or defaultValue
-   * if it does not
-   * @param key String
-   * @param defaultValue double
-   * @return double
-   */
-  public double getDouble(String key, double defaultValue) {
-    return get(key, toDouble, Optional.absent()).or(defaultValue);
-  }
-  
-  /**
-   * Return the value of the property as a float if it exists or 0f if it 
-   * does not
-   * @param key String
-   * @return float
-   */
-  public float getFloat(String key) {
-    return getFloat(key, 0f);
-  }
-  
-  /**
-   * Return the value of the property as a float if it exists or defaultValue
-   * if it does not
-   * @param key String
-   * @param defaultValue float
-   * @return float
-   */
-  public float getFloat(String key, float defaultValue) {
-    return get(key, toFloat, Optional.absent()).or(defaultValue);
-  }
-  
-  /**
-   * Return the value of the property as a short if it exists or 0 if it 
-   * does not
-   * @param key String
-   * @return short
-   */
-  public short getShort(String key) {
-    return getShort(key,(short)0);
-  }
-  
-  /**
-   * Return the value of the property as a short if it exists or defaultValue
-   * if it does not
-   * @param key String
-   * @param defaultValue short
-   * @return short
-   */
-  public short getShort(String key, short defaultValue) {
-    return get(key, toShort, Optional.absent()).or(defaultValue);
-  }
-  
-  /**
-   * return the value of the property as a boolean if it exists or false 
-   * if it does not
-   * @param key String
-   * @return boolean
-   */
-  public boolean getBoolean(String key) {
-    return getBoolean(key,false);
-  }
-  
-  /**
-   * Return the value of the property as a boolean if it exists or defaultValue
-   * if it does not
-   * @param key String
-   * @param defaultValue boolean
-   * @return boolean
-   */
-  public boolean getBoolean(
-    String key, 
-    boolean defaultValue) {
-      return get(key, toBoolean, Optional.absent()).or(defaultValue);
-  }
-  
-  /**
-   * Method _get.
-   * @param key String
-   * @return Optional
-   */
-  private Optional _get(String key) {
-    return Optional.fromNullable((V)map.get(key));
-  }
-  
-  /**
-   * Method _get.
-   * @param key String
-   * @param transform Function
-   * @return Optional
-   */
-  private Optional _get(String key, Function transform) {
-    return this._get(key).transform(transform);
-  }
-  
-  /**
-   * Return the value if it exists or defaultValue if it does not
-   * @param key String
-   * @param defaultValue V
-   * @return V 
-   **/
-  public V get(String key, V defaultValue) {
-    return defaultValue != null ?
-      this._get(key).or(defaultValue) :
-      this._get(key).orNull();
-  }
-  
-  /**
-   * Returns the value of the property, transformed using the given function
-   * @param key String
-   * @param transform Function
-   * @return V2 
-   **/
-  public V2 get(String key, Function transform, V2 defaultValue) {
-    return this._get(key,transform).or(defaultValue);
-  }
-  
-  /**
-   * Returns the value of the given property converted using the given converter
-   * @param key String
-   * @param converter Converter
-   * @return V2
-   */
-  public V2 get(String key, Converter converter) {
-    return this._get(key,converter).orNull();
-  }
-  
-  /**
-   * Returns the value of the property if it exists or defaultValue if it
-   * does not
-   * @param key String
-   * @param def V2
-   * @param transform Function
-   * @return V2 
-   **/
-  public V2 get(String key, V2 def, Function transform) {
-    return this._get(key,transform).or(def);
-  }
-
-  /**
-   * Returns an iterator listing all of the properties defined on this object
-   * @return Iterator 
-   * @see java.lang.Iterable#iterator() 
-   **/
-  public Iterator iterator() {
-    return map.keySet().iterator();
-  }
-  
-  /**
-   * Return this objects identifier
-   * @return String 
-   * @see com.ibm.common.activitystreams.TypeValue#id() 
-   **/
-  public String id() {
-    return this.getString("id");
-  }
-  
-  /**
-   * Return the objectType
-   * @return T 
-   **/
-  public T objectType() {
-    return this.get("objectType");
-  }
-  
-  /**
-   * Return this object's type identifier as a string
-   * @return String 
-   **/
-  public String objectTypeString() {
-    return typeValueAsString("objectType");
-  }
-  
-  /**
-   * Method typeValueAsString.
-   * @param name String
-   * @return String 
-   **/
-  protected String typeValueAsString(String name) {
-    TypeValue tv = this.get(name);
-    return tv != null ? tv.id() : null;
-  }
-  
-  /**
-   * Return this object's language context
-   * @return String 
-   **/
-  public String language() {
-    return this.getString("language");
-  }
-  
-  /**
-   * Return this objects displayName as an NLV object
-   * @return NLV 
-   **/
-  public NLV displayName() {
-    return this.get("displayName");
-  }
-  
-  /**
-   * Return this objects displayName
-   * @return String 
-   **/
-  public String displayNameString() {
-    return _nlv("displayName");
-  }
-  
-  /**
-   * Method displayNameString.
-   * @param lang String
-   * @return String 
-   **/
-  public String displayNameString(String lang) {
-    return _nlv("displayName", lang);
-  }
-  
-  /**
-   * Method _nlv.
-   * @param key String
-   * @return String 
-   **/
-  protected String _nlv(String key) {
-    String lang = language();
-    return _nlv(key, lang != null ? lang : DEFAULT_LOCALE);
-  }
-  
-  /**
-   * Method _nlv.
-   * @param key String
-   * @param lang String
-   * @return String 
-   **/
-  protected String _nlv(String key, String lang) {
-    NLV nlv = 
-      this.get(key);
-    switch(nlv.valueType()) {
-    case SIMPLE:
-      NLV.SimpleNLV sim = 
-        (SimpleNLV) nlv;
-      String l = language();
-      return l == null || Objects.equal(l,lang) ? sim.value() : null;
-    case OBJECT:
-      NLV.MapNLV map = 
-       (MapNLV) nlv;
-      return map.value(lang);
-    default:
-      return null;
-    } 
-  }
-  
-  /**
-   * Return this objects URL LinkValues
-   * @return java.util.Iterable<LinkValue> 
-   **/
-  public Iterable url() {
-    return links("url");
-  }
-  
-  /**
-   * Return the matching URL LinkValues
-   * @return java.util.Iterable<LinkValue>
-   **/
-  public Iterable url(Predicate test) {
-    return links("url", test);
-  }
-  
-  /**
-   * Return this objects first URL LinkValue
-   * @return LinkValue
-   */
-  public LinkValue firstUrl() {
-    return firstLink("url");
-  }
-  
-  /**
-   * Return this objects first matching LinkValue
-   * @param test
-   * @return LinkValue
-   */
-  public LinkValue firstMatchingUrl(Predicate test) {
-    return firstMatchingLink("url", test);
-  }
-  
-  /**
-   * Return this object's mediaType
-   * @return MediaType 
-   **/
-  public MediaType mediaType() {
-    return this.get("mediaType");
-  }
-  
-  /**
-   * Returns the value of this objects's rel property
-   * @return String 
-   **/
-  public String rel() {
-    return this.getString("rel");
-  }
-  
-  /**
-   * Returns this value of this object's alias property
-   * @return String 
-   **/
-  public String alias() {
-    return this.getString("alias");
-  }
-  
-  /**
-   * Return the given set of links
-   * @param name String
-   * @return java.util.Iterable 
-   **/
-  protected Iterable links(String name) {
-    LinkValue lv = this.get(name);
-    if (lv == null) return of();
-    return lv.valueType() == ValueType.ARRAY ?
-      (Iterable)lv : of(lv);
-  }
-  
-  protected Iterable links(
-    String name, 
-    Predicate test) {
-      return filter(links(name), test);
-  }
-  
-  protected LinkValue firstLink(String name) {
-    return getFirst(links(name), null);
-  }
-  
-  protected LinkValue firstMatchingLink(
-    String name, 
-    Predicate test) {
-      return getFirst(links(name,test), null);
-  }
-  
-  /**
-   * Return the set of attachments
-   * @return java.util.Iterable 
-   **/
-  public Iterable attachments() {
-    return links("attachments");
-  }
-  
-  /**
-   * Return the matching set of attachments;
-   * @param test
-   * @return java.util.Iterable<LinkValue>
-   */
-  public Iterable attachments(Predicate test) {
-    return links("attachments", test);
-  }
-  
-  /**
-   * Return the first attachment for this object
-   * @return LinkValue
-   */
-  public LinkValue firstAttachment() {
-    return firstLink("attachments");
-  }
-  
-  /**
-   * Return the first matching attachment
-   * @param test
-   * @return LinkValue
-   */
-  public LinkValue firstMatchingAttachment(Predicate test) {
-    return firstMatchingLink("attachments", test);
-  }
-  
-  /**
-   * Return this authors of this object
-   * @return java.util.Iterable 
-   **/
-  public Iterable author() {
-    return links("author");
-  }
-  
-  /**
-   * Return the matching authors of this object
-   * @return java.util.Iterable
-   */
-  public Iterable author(Predicate test) {
-    return links("author", test);
-  }
-  
-  /**
-   * Return the first author
-   * @return LinkValue
-   */
-  public LinkValue firstAuthor() {
-    return firstLink("author");
-  }
-  
-  /**
-   * Return the first matching author
-   * @param test
-   * @return LinkValue
-   */
-  public LinkValue firstMatchingAuthor(Predicate test) {
-    return firstMatchingLink("author", test);
-  }
-  
-  /**
-   * Return the collection of duplicates for this object
-   * @return java.util.Iterable 
-   **/
-  public Iterable duplicates() {
-    return links("duplicates");
-  }
-  
-  /**
-   * Return the matching duplicates
-   * @param test
-   * @return java.util.Iterable<LinkValue>
-   */
-  public Iterable duplicates(Predicate test) {
-    return links("duplicates", test);
-  }
-  
-  /**
-   * Return the first duplicate
-   * @return LinkValue
-   */
-  public LinkValue firstDuplicate() {
-    return firstLink("duplicates");
-  }
-  
-  /**
-   * Return the first matching duplicate
-   * @param test
-   * @return LinkValue
-   */
-  public LinkValue firstMatchingDuplicate(Predicate test) {
-    return firstMatchingLink("duplicates", test);
-  }
-  
-  /**
-   * Return the icons for this object
-   * @return java.util.Iterable */
-  public Iterable icon() {
-    return links("icon");
-  }
-  
-  /**
-   * Return the matching icons for this object
-   * @return java.util.Iterable
-   */
-  public Iterable icon(Predicate test) {
-    return links("icon", test);
-  }
-  
-  /**
-   * Return the first icon
-   * @return LinkValue
-   */
-  public LinkValue firstIcon() {
-    return firstLink("icon");
-  }
-  
-  /**
-   * Return thie first matching icon
-   * @param test
-   * @return LinkValue
-   */
-  public LinkValue firstMatchingIcon(Predicate test) {
-    return firstMatchingLink("icon", test);
-  }
-  
-  /**
-   * Return the image for this object
-   * @return java.util.Iterable
-   **/
-  public Iterable image() {
-    return links("image");
-  }
-  
-  /**
-   * Return the matching images for this object
-   * @param test
-   * @return java.util.Iterable
-   */
-  public Iterable image(Predicate test) {
-    return links("image", test);
-  }
-  
-  /**
-   * Return the first image
-   * @return LinkValue
-   */
-  public LinkValue firstImage() {
-    return firstLink("image");
-  }
-  
-  /**
-   * Return the first matching image
-   * @param test
-   * @return LinkValue
-   */
-  public LinkValue firstMatchingImage(Predicate test) {
-    return firstMatchingLink("image", test);
-  }
-  
-  /**
-   * Return the location associated with this object
-   * @return java.util.Iterable 
-   **/
-  public Iterable location() {
-    return links("location");
-  }
-  
-  /**
-   * Return the matching locations associated with this object
-   * @param test
-   * @return java.util.Iterable
-   */
-  public Iterable location(Predicate test) {
-    return links("location", test);
-  }
-  
-  /**
-   * Return the first location associated with this object
-   * @return LinkValue
-   */
-  public LinkValue firstLocation() {
-    return firstLink("location");
-  }
-  
-  /**
-   * Return the first matching location associated with this object
-   * @param test
-   * @return LinkValue
-   */
-  public LinkValue firstMatchingLocation(Predicate test) {
-    return firstMatchingLink("location", test);
-  }
-  
-  /**
-   * Return the generators for this object
-   * @return java.util.Iterable 
-   **/
-  public Iterable generator() {
-    return links("generator");
-  }
-  
-  /**
-   * Return the matching generators for this object
-   * @return java.util.Iterable
-   */
-  public Iterable generator(Predicate test) {
-    return links("generator", test);
-  }
-  
-  /**
-   * Return the first generator for this object
-   * @return LinkValue
-   */
-  public LinkValue firstGenerator() {
-    return firstLink("generator");
-  }
-  
-  /**
-   * Return the first matching generator for this object
-   * @param test
-   * @return LinkValue
-   */
-  public LinkValue firstMatchingGenerator(Predicate test) {
-    return firstMatchingLink("generator", test);
-  }
-  
-  /**
-   * Return the providers for this object
-   * @return java.util.Iterable 
-   **/
-  public Iterable provider() {
-    return links("provider");
-  }
-  
-  /**
-   * Return the matching providers for this object
-   * @return java.util.Iterable
-   */
-  public Iterable provider(Predicate test) {
-    return links("provider", test);
-  }
-  
-  /**
-   * Return the first provider for this object
-   * @return LinkValue
-   */
-  public LinkValue firstProvider() {
-    return firstLink("provider");
-  }
-  
-  /**
-   * Return the first matching providers for this object
-   * @param test
-   * @return LinkValue
-   */
-  public LinkValue firstMatchingProvider(Predicate test) {
-    return firstMatchingLink("provider", test);
-  }
-  
-  /**
-   * Return the tags for this object
-   * @return java.util.Iterable 
-   **/
-  public Iterable tags() {
-    return links("tags");
-  }
-  
-  /**
-   * Return the matching tags for this object
-   * @return java.util.Iterable
-   */
-  public Iterable tags(Predicate test) {
-    return links("tags", test);
-  }
-  
-  /**
-   * Return the first tag for this object
-   * @return LinkValue
-   */
-  public LinkValue firstTag() {
-    return firstLink("tags");
-  }
-  
-  /**
-   * Return this first matching tag for this object
-   * @param test
-   * @return LinkValue
-   */
-  public LinkValue firstMatchingTag(Predicate test) {
-    return firstMatchingLink("tags", test);
-  }
-  
-  /**
-   * Return the inReplyTo links for this object
-   * @return java.util.Iterable 
-   **/
-  public Iterable inReplyTo() {
-    return links("inReplyTo");
-  }
-  
-  /**
-   * Return the matching inReplyTo links for this object
-   * @return java.util.Iterable
-   */
-  public Iterable inReplyTo(Predicate test) {
-    return links("inReplyTo", test);
-  }
-  
-  /**
-   * Return the first inReplyTo link for this object
-   * @return LinkValue
-   */
-  public LinkValue firstInReplyTo() {
-    return firstLink("inReplyTo");
-  }
-  
-  /**
-   * Return the first matching inReplyTo link for this object
-   * @param test
-   * @return LinkValue
-   */
-  public LinkValue firstMatchingInReplyTo(Predicate test) {
-    return firstMatchingLink("inReplyTo", test);
-  }
-  
-  /**
-   * Return the content of this object
-   * @return NLV 
-   **/
-  public NLV content() {
-    return this.get("content");
-  }
-  
-  /**
-   * Return the content of this object
-   * @return String 
-   **/
-  public String contentString() {
-    return _nlv("content");
-  }
-  
-  /**
-   * Return the content of this object for the given language
-   * @param lang String
-   * @return String */
-  public String contentString(String lang) {
-    return _nlv("content", lang);
-  }
-  
-  /**
-   * Return the title of this object
-   * @return NLV 
-   **/
-  public NLV title() {
-    return this.get("title");
-  }
-  
-  /**
-   * Return the title of this object
-   * @return String 
-   **/
-  public String titleString() {
-    return _nlv("title");
-  }
-  
-  /**
-   * Return the title of this object for the given language
-   * @param lang String
-   * @return String 
-   **/
-  public String titleString(String lang) {
-    return _nlv("title", lang);
-  }
-  
-  /**
-   * Return the summary of this object
-   * @return NLV 
-   **/
-  public NLV summary() {
-    return this.get("summary");
-  }
-  
-  /**
-   * Return the summary of this object
-   * @return String 
-   **/
-  public String summaryString() {
-    return _nlv("summary");
-  }
-  
-  /**
-   * Return the summary of this object for the given language
-   * @param lang String
-   * @return String */
-  public String summaryString(String lang) {
-    return _nlv("summary", lang);
-  }
-  
-  /**
-   * Return the published timestamp for this object
-   * @return DateTime */
-  public DateTime published() {
-    return this.getDateTime("published");
-  }
-  
-  /**
-   * Return the updated timestamp for this object
-   * @return DateTime 
-   **/
-  public DateTime updated() {
-    return this.getDateTime("updated");
-  }
-  
-  /**
-   * Return the startTime timestamp for this object
-   * @return DateTime 
-   **/
-  public DateTime startTime() {
-    return this.getDateTime("startTime");
-  }
-  
-  /**
-   * Return the endTime timestamp for this object
-   * @return DateTime 
-   **/
-  public DateTime endTime() {
-    return this.getDateTime("endTime");
-  }
-  
-  /**
-   * Return the rating property for this object
-   * @return double 
-   **/
-  public double rating() {
-    return checkRating(getDouble("rating"));
-  }
-  
-  /**
-   * Return the duration of this object
-   * @return Duration 
-   **/
-  public Duration duration() {
-    return this.get("duration", toDuration, Optional.absent()).orNull();
-  }
-  
-  /**
-   * Return the height of this object in device independent pixels
-   * @return int 
-   **/
-  public int height() {
-    return checkNotNegative(getInt("height"));
-  }
-  
-  /**
-   * Return the width of this object in device independent pixels
-   * @return int 
-   **/
-  public int width() {
-    return checkNotNegative(getInt("width"));
-  }
-  
-  /**
-   * Return the replies collection for this object
-   * @return Collection */
-  public Collection replies() {
-    return this.get("replies");
-  }
-  
-  /**
-   * Return the actions collection for this object
-   * @return ActionsValue 
-   */
-  public ActionsValue actions() {
-    return this.get("actions");
-  }
-  
-  /**
-   * Return the scope
-   * @return java.util.Iterable 
-   **/
-  public Iterable scope() {
-    return links("scope");
-  }
-  
-  /**
-   * Return the matching scope items
-   * @return java.util.Iterable
-   */
-  public Iterable scope(Predicate test) {
-    return links("scope", test);
-  }
-  
-  /**
-   * Return the first scope item
-   * @return LinkValue
-   */
-  public LinkValue firstScope() {
-    return firstLink("scope");
-  }
-  
-  /**
-   * Return the first matching scope item
-   * @param test
-   * @return LinkValue
-   */
-  public LinkValue firstMatchingScope(Predicate test) {
-    return firstMatchingLink("scope", test);
-  }
-
-  @Override
-  public int hashCode() {
-    if (hash == 1)
-      hash = Objects.hashCode(map);
-    return hash;
-  }
-
-  @Override
-  public boolean equals(Object obj) {
-    if (this == obj)
-      return true;
-    if (obj == null)
-      return false;
-    if (getClass() != obj.getClass())
-      return false;
-    ASObject other = (ASObject) obj;
-    return 
-      difference(map, other.map)
-        .areEqual();
-  }
-  
-  /**
-   * Return the valueType of this object (always returns ValueType.OBJECT)
-   * @return ValueType
-   * @see com.ibm.common.activitystreams.LinkValue#valueType()
-   */
-  public ValueType valueType() {
-    return ValueType.OBJECT;
-  }
-  
-  
-  // Java Serialization support... 
-  
-  Object writeReplace() throws java.io.ObjectStreamException {
-    return new SerializedForm(this);
-  }
-  
-  private static class SerializedForm 
-    extends AbstractSerializedForm {
-    protected SerializedForm(ASObject obj) {
-      super(obj);
-    }
-    private static final long serialVersionUID = -1975376657749952999L;
-    protected ASObject.Builder builder() {
-      return Makers.object();
-    }
-    Object readResolve() throws ObjectStreamException {
-      return super.doReadResolve();
-    }
-  }
-  
-  protected static abstract class AbstractSerializedForm 
-    implements Serializable {
-    private static final long serialVersionUID = -801787904013409277L;
-    private ImmutableMap map;
-    protected AbstractSerializedForm(A obj) {      
-      this.map = ImmutableMap.copyOf(Maps.transformValues(obj.map, SerializableTransform));
-    }
-    protected abstract ASObject.AbstractBuilder builder();
-    protected Object doReadResolve() 
-      throws java.io.ObjectStreamException {
-        ASObject.AbstractBuilder builder = builder();
-        for (Map.Entry entry : map.entrySet()) {
-          Object obj = entry.getValue();
-          if (obj instanceof SerializableMediaType)
-            obj = ((SerializableMediaType)obj).mediaType();
-          builder.set(entry.getKey(), obj);
-        }
-        return builder.get();
-    }
-  }
-  
-  private static final Function SerializableTransform = 
-    new Function() {
-      public Object apply(Object input) {
-        if (input instanceof MediaType)
-          input = new SerializableMediaType((MediaType) input);
-        return input;
-      }
-    };
-  
-  private static final class SerializableMediaType 
-    implements Serializable {
-    private static final long serialVersionUID = -3162545492169619570L;
-    private String mediaType;
-    SerializableMediaType(MediaType mt) {
-      this.mediaType = mt.toString();
-    }
-    MediaType mediaType() {
-      return MediaType.parse(mediaType);
-    }
-  }
-}
diff --git a/core/src/main/java/com/ibm/common/activitystreams/ActionsValue.java b/core/src/main/java/com/ibm/common/activitystreams/ActionsValue.java
deleted file mode 100755
index 05ba103..0000000
--- a/core/src/main/java/com/ibm/common/activitystreams/ActionsValue.java
+++ /dev/null
@@ -1,234 +0,0 @@
-/**
- * Copyright 2013 OpenSocial Foundation
- * Copyright 2013 International Business Machines Corporation
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * Utility library for working with Activity Streams Actions
- * Requires underscorejs.
- *
- * @author James M Snell (jasnell@us.ibm.com)
- */
-package com.ibm.common.activitystreams;
-
-import java.io.Serializable;
-import java.util.Map;
-
-import com.google.common.base.Function;
-import com.google.common.base.Predicate;
-import com.google.common.base.Supplier;
-import com.google.common.collect.ImmutableMap;
-import com.ibm.common.activitystreams.util.AbstractDictionaryObject;
-
-/**
- * 

The value of the "actions" property... used to map potential verbs - * with objects capable of "handling" those verbs. Each of the keys - * must be a valid verb (either a token or an absolute IRI).

- * - *

Specifying Actions while creating AS Objects:

- * - *
- * import static com.ibm.common.activitystreams.Makers.object;
- * import static com.ibm.common.activitystreams.Makers.actions;
- * import static com.ibm.common.activitystreams.actions.ActionMakers.intentAction;
- * ...
- * 
- * ASObject obj = object()
- *   .action("like", "http://example.org/like-action")
- *   .action("follow", intentAction())
- *   .get();
- * 
- * - *

Accessing Actions when consuming AS Objects:

- * - *
- * ActionsValue actions = obj.actions();
- * for (LinkValue lv : actions.get("like")) {
- *   ...
- * }
- * 
- * - *

The Actions object itself is a JSON Dictonary that maps - * verb identifiers to a Link Value that contains one or more - * Action Handlers. A call to the get(...) method returns an - * Iterable of Simple or Object LinkValue instances representing - * each of the associated Action Handlers.

- * - *

A Serialized Activity Stream object with Actions: - *

- * {
- *   "objectType": "note",
- *   "displayName": "My Note",
- *   "actions": { 
- *     "like": "http://example.org/like-action",
- *     "follow": {
- *       "objectType": "IntentActionHandler",
- *       "displayName": "Follow updates to this note!"
- *     }
- *   }
- * }
- * 
- * - * @author james - * @version $Revision: 1.0 $ - */ -public final class ActionsValue - extends AbstractDictionaryObject - implements Serializable { - - /** - * Builder for ActionsValue objects. - *
-   *   Makers.actions()
-   *     .set("like", "http://example.org/like-action")
-   *     .set("follow", ActionMakers.intentAction())
-   *     .get();
-   * 
- */ - public static final class Builder - extends AbstractDictionaryObject.AbstractBuilder - { - - protected Builder() {} - - /** - * Add an action handler for the given verb. - * Calling this multiple times results in - * multiple action handlers. - * @param verb String - * @param iri String - * @return Builder - */ - public Builder set(String verb, String iri) { - return set( - verb, - LinkValue.SimpleLinkValue.make(iri)); - } - - @Override - public Builder set(String key, LinkValue x) { - return super.link(key, x); - } - - @Override - public Builder set(String key, Supplier x) { - return super.link(key, x); - } - - /** - * Get the built ActionsValue instance - * @return ParametersValue - * @see com.google.common.base.Supplier#get() - **/ - public ActionsValue get() { - return new ActionsValue(this); - } - - } - - private ActionsValue(Builder builder) { - super(builder); - } - - /** - * Get all Action Handlers associated with the given verb. - * @param verb String - * @return java.util.Iterable - */ - public Iterable get(String verb) { - return super.getIterable(verb); - } - - /** - * Get all Action Handlers associated with the given verb - * that satisfy the given filter - * @param verb String - * @param filter Predicate - * @return java.util.Iterable - */ - public Iterable get( - String verb, - Predicate filter) { - return super.getIterable(verb, filter); - } - - /** - * Get all Action Handlers associated with the given verb, - * transformed using the given Transform function - * @param verb String - * @param transform Function - * @return java.util.Iterable - */ - public Iterable get( - String verb, - Function transform) { - return super.getIterable(verb, transform); - } - - /** - * Get all Action Handlers associated with the given verb, - * filtered using the given Predicate and transformed - * using the given Transform function. - * @param verb String - * @param filter Predicate - * @param transform Function - * @return java.util.Iterable - */ - public Iterable get( - String verb, - Predicate filter, - Function transform) { - return super.getIterable(verb, filter, transform); - } - - /** - * True if there is at least one Action Handler associated - * with the given verb - * @param verb String - * @return boolean - */ - public boolean hasAtLeastOne(String verb) { - return super.hasAtLeastOne(verb); - } - - // Java serialization support - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - implements Serializable { - private static final long serialVersionUID = -1975376657749952999L; - private ImmutableMap map; - SerializedForm(ActionsValue obj) { - ImmutableMap.Builder builder = - ImmutableMap.builder(); - for (String key : obj) - builder.put(key, obj.get(key)); - this.map = builder.build(); - } - @SuppressWarnings("unchecked") - Object readResolve() - throws java.io.ObjectStreamException { - ActionsValue.Builder builder = - Makers.actions(); - for (Map.Entry entry : map.entrySet()) { - Iterable list = (Iterable) entry.getValue(); - for (LinkValue link : list) - builder.set(entry.getKey(), link); - } - return builder.get(); - } - } -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/Activity.java b/core/src/main/java/com/ibm/common/activitystreams/Activity.java deleted file mode 100755 index 5405410..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/Activity.java +++ /dev/null @@ -1,853 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams; - -import static com.google.common.base.Preconditions.checkArgument; -import static java.lang.Math.floor; -import static java.lang.Math.ceil; -import static com.ibm.common.activitystreams.Makers.linkValue; -import static com.ibm.common.activitystreams.Makers.type; - -import java.io.ObjectStreamException; -import java.io.Serializable; - -import com.google.common.base.Predicate; -import com.google.common.base.Supplier; - - -/** - * An Activity Streams 2.0 Activity - * - *

Creating an Activity:

- *
- *   import static com.ibm.common.activitystreams.Makers.activity;
- *   import static com.ibm.common.activitystreams.Makers.object;
- *   ...
- * 
- *   Activity activity = activity()
- *     .actor("acct:joe@example.org")
- *     .verb("post")
- *     .object(object().content("This is a note"))
- *     .get();
- * 
- * - *

Consuming an Activity:

- *
- *   Activity activity = IO.makeDefault().readAsActivity(...);
- *   
- *   System.out.println(activity.verbAsString());   
- *   ASObject actor = activity.firstActor();
- *   ASObject object = activity.firstObject();
- * 
- * - * @author james - * @version $Revision: 1.0 $ - */ -public class Activity - extends ASObject - implements Serializable { - - public static enum Audience { - /** - * Primary public audience - **/ - TO, - /** - * Primary private audience - **/ - BTO, - /** - * Secondary public audience - **/ - CC, - /** - * Secondary private audience - **/ - BCC, - /** - * Public origin - **/ - FROM, - /** - * Private origin - **/ - BFROM; - - private final String label; - - private Audience() { - this.label = name().toLowerCase(); - } - - /** - * Returns the "from" target(s) - * @return java.util.Iterable<LinkValue>*/ - private Iterable get( - Activity activity) { - return activity.links(label); - } - - private Iterable get( - Activity activity, - Predicate filter) { - return activity.links(label, filter); - } - - private LinkValue first(Activity activity) { - return activity.firstLink(label); - } - - private LinkValue firstMatching( - Activity activity, - Predicate test) { - return activity.firstMatchingLink(label, test); - } - } - - public static enum Status { - /** The Activity is tentatively scheduled to begin **/ - TENTATIVE, - /** The Activity is scheduled to begin **/ - PENDING, - /** The Activity has been completed **/ - COMPLETED, - /** The Activity has been canceled or aborted **/ - CANCELED, - /** The Activity is currently active **/ - ACTIVE, - /** The Activity has been voided. **/ - VOIDED, - OTHER - } - - /** - * - * Builder for concrete Activity object instances. - * - * @author james - * @version $Revision: 1.0 $ - */ - public static final class Builder - extends Activity.AbstractBuilder { - - /** - * Get the built Activity object - * @return Activity - * @see com.google.common.base.Supplier#get() - */ - public Activity get() { - return new Activity(this); - } - - } - - /** - * Ensures that the priority value is within the acceptable range (0.0-1.0) - * @param d double - * @return double - */ - private static double checkPriority(double d) { - checkArgument(floor(d) >= 0 && ceil(d) >= 1); - return d; - } - - /** - * Abstract builder for Activity classes. This is defined this way - * to make it easier to build extensions of the Activity class. - * @author james - * @version $Revision: 1.0 $ - */ - @SuppressWarnings("unchecked") - public static abstract class AbstractBuilder -
> - extends ASObject.AbstractBuilder { - - /** - * Set the Activity status property. - * @param status Status - * @return B - */ - public B status(Status status) { - if (status != null) - set("status", status); - return (B)this; - } - - /** - * Mark the status of this activity as being "voided" - * @return B - */ - public B voided() { - return status(Status.VOIDED); - } - - /** - * Mark the status of this activity as being "tentative" - * @return B - */ - public B tentative() { - return status(Status.TENTATIVE); - } - - /** - * Mark the status of this activity as being "pending" - * @return B - */ - public B pending() { - return status(Status.PENDING); - } - - /** - * Mark the status of this activity as being "active" - * @return B - */ - public B active() { - return status(Status.ACTIVE); - } - - /** - * Mark the status of this activity as being "canceled" - * @return B - */ - public B canceled() { - return status(Status.CANCELED); - } - - /** - * Mark the status of this activity as being "completed" - * @return B - */ - public B completed() { - return status(Status.COMPLETED); - } - - /** - * Set the verb for this activity - * @param iri String - * @return B - */ - public B verb(String iri) { - set("verb", type(iri)); - return (B)this; - } - - /** - * Set the verb for this activity - * @param tv TypeValue - * @return B - */ - public B verb(TypeValue tv) { - set("verb", tv); - return (B)this; - } - - /** - * Set the verb for this activity - * @param tv Supplier - * @return B - */ - public B verb(Supplier tv) { - return verb(tv.get()); - } - - /** - * Set a participant that indirectly contributed to the activity. - * @param url String - * @return B - **/ - public B participant(String url, String... urls) { - if (url != null) - link("participant", linkValue(url)); - if (urls != null) - for (String u : urls) - link("participant", linkValue(u)); - return (B)this; - } - - /** - * Set a participant that indirectly contributed to the activity - * @param link LinkValue - * @return B - */ - public B participant(LinkValue link, LinkValue... links) { - if (link != null) - link("participant", link); - if (links != null) - for (LinkValue l : links) - link("participant", l); - return (B)this; - } - - /** - * Set a participant that indirectly contributed to the activity - * @param link Supplier - * @return B - */ - public B participant(Supplier link) { - return link("participant", link.get()); - } - - /** - * Set the instrument used to complete the activity - * @param url String - * @return B - */ - public B instrument(String url, String... urls) { - if (url != null) - link("instrument", linkValue(url)); - if (urls != null) - for (String u : urls) - link("instument", linkValue(u)); - return (B)this; - } - - /** - * Set the instrument used to complete the activity - * @param link LinkValue - * @return B - */ - public B instrument(LinkValue link, LinkValue... links) { - if (link != null) - link("instrument", link); - if (links != null) - for (LinkValue l : links) - link("instrument", l); - return (B)this; - } - - /** - * Set the instrument used to complete the activity - * @param link Supplier - * @return B - */ - public B instrument(Supplier link) { - return link("instrument", link.get()); - } - - /** - * Set the primary actor/agent for this activity - * @param url String - * @return B - */ - public B actor(String url, String... urls) { - if (url != null) - link("actor", linkValue(url)); - if (urls != null) - for (String u : urls) - link("actor", linkValue(u)); - return (B)this; - } - - /** - * Set the primary actor/agent for this activity - * @param link LinkValue - * @return B - */ - public B actor(LinkValue link, LinkValue... links) { - if (link != null) - link("actor", link); - if (links != null) - for (LinkValue l : links) - link("actor", l); - return (B)this; - } - - /** - * Set the actor - * @param link Supplier - * @return B - */ - public B actor(Supplier link) { - return link("actor", link.get()); - } - - /** - * Set the direct object of this activity (the object that has been - * or will be acted upon) - * @param url String - * @return B - */ - public B object(String url, String... urls) { - if (url != null) - link("object", linkValue(url)); - if (urls != null) - for (String u : urls) - link("object", linkValue(u)); - return (B)this; - } - - /** - * Set the direct object of this activity (the object that has been - * or will be acted upon) - * @param link LinkValue - * @return B - */ - public B object(LinkValue link, LinkValue... links) { - if (link != null) - link("object", link); - if (links != null) - for (LinkValue l : links) - link("object", l); - return (B)this; - } - - /** - * Set the direct object of this activity (the object that has been - * or will be acted upon) - * @param link Supplier - * @return B - */ - public B object(Supplier link) { - return link("object", link.get()); - } - - /** - * Set an object that is indirectly affected by the activity - * @param url String - * @return B - */ - public B target(String url, String... urls) { - if (url != null) - link("target", linkValue(url)); - if (urls != null) - for (String u : urls) - link("target", linkValue(u)); - return (B)this; - } - - /** - * Set an object that is indirectly affected by the activity - * @param link LinkValue - * @return B - */ - public B target(LinkValue link, LinkValue... links) { - if (link != null) - link("target", link); - if (links != null) - for (LinkValue l : links) - link("target", l); - return (B)this; - } - - /** - * Set an object that is indirectly affected by the activity - * @param link Supplier - * @return B - */ - public B target(Supplier link) { - return link("target", link.get()); - } - - /** - * Set a URI that describes the result of this activity - * @param url String - * @return B - */ - public B result(String url, String... urls) { - if (url != null) - link("result", linkValue(url)); - if (urls != null) - for (String u : urls) - link("result", linkValue(u)); - return (B)this; - } - - /** - * Set an object that describes the result of this activity - * @param link LinkValue - * @return B - */ - public B result(LinkValue link, LinkValue... links) { - if (link != null) - link("result", link); - if (links != null) - for (LinkValue l : links) - link("result", l); - return (B)this; - } - - /** - * Set an object that describes the result of this activity - * @param link Supplier - * @return B - */ - public B result(Supplier link) { - return link("result", link.get()); - } - - /** - * Set the audience for this activity - * @param audience - * @param url - * @param urls - * @return B - */ - public B audience(Audience audience, String url, String... urls) { - link(audience.label, linkValue(url)); - for (String u : urls) - link(audience.label, u); - return (B)this; - } - - /** - * Set the audience for this activity - * @param audience - * @param link - * @param links - * @return B - */ - public B audience(Audience audience, LinkValue link, LinkValue... links) { - link(audience.label, link); - for (LinkValue lv : links) - link(audience.label, lv); - return (B)this; - } - - /** - * Set the audience for this activity - * @param audience - * @param link - * @return B - */ - public B audience(Audience audience, Supplier link) { - return link(audience.label, link); - } - - /** - * Set the priority as value in the range 0.00 to 1.00. - * Value will be checked to ensure it is within the valid range. - * The value SHOULD be limited to two decimal places but the - * number of decimals will not be checked. - * @param d double - * @return B - * @throws IllegalArgumentException if the value is not within 0.00-1.00 - */ - public B priority(double d) { - return set("priority", checkPriority(d)); - } - } - - Activity(Activity.AbstractBuilder builder) { - super(builder); - } - - /** - * returns the verb as TypeValue object - * @return T - **/ - public T verb() { - return this.get("verb"); - } - - /** - * Returns the verb as a string - * @return String - **/ - public String verbString() { - return typeValueAsString("verb"); - } - - /** - * Return the participant(s) - * @return java.util.Iterable<LinkValue> - **/ - public Iterable participant() { - return links("participant"); - } - - /** - * Return the matching participant(s) - * @param filter - * @return java.util.Iterable - */ - public Iterable participant(Predicate filter) { - return links("participant", filter); - } - - /** - * Return the first paticipant - * @return LinkValue - */ - public LinkValue firstParticipant() { - return firstLink("participant"); - } - - /** - * Return the first matching participant - * @param test - * @return LinkValue - */ - public LinkValue firstMatchingParticipant(Predicate test) { - return firstMatchingLink("participan", test); - } - - /** - * Return the instrument(s) - * @return java.util.Iterable<LinkValue> - **/ - public Iterable instrument() { - return links("instrument"); - } - - /** - * Return the matching instrument(s) - * @param filter - * @return java.util.Iterable - */ - public Iterable instrument(Predicate filter) { - return links("instrument", filter); - } - - /** - * Return the first instrument - * @return LinkValue - */ - public LinkValue firstInstrument() { - return firstLink("instrument"); - } - - /** - * Return the first matching instrument - * @param test - * @return LinkValue - */ - public LinkValue firstMatchingInstrument(Predicate test) { - return firstMatchingLink("instrument", test); - } - - /** - * Returns the actor(s) - * @return java.util.Iterable<LinkValue> - **/ - public Iterable actor() { - return links("actor"); - } - - /** - * Return the matching actor(s) - * @param filter - * @return java.util.Iterable - */ - public Iterable actor(Predicate filter) { - return links("actor", filter); - } - - /** - * Return the first actor - * @return LinkValue - */ - public LinkValue firstActor() { - return firstLink("actor"); - } - - /** - * Return the first matching actor - * @param test - * @return LinkValue - */ - public LinkValue firstMatchingActor(Predicate test) { - return firstMatchingLink("actor", test); - } - - /** - * Returns the object(s) - * @return java.util.Iterable<LinkValue> - **/ - public Iterable object() { - return links("object"); - } - - /** - * Return the matching object(s) - * @param filter - * @return java.util.Iterable - */ - public Iterable object(Predicate filter) { - return links("object", filter); - } - - /** - * Return the first object - * @return LinkValue - */ - public LinkValue firstObject() { - return firstLink("object"); - } - - /** - * Return the first matching object - * @param test - * @return LinkValue - */ - public LinkValue firstMatchingObject(Predicate test) { - return firstMatchingLink("object", test); - } - - /** - * Returns the target(s) - * @return java.util.Iterable<LinkValue> - **/ - public Iterable target() { - return links("target"); - } - - /** - * Return the matching target(s) - * @param filter - * @return java.util.Iterable - */ - public Iterable target(Predicate filter) { - return links("target", filter); - } - - /** - * Return the first target - * @return LinkValue - */ - public LinkValue firstTarget() { - return firstLink("target"); - } - - /** - * Return the first matching target - * @param test - * @return LinkValue - */ - public LinkValue firstMatchingTarget(Predicate test) { - return firstMatchingLink("target", test); - } - - /** - * Returns the result(s) - * @return java.util.Iterable<LinkValue> - **/ - public Iterable result() { - return links("result"); - } - - /** - * Returns the matching result(s) - * @param filter - * @return java.util.Iterable<LinkValue> - */ - public Iterable result(Predicate filter) { - return links("result", filter); - } - - /** - * Return the first result - * @return LinkValue - */ - public LinkValue firstResult() { - return firstLink("result"); - } - - /** - * Return the first matching result - * @param test - * @return LinkValue - */ - public LinkValue firstMatchingResult(Predicate test) { - return firstMatchingLink("result", test); - } - - /** - * Returns the priority. - * @return double - * @throws IllegalArgumentException if the priority is not within - * the range 0.00-1.00 - **/ - public double priority() { - return checkPriority(getDouble("priority")); - } - - /** - * Return the audience for this activity - * @param audience - * @return java.util.Iterable<LinkValue> - */ - public Iterable audience( - Audience audience) { - return audience.get(this); - } - - /** - * Return the audience for this activity - * @param audience - * @param filter - * @return java.util.Iterable<LinkValue> - */ - public Iterable audience( - Audience audience, - Predicate filter) { - return audience.get(this,filter); - } - - /** - * Return the first audience for this activity - * @param audience - * @return LinkValue - */ - public LinkValue firstAudience(Audience audience) { - return audience.first(this); - } - - /** - * Return the first matching audience for this activity - * @param audience - * @param test - * @return LinkValue - */ - public LinkValue firstMatchingAudience( - Audience audience, - Predicate test) { - return audience.firstMatching(this, test); - } - - /** - * Return the status of this activity - * @return Status - */ - public Status status() { - return get("status"); - } - - // Java Serialization Support - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - protected SerializedForm(Activity obj) { - super(obj); - } - private static final long serialVersionUID = -1975376657749952999L; - protected Activity.Builder builder() { - return Makers.activity(); - } - Object readResolve() throws ObjectStreamException { - return super.doReadResolve(); - } - } -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/Collection.java b/core/src/main/java/com/ibm/common/activitystreams/Collection.java deleted file mode 100755 index 83abf21..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/Collection.java +++ /dev/null @@ -1,540 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.ibm.common.activitystreams.Makers.linkValue; -import static com.google.common.collect.Iterables.filter; - -import java.io.ObjectStreamException; -import java.io.Serializable; -import java.util.concurrent.TimeUnit; - -import org.joda.time.DateTime; -import org.joda.time.ReadableDuration; -import org.joda.time.ReadablePeriod; - -import com.google.common.base.Predicate; -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; - -/** - * - * An Activity Streams collection object - * - *
- *   import static com.ibm.common.activitystreams.Makers.collection;
- *   import static com.ibm.common.activitystreams.Makers.object;
- *   ...
- * 
- *   Collection collection = collection()
- *     .items(object()...)
- *     .items(object()...)
- *     .get();
- * 
- * - * @author james - * @version $Revision: 1.0 $ - */ -@SuppressWarnings("unchecked") -public class Collection - extends ASObject - implements Serializable { - - /** Standardized Paging Links **/ - public static enum Page { - /** - * Reference to the first page in the logical set - **/ - FIRST, - /** - * Reference to the next page in the logical set - **/ - NEXT, - /** - * Reference to the final page in the logical set - * **/ - LAST, - /** - * Reference to the previous page in the logical set - **/ - PREVIOUS, - /** - * Reference to the previous page in the logical set (treated as an alias for "previous") - * @deprecated Use Page.PREVIOUS instead - **/ - PREV, - /** - * Reference to the page containing the most recently published/updated - * items in the logical set - **/ - CURRENT, - /** - * Reference to this page - **/ - SELF; - - private final String label; - private Page() { - this.label = name().toLowerCase(); - } - - private String checkPrev(Collection col, String or) { - if (this == PREVIOUS) { - if (!col.has(label) && col.has(PREV.label)) - return PREV.label; - } else if (this == PREV) { - if (!col.has(label) && col.has(PREVIOUS.label)) - return PREVIOUS.label; - } - return or; - } - - private Iterable links(Collection col) { - return col.links(checkPrev(col,label)); - } - - private Iterable links( - Collection col, - Predicate filter) { - return col.links(checkPrev(col,label), filter); - } - - private LinkValue first(Collection col) { - return col.firstLink(checkPrev(col,label)); - } - - private LinkValue firstMatching( - Collection col, - Predicate filter) { - return col.firstMatchingLink(checkPrev(col,label), filter); - } - } - - /** - * @author james - * @version $Revision: 1.0 $ - */ - public static final class Builder - extends Collection.AbstractBuilder { - - /** - * Method create. - * @return Collection */ - protected Collection create() { - return new Collection(this); - } - - } - - /** - * @author james - * @version $Revision: 1.0 $ - */ - public static abstract class AbstractBuilder -
> - extends ASObject.AbstractBuilder { - - protected final ImmutableList.Builder list = - ImmutableList.builder(); - - /** - * Method create. - * @return A - **/ - protected abstract A create(); - - @Override - public B set(String key, Object value) { - if (key.equals("items")) { - if (value instanceof ArrayLinkValue) { - ArrayLinkValue alv = (ArrayLinkValue) value; - for (LinkValue lv : alv) { - list.add((ASObject)lv); - } - } else if (value instanceof ASObject) - list.add((ASObject) value); - return (B)this; - } else return super.set(key,value); - } - - - /** - * Method get. - * @return A - * @see com.google.common.base.Supplier#get() - **/ - public A get() { - super.set("items", list.build()); - return create(); - } - - /** - * Add items to this collection - * @param objs java.util.Iterable - * @return B - */ - public B items(Iterable objs) { - if (objs == null) - return (B)this; - for (ASObject obj : objs) - items(obj); - return (B)this; - } - - /** - * Add items to this collection - * @param obj ASObject The object to add - * @param objs ASObject[] Additional objects to add (vararg) - * @return B - **/ - public B items(ASObject obj, ASObject... objs) { - if (obj == null) - return (B)this; - list.add(obj); - if (objs != null) - for (ASObject o : objs) - list.add(o); - return (B)this; - } - - /** - * Add an item to this collection - * @param obj com.google.common.base.Supplier - * @return B - **/ - public B items(Supplier obj) { - if (obj == null) - return (B)this; - items(obj.get()); - return (B)this; - } - - /** - * Set the total number of items (must be non-negative) - * @param i int - * @return B - **/ - public B totalItems(int i) { - checkArgument(i >= 0); - set("totalItems", i); - return (B)this; - } - - /** - * Set the number of items per page (must be non-negative) - * @param i int - * @return B - **/ - public B itemsPerPage(int i) { - checkArgument(i >= 0); - set("itemsPerPage", i); - return (B)this; - } - - /** - * Set the starting index (must be non-negative) - * @param i int - * @return B - **/ - public B startIndex(int i) { - checkArgument(i >= 0); - set("startIndex", i); - return (B)this; - } - - /** - * Specify that the collection contains items updated after the specified time - * @param dt DateTime - * @return B - **/ - public B itemsAfter(DateTime dt) { - return _dt("itemsAfter", dt); - } - - /** - * Specify that the collection contains items updated after right now - * @return B - */ - public B itemsAfterNow() { - return _dtNow("itemsAfter"); - } - - /** - * Specify that the collection contains items updated a specific duration after now - * @param duration Duration - * @return B - */ - public B itemsAfterFromNow(ReadableDuration duration) { - return _dtFromNow("itemsAfter", duration); - } - - /** - * Specify that the collection contains items updated a specific period after now - * @param period - * @return B - */ - public B itemsAfterFromNow(ReadablePeriod period) { - return _dtFromNow("itemsAfter", period); - } - - /** - * Specify that the collection contains items updated a specific duration after now - * @param v long - * @param unit TimeUnit - * @return B - **/ - public B itemsAfterFromNow(long v, TimeUnit unit) { - return _dtFromNow("itemsAfter", v, unit); - } - - /** - * Specify that the collection contains items updated before a specific time - * @param dt DateTime - * @return B - **/ - public B itemsBefore(DateTime dt) { - return _dt("itemsBefore", dt); - } - - /** - * Specify that the collection contains items updated before now - * @return B - */ - public B itemsBeforeNow() { - return _dtNow("itemsBefore"); - } - - /** - * Specify that the collection contains items updated a specific duration - * before now - * @param duration Duration - * @return B - */ - public B itemsBeforeFromNow(ReadableDuration duration) { - return _dtFromNow("itemsBefore", duration); - } - - /** - * Specify that the collection contains items updated a specific period - * before now - * @param period - * @return B - */ - public B itemsBeforeFromNow(ReadablePeriod period) { - return _dtFromNow("itemsBefore", period); - } - - /** - * Method itemsBeforeFromNow. - * @param v long - * @param unit TimeUnit - * @return B - **/ - public B itemsBeforeFromNow(long v, TimeUnit unit) { - return _dtFromNow("itemsBefore", v, unit); - } - - /** - * Adds a paging link - *
-     *   Collection collection = Makers.collection()
-     *     .pageLink(Page.NEXT, "http://example.org")
-     *     .get();
-     * 
- * @param page - * @param url - * @return B - */ - public B pageLink(Page page, String url) { - return link(page.label, linkValue(url)); - } - - /** - * Adds a paging link - * @param page - * @param link - * @return B - */ - public B pageLink(Page page, LinkValue link) { - return link(page.label, link); - } - - /** - * Adds a paging link - * @param page - * @param link - * @return B - */ - public B pageLink(Page page, Supplier link) { - return link(page.label, link); - } - - } - - /** - * Constructor for Collection. - * @param builder Collection.AbstractBuilder - */ - Collection(Collection.AbstractBuilder builder) { - super(builder); - } - - /** - * Returns the total number of items - * @return int - **/ - public int totalItems() { - return getInt("totalItems"); - } - - /** - * If not null, indicates that the collection only contains items - * updated after the given instant - * @return DateTime - **/ - public DateTime itemsAfter() { - return this.getDateTime("itemsAfter"); - } - - /** - * If not null, indicates that the collection only contains items - * updated before the given instant - * @return DateTime - * */ - public DateTime itemsBefore() { - return this.getDateTime("itemsBefore"); - } - - /** - * Returns the number of items per page - * @return int - **/ - public int itemsPerPage() { - return this.getInt("itemsPerPage"); - } - - /** - * Returns the start index for this page - * @return int - **/ - public int startIndex() { - return this.getInt("startIndex"); - } - - /** - * Returns a listing of Paging links that - * exist on this collection - * @return Iterable<Page> - */ - public Iterable pages() { - ImmutableSet.Builder pages = - ImmutableSet.builder(); - for (Page page : Page.values()) - if (has(page.label)) - pages.add(page); - return pages.build(); - } - - /** - * Returns a listing of Paging LinkValues - * @param page Page The type of paging link to return - * @return Iterable<LinkValue> - */ - public Iterable pageLink( - Page page) { - return page.links(this); - } - - /** - * Returns a listing of Paging LinkValues - * @param page Page The type of paging link to return - * @param filter Predicate A filter - * @return Iterable<LinkValue> - */ - public Iterable pageLink( - Page page, - Predicate filter) { - return page.links(this,filter); - } - - /** - * Returns the first matching paging LinkValue - * @param page Page The type of paging link to return - * @return LinkValue - */ - public LinkValue firstPageLink( - Page page) { - return page.first(this); - } - - /** - * Returns the first matching paging LinkValue - * @param page Page the type of paging link to return - * @param test com.google.common.base.Predicate a filter - * @return LinkValue - */ - public LinkValue firstMatchingPageLink( - Page page, - Predicate test) { - return page.firstMatching(this,test); - } - - /** - * Returns the collection of items - * @return java.util.Iterable
- **/ - public Iterable items() { - return this.>get("items"); - } - - /** - * Returns a filtered collection of items - * @param filter com.google.common.base.Predicate filter - * @return java.util.Iterable - */ - public Iterable items( - Predicate filter) { - return filter(this.items(), filter); - } - - // Java Serialization Support - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - protected SerializedForm(Collection obj) { - super(obj); - } - private static final long serialVersionUID = -1975376657749952999L; - protected Collection.Builder builder() { - return Makers.collection(); - } - Object readResolve() throws ObjectStreamException { - return super.doReadResolve(); - } - } -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/IO.java b/core/src/main/java/com/ibm/common/activitystreams/IO.java deleted file mode 100755 index 6d213d7..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/IO.java +++ /dev/null @@ -1,629 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams; - -import java.io.InputStream; -import java.io.OutputStream; -import java.io.Reader; -import java.io.StringReader; -import java.io.StringWriter; -import java.io.Writer; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableSet; -import com.ibm.common.activitystreams.internal.Adapter; -import com.ibm.common.activitystreams.internal.GsonWrapper; -import com.ibm.common.activitystreams.internal.Schema; -import com.ibm.common.activitystreams.util.Module; - -/** - * The IO object is responsible for serializing and deserializing - * Activity Stream objects. Instances of IO should be created and - * defined statically. IO instances are threadsafe and immutable - * once created. - * - *

You can choose to use one of the default IO instances:

- * - *
- *   public static final IO io = IO.makeDefault();
- *   
- *   public static final IO prettyIo = IO.makeDefaultPrettyPrint();
- * 
- * - *

Or you can use the IO.Builder to construct and configure your - * own IO instance with custom adapters, object properties and - * type mappings:

- * - *
- *   import static 
- * 
- *   public static final IO io = 
- *   IO.make()
- *     .schema(
- *       Makers.makeSchema().map(
- *         Schema.object.template()
- *           .as("foo", Foo.class)))
- *     .adapter(Foo.class, new MyFooAdapter())
- *     .get();
- * 
- * - *

Once created, you can use IO instances to parse Activity Streams - * documents:

- * - *
- *  InputStream in = ...
- *  Activity activity = io.readAsActivity(in);
- * 
- * - *

Or can use the IO instance to serialize:

- * - *
- *   OutputStream out = ...
- *   Activity activity = ...
- *   activity.writeTo(out, io);
- * 
- * - * @author james - * @version $Revision: 1.0 $ - */ -public final class IO { - - /** - * Create a new IO.Builder - * @return Builder */ - public static Builder make() { - return new Builder(); - } - - /** - * Create a new IO.Builder that uses the given schema - * @param schema Schema - * @return IO - */ - public static IO makeWithSchema(Schema schema) { - return make().schema(schema).get(); - } - - /** - * Create a new IO.Builder that uses the given schema - * @param schema Supplier - * @return IO - */ - public static IO makeWithSchema(Supplier schema) { - return makeWithSchema(schema.get()); - } - - /** - * Make or return the default IO instance - * @return IO - **/ - public static IO makeDefault(Module... modules) { - IO.Builder builder = make(); - if (modules != null) - for (Module mod : modules) - builder.using(mod); - return builder.get(); - } - - /** - * Make or return a default IO instance with Pretty Print enabled - * @return IO - */ - public static IO makeDefaultPrettyPrint(Module... modules) { - IO.Builder builder = make().prettyPrint(); - if (modules != null) - for (Module mod : modules) - builder.using(mod); - return builder.get(); - } - - public static class Builder - implements Supplier { - - private final GsonWrapper.Builder inner = - GsonWrapper.make(); - private Schema schema; - private final ImmutableSet.Builder modules = - ImmutableSet.builder(); - - public Builder using(Module module) { - modules.add(module); - return this; - } - - /** - * Turn pretty print on or off - * @param on boolean - * @return Builder - **/ - public Builder prettyPrint(boolean on) { - inner.prettyPrint(on); - return this; - } - - /** - * Turn pretty print on - * @return Builder - **/ - public Builder prettyPrint() { - return prettyPrint(true); - } - - /** - * Add an adapter - * @param type Class - * @param adapter Adapter - * @return Builder - **/ - public Builder adapter( - Class type, - Adapter adapter) { - inner.adapter(type, adapter); - return this; - } - - /** - * Add an adapter - * @param type Class<? extends T> - * @return Builder - */ - public Builder adapter( - Class type) { - return adapter(type,null); - } - - /** - * Add an adapter - * @param type Class<? extends T> - * @return Builder - */ - public Builder hierarchicalAdapter( - Class type) { - return hierarchicalAdapter(type,null); - } - - /** - * Add an adapter. - * @param type Class - * @param adapter Adapter - * @param hier boolean - * @return Builder - **/ - public Builder hierarchicalAdapter( - Class type, - Adapter adapter) { - inner.adapter(type, adapter, true); - return this; - } - - /** - * Set the schema - * @param schema Schema - * @return Builder - **/ - public Builder schema(Schema schema) { - //inner.schema(schema); - this.schema = schema; - return this; - } - - /** - * Set the schema. - * @param schema Supplier - * @return Builder - **/ - public Builder schema(Supplier schema) { - return schema(schema.get()); - } - - public IO get() { - Iterable mods = modules.build(); - Schema schema = this.schema; - if (schema == null) { - Schema.Builder builder = Schema.make(); - for (Module mod : mods) - mod.apply(builder); - schema = builder.get(); - } - inner.schema(schema); - for (Module module : modules.build()) - module.apply(this, schema); - return new IO(this); - } - } - - private final GsonWrapper gson; - - protected IO(Builder builder) { - this.gson = - builder.inner.get(); - } - - /** - * Write the given object - * @param w Writable - * @return String - */ - public String write(Writable w) { - StringWriter sw = new StringWriter(); - w.writeTo(sw,this); - return sw.toString(); - } - - /** - * Asynchronously write the given object - * @param w - * @param executor - * @return java.util.concurrent.Future<String> - */ - public Future write( - final Writable w, - ExecutorService executor) { - return executor.submit( - new Callable() { - public String call() throws Exception { - return write(w); - } - } - ); - } - - /** - * Write the object to the given outputstream - * @param w Writable - * @param out OutputStream - */ - public void write(Writable w, OutputStream out) { - gson.write(w,out); - } - - /** - * Asychronously write the object to the given output stream - * @param w - * @param out - * @param executor - * @return java.util.concurrent.Future<?> - */ - public Future write( - final Writable w, - final OutputStream out, - ExecutorService executor) { - return executor.submit( - new Runnable() { - public void run() { - write(w, out); - } - } - ); - } - - /** - * Asychronously write the object to the given writer - * @param w - * @param out - * @param executor - * @return java.util.concurrent.Future<?> - */ - public Future write( - final Writable w, - final Writer out, - ExecutorService executor) { - return executor.submit( - new Runnable() { - public void run() { - write(w, out); - } - } - ); - } - - /** - * Write the object to the given writer - * @param w Writable - * @param out Writer - */ - public void write(Writable w, Writer out) { - gson.write(w,out); - } - - /** - * Asynchronously read the given input stream and - * return a parsed object of the given type - * @param in - * @param type - * @param executor - * @return java.util.concurrent.Future<A extends ASObject> - */ - public
Future readAs( - final InputStream in, - final Class type, - ExecutorService executor) { - return executor.submit( - new Callable() { - public A call() throws Exception { - return readAs(in, type); - } - } - ); - } - - /** - * Read the given input stream and return a parsed object - * of the given type - * @param in InputStream - * @param type Class - * @return A */ - public A readAs( - InputStream in, - Class type) { - return gson.readAs(in, type); - } - - /** - * Asynchronously read the given reader and return a parsed - * object of the given type - * @param in - * @param type - * @param executor - * @return java.util.concurrent.Future<A extends ASObject> - */ - public Future readAs( - final Reader in, - final Class type, - ExecutorService executor) { - return executor.submit( - new Callable() { - public A call() throws Exception { - return readAs(in, type); - } - } - ); - } - - /** - * Read the given reader and return a parsed object of the given type - * @param in Reader - * @param type Class - * @return A */ - public A readAs( - Reader in, - Class type) { - return gson.readAs(in, type); - } - - /** - * Asynchronously read the given string and return a parsed object of - * the given type - * @param in - * @param type - * @param executor - * @return java.util.concurrent.Future<A extends ASObject> - */ - public Future readAs( - final String in, - final Class type, - ExecutorService executor) { - return executor.submit( - new Callable() { - public A call() throws Exception { - return readAs(in, type); - } - } - ); - } - - /** - * Read the given string and return a parsed object of the given type - * @param in String - * @param type Class - * @return A - */ - public A readAs( - String in, - Class type) { - return readAs(new StringReader(in),type); - } - - /** - * Asynchronously read the given string - * @param in - * @param executor - * @return java.util.concurrent.Future<ASObject> - */ - public Future read(String in, ExecutorService executor) { - return read(new StringReader(in), executor); - } - - /** - * Read the given string - * @param in String - * @return ASObject - */ - public ASObject read(String in) { - return read(new StringReader(in)); - } - - /** - * Asynchronously read the given inputstream - * @param in - * @param executor - * @return java.util.concurrent.Future<ASObject> - */ - public Future read(InputStream in, ExecutorService executor) { - return readAs(in, ASObject.class, executor); - } - - /** - * Asynchronously read the given reader - * @param in - * @param executor - * @return java.util.concurrent.Future<ASObject> - */ - public Future read(Reader in, ExecutorService executor) { - return readAs(in, ASObject.class, executor); - } - - /** - * Read the given input stream. - * @param in InputStream - * @return ASObject - **/ - public ASObject read(InputStream in) { - return readAs(in, ASObject.class); - } - - /** - * Return the given input stream - * @param in InputStream - * @return A - */ - @SuppressWarnings("unchecked") - public A readAs(InputStream in) { - return (A)read(in); - } - - /** - * Read the given string as an Activity object - * @param in String - * @return Activity - */ - public Activity readAsActivity(String in) { - return readAsActivity(new StringReader(in)); - } - - /** - * Asynchronously read the given string as an Activity object - * @param in - * @param executor - * @return java.util.concurrent.Future<Activity> - */ - public Future readAsActivity(String in, ExecutorService executor) { - return readAsActivity(new StringReader(in), executor); - } - - /** - * Asynchronously read the given inputstream as an Activity object - * @param in - * @param executor - * @return java.util.concurrent.Future<Activity> - */ - public Future readAsActivity(InputStream in, ExecutorService executor) { - return readAs(in, Activity.class, executor); - } - - /** - * Asynchronously read the given reader as an Activity object - * @param in - * @param executor - * @return java.util.concurrent.Future<Activity> - */ - public Future readAsActivity(Reader in, ExecutorService executor) { - return readAs(in, Activity.class, executor); - } - - /** - * Asynchronously read the given string as a Collection object - * @param in - * @param executor - * @return java.util.concurrent.Future<Collection> - */ - public Future readAsCollection(String in, ExecutorService executor) { - return readAsCollection(new StringReader(in), executor); - } - - /** - * Asynchronously read the given input stream as a Collection object - * @param in - * @param executor - * @return java.util.concurrent.Future<Collection> - */ - public Future readAsCollection(InputStream in, ExecutorService executor) { - return readAs(in, Collection.class, executor); - } - - /** - * Asynchronously read the given reader as a Collection object - * @param in - * @param executor - * @return java.util.concurrent.Future<Collection> - */ - public Future readAsCollection(Reader in, ExecutorService executor) { - return readAs(in, Collection.class, executor); - } - - /** - * Read the given inputstream as an Activity. - * @param in InputStream - * @return Activity - **/ - public Activity readAsActivity(InputStream in) { - return readAs(in, Activity.class); - } - - /** - * Read the given string as a Collection. - * @param in InputStream - * @return Collection - **/ - public Collection readAsCollection(String in) { - return readAsCollection(new StringReader(in)); - } - - /** - * Read the given inputstream as a Collection. - * @param in InputStream - * @return Collection - **/ - public Collection readAsCollection(InputStream in) { - return readAs(in, Collection.class); - } - - /** - * Read the given reader - * @param in - * @return ASObject - */ - public ASObject read(Reader in) { - return readAs(in, ASObject.class); - } - - /** - * Read the given reader as an Activity - * @param in Reader - * @return Activity - **/ - public Activity readAsActivity(Reader in) { - return readAs(in, Activity.class); - } - - /** - * Read the given reader as a Collection - * @param in Reader - * @return Collection - **/ - public Collection readAsCollection(Reader in) { - return readAs(in, Collection.class); - } -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/LinkValue.java b/core/src/main/java/com/ibm/common/activitystreams/LinkValue.java deleted file mode 100755 index 347c89c..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/LinkValue.java +++ /dev/null @@ -1,330 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams; - -import static com.google.common.base.Preconditions.checkArgument; - -import java.io.Serializable; -import java.util.Iterator; - -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableList; -import com.ibm.common.activitystreams.util.AbstractWritable; - -/** - * An Activity Streams 2.0 Link Value. - * - *

In Actvity Streams 2.0, Link Values can take one of three possible - * forms:

- * - *
    - *
  • A String containing an absolute IRI
  • - *
  • An Activity String object
  • - *
  • An Array containing a mix of Strings or Objects
  • - *
- * - *

For instance, the following are all valid examples of Link Values:

- * - *
- *   {
- *     "actor": "acct:joe@example.org"
- *   }
- *   
- *   {
- *     "actor": {
- *       "objectType": "person",
- *       "id": "acct:sally@example.org"
- *     }
- *   }
- *   
- *   {
- *     "actor": [
- *       "acct:joe@example.org",
- *       {
- *         "objectType": "person",
- *         "id": "acct:sally@example.org"
- *       }
- *     ]
- *   }
- * 
- * - *

The LinkValue interface provides a minimal abstraction over these - * value options. Developers will have to check the ValueType of the LinkValue - * (or do an instanceof check) in order to determine which kind of value - * they are working with.

- * - *
- *   Activity activity = ...;
- *   Iterable actors = activity.actor();
- *   for (LinkValue actor : actors) {
- *     switch(actor.valueType()) {
- *     case SIMPLE:
- *       SimpleLinkValue s = (SimpleLinkValue)actor;
- *       //...
- *       break;
- *     case OBJECT:
- *       ASObject obj = (ASObject)actor;
- *       //...
- *       break;
- *     }
- *   }
- * 
- * - *

Methods that return Iterable will never include an instance - * of ArrayLinkValue as one of the Iterable values

- * - * @author james - * @version $Revision: 1.0 $ - */ -public interface LinkValue - extends Writable, Serializable { - - /** - * Returns the LinkValue type - * @return ValueType - */ - ValueType valueType(); - - /** - * A "Simple Link Value" is a string with a relative or absolute - * URI or IRI value. - */ - public static final class SimpleLinkValue - extends AbstractWritable - implements LinkValue, Serializable { - - /** - * Creates a new builder - * @return Builder - **/ - public static Builder make() { - return new Builder(); - } - - /** - * Creates a new instance - * @param url String - * @return LinkValue - **/ - public static LinkValue make(String url) { - return new SimpleLinkValue.Builder().url(url).get(); - } - - public static final class Builder - extends AbstractWritable.AbstractWritableBuilder { - - private String iri; - - /** - * Set the url - * @param iri String - * @return Builder - **/ - public Builder url(String iri) { - this.iri = iri; - return this; - } - - /** - * Method get. - * @return SimpleLinkValue - * @see com.google.common.base.Supplier#get() - **/ - public SimpleLinkValue get() { - return new SimpleLinkValue(this); - } - } - - private final String iri; - - SimpleLinkValue(SimpleLinkValue.Builder builder) { - super(builder); - this.iri = builder.iri; - } - - /** - * Return the url - * @return String - */ - public String url() { - return iri; - } - - public String toString() { - return iri; - } - - public ValueType valueType() { - return ValueType.SIMPLE; - } - - // Java Serialization Support - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - implements Serializable { - private static final long serialVersionUID = -1975376657749952999L; - private String iri; - SerializedForm(SimpleLinkValue obj) { - this.iri = obj.iri; - } - Object readResolve() - throws java.io.ObjectStreamException { - return Makers.linkValue(iri); - } - } - - } - - /** - * An Array Link value is a JSON Array of one or more Simple or Object - * Link Values. Array Link Values MUST NOT contain nested arrays. - */ - public static final class ArrayLinkValue - extends AbstractWritable - implements Iterable, LinkValue, Serializable { - - /** - * Create a new builder - * @return ArrayLinkValue.Builder - **/ - public static ArrayLinkValue.Builder make() { - return new ArrayLinkValue.Builder(); - } - - public static class Builder - extends AbstractWritable.AbstractWritableBuilder { - - private final ImmutableList.Builder links = - ImmutableList.builder(); - - /** - * Add one or more items - * @param value String - * @param values String[] - * @return Builder */ - public Builder add(String value, String... values) { - if (value != null) - add(SimpleLinkValue.make(value)); - if (values != null) - for (String v : values) - add(SimpleLinkValue.make(v)); - return this; - } - - /** - * Add one or more link values - * @param links Iterable - * @return Builder */ - public Builder add(Iterable links) { - for (LinkValue l : links) - add(l); - return this; - } - - /** - * Add one or more link values - * @param values LinkValue[] - * @return Builder */ - public Builder add(LinkValue value, LinkValue... values) { - if (value != null) { - checkArgument(value.valueType() != ValueType.ARRAY); - links.add(value); - } - if (values != null) - for (LinkValue v : values) { - checkArgument(v.valueType() != ValueType.ARRAY); - links.add(v); - } - return this; - } - - /** - * Add a link value - * @param value Supplier - * @return Builder */ - public Builder add(Supplier value) { - LinkValue val = value.get(); - checkArgument(val.valueType() != ValueType.ARRAY); - links.add(val); - return this; - } - - /** - * Method get. - * @return ArrayLinkValue - * @see com.google.common.base.Supplier#get() - **/ - public ArrayLinkValue get() { - return new ArrayLinkValue(this); - } - - } - - private final ImmutableList links; - - ArrayLinkValue(ArrayLinkValue.Builder builder) { - super(builder); - this.links = builder.links.build(); - } - - /** - * Method iterator. - * @return Iterator - * @see java.lang.Iterable#iterator() - **/ - public Iterator iterator() { - return links.iterator(); - } - - public String toString() { - return links.toString(); - } - - public ValueType valueType() { - return ValueType.ARRAY; - } - - // Java Serialization Support - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - implements Serializable { - private static final long serialVersionUID = -1975376657749952999L; - private ImmutableList list; - SerializedForm(ArrayLinkValue obj) { - this.list = obj.links; - } - Object readResolve() - throws java.io.ObjectStreamException { - return Makers.linkValues().add(list); - } - } - - } -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/Makers.java b/core/src/main/java/com/ibm/common/activitystreams/Makers.java deleted file mode 100755 index f0daf2b..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/Makers.java +++ /dev/null @@ -1,174 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams; - -import java.util.Map; - -import static com.google.common.collect.ImmutableMap.copyOf; -import com.ibm.common.activitystreams.internal.Schema; - -/** - * Utility class for creating Makers for all of the various objects. - */ -public final class Makers { - - private Makers() {} - - /** - * Make a new ActionsValue.Builder - * @return ParametersValue.Builder - **/ - public static ActionsValue.Builder actions() { - return new ActionsValue.Builder(); - } - - /** - * Make a new Schema.Builder - * @return Schema.Builder - */ - public static Schema.Builder schema() { - return Schema.make(); - } - - /** - * Make a new IO.builder - * @return IO.Builder - **/ - public static IO.Builder io() { - return IO.make(); - } - - /** - * Make a new Activity.Builder - * @return Activity.Builder - **/ - public static Activity.Builder activity() { - return new Activity.Builder(); - } - - /** - * Make a new Collection.Builder - * @return Collection.Builder - **/ - public static Collection.Builder collection() { - return new Collection.Builder(); - } - - /** - * Make a new ASObject.Builder - * @return ASObject.Builder - **/ - public static ASObject.Builder object() { - return new ASObject.Builder(); - } - - /** - * Make a new ASObject.Builder with a specific objectType - * @param type String - * @return ASObject.Builder - **/ - public static ASObject.Builder object(String type) { - return object().objectType(type); - } - - /** - * Return an Object from the given Map - * @param map - * @return ASObject - */ - public static ASObject objectFrom(Map map) { - ASObject.Builder builder = object(); - for (Map.Entry entry : copyOf(map).entrySet()) - builder.set(entry.getKey(), entry.getValue()); - return builder.get(); - } - - /** - * Make a new ASObject.Builder - * @param type TypeValue - * @return ASObject.Builder - **/ - public static ASObject.Builder object(TypeValue type) { - return object().objectType(type); - } - - /** - * Make a new TypeValue - * @param iri String - * @return TypeValue - **/ - public static TypeValue type(String iri) { - return TypeValue.SimpleTypeValue.make(iri); - } - - /** - * Make a new LinkValue - * @param iri String - * @return LinkValue - **/ - public static LinkValue linkValue(String iri) { - return LinkValue.SimpleLinkValue.make(iri); - } - - /** - * Make a new ArrayLinkValue.Builder - * @return LinkValue.ArrayLinkValue.Builder - **/ - public static LinkValue.ArrayLinkValue.Builder linkValues() { - return LinkValue.ArrayLinkValue.make(); - } - - /** - * Make a new MapNLV.Builder - * @return NLV.MapNLV.Builder - **/ - public static NLV.MapNLV.Builder nlv() { - return NLV.MapNLV.make(); - } - - /** - * Make a new SimpleNLV value - * @param val String - * @return NLV.SimpleNLV - **/ - public static NLV.SimpleNLV nlv(String val) { - return NLV.SimpleNLV.make(val); - } - - /** - * Make a new verb ASObject.Builder - * @param id String - * @return ASObject.Builder - */ - public static ASObject.Builder verb(String id) { - return object("verb").id(id); - } - - /** - * Make a new objectType ASObject.Builder - * @param id String - * @return ASObject.Builder - */ - public static ASObject.Builder objectType(String id) { - return object("objectType").id(id); - } -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/NLV.java b/core/src/main/java/com/ibm/common/activitystreams/NLV.java deleted file mode 100755 index 979016c..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/NLV.java +++ /dev/null @@ -1,278 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams; - -import static com.google.common.collect.Maps.difference; - -import java.io.Serializable; -import java.util.Iterator; -import java.util.Map; - -import com.google.common.base.Objects; -import com.google.common.collect.ImmutableMap; -import com.ibm.common.activitystreams.util.AbstractWritable; - - -/** - * An Activity Streams 2.0 Natural Language Value... - * - *

The value is either a simple string or an object - * with multiple Language-Tag keys and values...

- * - *
- *   {
- *     "objectType": "note",
- *     "displayName": {
- *       "en": "My Title In English",
- *       "fr": "Mon titre en français"
- *     }
- *   }
- * 
- * - *

- * ASObject obj = ... - * System.out.println(obj.displayNameString("en")); - * System.out.println(obj.displayNameString("fr")); - * - * NLV nlv = obj.displayName(); - * switch(nlv.valueType()) { - * case SIMPLE: - * SimpleNLV s = (SimpleNLV)nlv; - * ... - * break; - * case OBJECT: - * MapNLV m = (MapNLV)nlv; - * ... - * break; - * } - *

- * - * @author james - * @version $Revision: 1.0 $ - */ -public interface NLV - extends Writable, Serializable { - - /** - * Returns the value type. Either ValueType.SIMPLE or ValueType.OBJECT - * @return ValueType - */ - ValueType valueType(); - - public static final class SimpleNLV - extends AbstractWritable - implements NLV, Serializable { - - /** - * Create a new builder - * @return Builder */ - public static Builder make() { - return new Builder(); - } - - /** - * Create a new instance - * @param value String - * @return SimpleNLV */ - public static SimpleNLV make(String value) { - return make().value(value).get(); - } - - private final String val; - - SimpleNLV(Builder builder) { - super(builder); - this.val = builder.val; - } - - /** - * Return the value - * @return String - **/ - public String value() { - return val; - } - - @Override - public int hashCode() { - return Objects.hashCode(val); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - SimpleNLV other = (SimpleNLV) obj; - return Objects.equal(val, other.val); - } - - public String toString() { - return val; - } - - public static final class Builder - extends AbstractWritable.AbstractWritableBuilder { - - private String val; - - public Builder value(String val) { - this.val = val; - return this; - } - - public SimpleNLV get() { - return new SimpleNLV(this); - } - - } - - public ValueType valueType() { - return ValueType.SIMPLE; - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - implements Serializable { - private static final long serialVersionUID = -1975376657749952999L; - private String value; - SerializedForm(SimpleNLV obj) { - this.value = obj.val; - } - Object readResolve() - throws java.io.ObjectStreamException { - return Makers.nlv(value); - } - } - - } - - public static final class MapNLV - extends AbstractWritable - implements NLV, Iterable { - - public static Builder make() { - return new Builder(); - } - - private final ImmutableMap vals; - private transient int hash = 1; - - MapNLV(Builder builder) { - super(builder); - this.vals = builder.vals.build(); - } - - public String value(String lang) { - return vals.get(lang); - } - - public boolean has(String lang) { - return vals.containsKey(lang); - } - - @Override - public int hashCode() { - if (hash == 1) - hash = Objects.hashCode(vals); - return hash; - } - - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - MapNLV other = (MapNLV) obj; - return - difference(vals, other.vals) - .areEqual(); - - } - - public Iterator iterator() { - return vals.keySet().iterator(); - } - - public static final class Builder - extends AbstractWritable.AbstractWritableBuilder { - - private final ImmutableMap.Builder vals = - ImmutableMap.builder(); - - public Builder from(MapNLV other, String lang) { - for (String l : other) - if (!l.equalsIgnoreCase(lang)) - set(l, other.value(l)); - return this; - } - - public Builder set(String lang, String val) { - vals.put(lang,val); - return this; - } - - public MapNLV get() { - return new MapNLV(this); - } - - } - - public ValueType valueType() { - return ValueType.OBJECT; - } - - public Map toMap() { - return vals; - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - implements Serializable { - private static final long serialVersionUID = -1975376657749952999L; - private ImmutableMap map; - SerializedForm(MapNLV obj) { - this.map = obj.vals; - } - Object readResolve() - throws java.io.ObjectStreamException { - NLV.MapNLV.Builder builder = - Makers.nlv(); - for (Map.Entry entry : map.entrySet()) - builder.set(entry.getKey(), entry.getValue()); - return builder.get(); - } - } - } - -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/TypeValue.java b/core/src/main/java/com/ibm/common/activitystreams/TypeValue.java deleted file mode 100755 index dffcfc6..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/TypeValue.java +++ /dev/null @@ -1,179 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams; - -import java.io.Serializable; -import java.util.Objects; - -import com.ibm.common.activitystreams.util.AbstractWritable; - -/** - * In Activity Streams 2.0, the "objectType" and "verb" properties, - * as well as several other properties, are defined as "Type Values". - * A "Type Value" can be either a simple token string, an absolute - * IRI string, or an ASObject. - * - *
- *   {
- *     "verb": "post"
- *   }
- *   
- *   {
- *     "verb": "urn:example:verbs:foo"
- *   }
- *   
- *   {
- *     "verb": {
- *       "id": "urn:example:verbs:foo",
- *       "displayName": "Foo"
- *     }
- *   }
- * 
- * - *

The TypeValue interface provides a minimal abstraction - * over these possible values. Developers should check valueType - * to determine which type of TypeValue they are working with.

- * - *
- *   Activity activity = ...
- *   TypeValue tv = activity.verb();
- *   
- *   System.out.println(tv.id());
- *   
- *   switch(tv.valueType()) {
- *   case SIMPLE:
- *     SimpleTypeValue s = (SimpleTypeValue)tv;
- *     ...
- *     break;
- *   case OBJECT:
- *     ASObject o (ASObject)tv;
- *     ...
- *     break;
- *   }
- * 
- * - * @author james - * @version $Revision: 1.0 $ - */ -public interface TypeValue - extends Writable, Serializable { - - /** - * Return the type value identifier - * @return String - */ - String id(); - - ValueType valueType(); - - public static final class SimpleTypeValue - extends AbstractWritable - implements TypeValue, Serializable { - - public static Builder make() { - return new SimpleTypeValue.Builder(); - } - - public static TypeValue make(String url) { - return make().url(url).get(); - } - - public static final class Builder - extends AbstractWritable.AbstractWritableBuilder { - - private String iri; - - /** - * Set the url - * @param iri String - * @return Builder - **/ - public Builder url(String iri) { - this.iri = iri; - return this; - } - - public SimpleTypeValue get() { - return new SimpleTypeValue(this); - } - - } - - private final String iri; - - SimpleTypeValue(SimpleTypeValue.Builder builder) { - super(builder); - this.iri = builder.iri; - } - - @Override - public int hashCode() { - return Objects.hash(iri); - } - - @Override - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - SimpleTypeValue other = (SimpleTypeValue) obj; - return Objects.equals(iri,other.iri); - } - - /** - * Return the type value identifier - * @return String - * @see com.ibm.common.activitystreams.TypeValue#id() */ - public String id() { - return iri; - } - - public String toString() { - return iri; - } - - public ValueType valueType() { - return ValueType.SIMPLE; - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - implements Serializable { - private static final long serialVersionUID = -1975376657749952999L; - private String iri; - SerializedForm(SimpleTypeValue obj) { - this.iri = obj.iri; - } - Object readResolve() - throws java.io.ObjectStreamException { - return Makers.type(iri); - } - } - } - -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/Writable.java b/core/src/main/java/com/ibm/common/activitystreams/Writable.java deleted file mode 100755 index 816f5bf..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/Writable.java +++ /dev/null @@ -1,98 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams; - -import java.io.OutputStream; -import java.io.Writer; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -/** - * Base interface for all objects that serialize to IO object instances - * @author james - * @version $Revision: 1.0 $ - */ -public interface Writable { - - /** - * Write the object to the output stream using the default IO instance - * @param out OutputStream - */ - void writeTo(OutputStream out); - - /** - * Asynchronously write the object to the output stream using the - * default IO instance - * @param out - * @param executor - * @return Future<?> - */ - Future writeTo(OutputStream out, ExecutorService executor); - - /** - * Write the object to the Writer using the default IO instance - * @param out Writer - */ - void writeTo(Writer out); - - /** - * Asynchronously write the object to the writer using the default IO instance - * @param out - * @param executor - * @return Future<?> - */ - Future writeTo(Writer out, ExecutorService executor); - - /** - * Write the object to the output stream using the given IO instance - * @param out OutputStream - * @param io IO - */ - void writeTo(OutputStream out, IO io); - - /** - * Asynchronously write the object to the output stream using the given - * IO instance. - * @param out - * @param io - * @param executor - * @return Future<?> - */ - Future writeTo(OutputStream out, IO io, ExecutorService executor); - - /** - * Write the object to the writer using the given IO instance - * @param out Writer - * @param io IO - */ - void writeTo(Writer out, IO io); - - /** - * Asynchronously write the object to the writer using the given IO instance - * @param out - * @param io - * @param executor - * @return Future<?> - */ - Future writeTo(Writer out, IO io, ExecutorService executor); - -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/internal/ASObjectAdapter.java b/core/src/main/java/com/ibm/common/activitystreams/internal/ASObjectAdapter.java deleted file mode 100755 index 348fe79..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/internal/ASObjectAdapter.java +++ /dev/null @@ -1,323 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.internal; - - -import static com.google.common.collect.ImmutableList.builder; -import static com.ibm.common.activitystreams.Makers.activity; -import static com.ibm.common.activitystreams.Makers.collection; -import static com.ibm.common.activitystreams.Makers.object; - -import java.lang.reflect.Type; -import java.util.Map.Entry; - -import com.google.common.base.Converter; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSet; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.ibm.common.activitystreams.ASObject; -import com.ibm.common.activitystreams.Activity; -import com.ibm.common.activitystreams.Collection; -import com.ibm.common.activitystreams.LinkValue; -import com.ibm.common.activitystreams.Makers; -import com.ibm.common.activitystreams.TypeValue; - -/** - * @author james - * @version $Revision: 1.0 $ - */ -public class ASObjectAdapter - extends Adapter { - - private final Schema schema; - - protected Schema schema() { - return schema; - } - - /** - * Constructor for ASObjectAdapter. - * @param schema Schema - */ - protected ASObjectAdapter(Schema schema) { - this.schema = schema; - } - - /** - * Method serialize. - * @param obj ASObject - * @param type Type - * @param context JsonSerializationContext - - * @return JsonElement */ - public final JsonElement serialize( - ASObject obj, - Type type, - JsonSerializationContext context) { - JsonObject el = - new JsonObject(); - for (String key : obj) { - Object val = obj.get(key); - if (val != null) { - el.add( - key, - context.serialize( - val, - val.getClass())); - } - } - return el; - - } - - private static final ImmutableSet knownTypes = - ImmutableSet.of( - Collection.class, - Activity.class); - - protected boolean knowsType(Type type) { - return knownTypes.contains(type); - } - - protected ASObject.AbstractBuilder builderFor(Type type) { - if (type == Collection.class) - return collection(); - else if (type == Activity.class) - return activity(); - else return null; - } - - protected Model modelFor(Type type) { - if (type == Collection.class) - return schema.forObjectClassOrType( - Collection.Builder.class, - "collection"); - else if (type == Activity.class) - return schema.forObjectClassOrType( - Activity.Builder.class, - "activity"); - else return null; - } - - /** - * Method deserialize. - * @param element JsonElement - * @param type Type - * @param context JsonDeserializationContext - * @return ASObject - * @throws JsonParseException - * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) - **/ - public final ASObject deserialize( - JsonElement element, - Type type, - JsonDeserializationContext context) - throws JsonParseException { - - JsonObject obj = (JsonObject)element; - ASObject.AbstractBuilder builder = null; - Model propMap = null; - TypeValue tv = null; - - if (knowsType(type)) { - builder = builderFor(type); - propMap = modelFor(type); - } else { - if (obj.has("objectType")) { - tv = context.deserialize( - obj.get("objectType"), - TypeValue.class); - @SuppressWarnings("rawtypes") - Class _class = - schema.builderForObjectTypeOrClass(tv.id(), (Class)type); - if (_class != null) { - propMap = schema.forObjectClassOrType(_class, tv.id()); - if (!_class.isInterface()) { - try { - builder = _class.getConstructor(String.class).newInstance(tv.id()); - } catch (Throwable t) { - try { - builder = _class.newInstance(); - builder.set("objectType", tv); - } catch (Throwable t2) { - builder = Makers.object(tv); - } - } - } else - builder = Makers.object(tv); - } else { - builder = Makers.object(tv); - propMap = schema.forObjectClassOrType( - ASObject.Builder.class, tv.id()); - } - } else { - if (obj.has("verb") && - (obj.has("actor") || - obj.has("object") || - obj.has("target"))) { - builder = activity(); - propMap = schema.forObjectClassOrType( - Activity.Builder.class, "activity"); - } else if (obj.has("items")) { - builder = collection(); - propMap = schema.forObjectClassOrType( - Collection.Builder.class, - "collection"); - } else { - @SuppressWarnings("rawtypes") - Class _class = - schema.builderFor((Class)type); - if (_class != null) { - if (!_class.isInterface()) { - try { - builder = _class.newInstance(); - } catch (Throwable t) { - builder = object(); - } - } else builder = object(); - } - if (builder == null) - builder = object(); // anonymous - propMap = schema.forObjectClass(builder.getClass()); - propMap = propMap != null ? - propMap : - schema.forObjectClass( - ASObject.Builder.class); - } - } - } - - for (Entry entry : obj.entrySet()) { - String name = entry.getKey(); - if (name.equalsIgnoreCase("objectType")) continue; - Class _class = propMap.get(name); - JsonElement val = entry.getValue(); - if (val.isJsonPrimitive()) - builder.set( - name, - _class != null ? - context.deserialize(val,_class) : - primConverter.convert(val.getAsJsonPrimitive())); - else if (val.isJsonArray()) { - builder.set( - name, - LinkValue.class.isAssignableFrom(_class!=null?_class:Object.class) ? - context.deserialize(val, LinkValue.class) : - convert( - val.getAsJsonArray(), - _class, - context, - builder())); - } else if (val.isJsonObject()) - builder.set( - name, - context.deserialize( - val, - propMap.has(name) ? - propMap.get(name): - ASObject.class)); - } - return builder.get(); - - } - - /** - * Method convert. - * @param arr JsonArray - * @param _class Class - * @param context JsonDeserializationContext - * @param list ImmutableList.Builder - * @return ImmutableList - */ - private ImmutableList convert( - JsonArray arr, - Class _class, - JsonDeserializationContext context, - ImmutableList.Builder list) { - processArray(arr, _class, context, list); - return list.build(); - } - - /** - * Method processArray. - * @param arr JsonArray - * @param _class Class - * @param context JsonDeserializationContext - * @param list ImmutableList.Builder - */ - private void processArray( - JsonArray arr, - Class _class, - JsonDeserializationContext context, - ImmutableList.Builder list) { - for (JsonElement mem : arr) { - if (mem.isJsonPrimitive()) - list.add( - _class != null ? - context.deserialize(mem,_class) : - primConverter.convert( - mem.getAsJsonPrimitive())); - else if (mem.isJsonObject()) - list.add( - context.deserialize( - mem, - _class != null ? - _class : - ASObject.class)); - else if (mem.isJsonArray()) - list.add( - convert( - mem.getAsJsonArray(), - _class, - context, - builder())); - } - } - - public static final Converter primConverter = - new Converter() { - @Override - protected JsonPrimitive doBackward(Object a) { - if (a instanceof Boolean) - return new JsonPrimitive((Boolean)a); - else if (a instanceof Number) - return new JsonPrimitive((Number)a); - else - return new JsonPrimitive(a.toString()); - } - @Override - protected Object doForward(JsonPrimitive b) { - if (b.isBoolean()) - return b.getAsBoolean(); - else if (b.isNumber()) - return b.getAsNumber(); - else - return b.getAsString(); - } - }; -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/internal/Adapters.java b/core/src/main/java/com/ibm/common/activitystreams/internal/Adapters.java deleted file mode 100755 index d7cf209..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/internal/Adapters.java +++ /dev/null @@ -1,336 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.internal; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.collect.Iterables.getFirst; -import static com.google.common.collect.Iterables.size; - -import static com.ibm.common.activitystreams.Makers.actions; -import static com.ibm.common.activitystreams.Makers.linkValues; -import static com.ibm.common.activitystreams.internal.ASObjectAdapter.primConverter; - -import java.lang.reflect.Type; -import java.util.Date; -import java.util.Map; - -import org.joda.time.DateTime; -import org.joda.time.Duration; -import org.joda.time.Interval; -import org.joda.time.Period; -import org.joda.time.format.ISODateTimeFormat; - -import com.google.common.base.Optional; -import com.google.common.base.Throwables; -import com.google.common.collect.BoundType; -import com.google.common.collect.ImmutableTable; -import com.google.common.collect.Range; -import com.google.common.collect.Table; -import com.google.common.net.MediaType; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonElement; -import com.google.gson.JsonArray; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.google.gson.internal.LazilyParsedNumber; -import com.ibm.common.activitystreams.ASObject; -import com.ibm.common.activitystreams.ActionsValue; -import com.ibm.common.activitystreams.LinkValue; -import com.ibm.common.activitystreams.util.AbstractDictionaryObjectAdapter; - -/** - * @author james - * @version $Revision: 1.0 $ - */ -final class Adapters { - - private Adapters() {} - - /** - * Method forEnum. - * @param _enumClass Class - * @return EnumAdapter - */ - static >EnumAdapter forEnum(Class _enumClass) { - return new EnumAdapter(_enumClass); - } - - /** - * Method forEnum. - * @param _enumClass Class - * @param or E - * @return EnumAdapter - */ - static >EnumAdapter forEnum(Class _enumClass, E or) { - return new EnumAdapter(_enumClass,or); - } - - static final Adapter NLV = - new NaturalLanguageValueAdapter(); - - static final Adapter ACTIONS = - new AbstractDictionaryObjectAdapter - (LinkValue.class) { - public JsonElement serialize( - ActionsValue actions, - Type type, - JsonSerializationContext context) { - JsonObject obj = new JsonObject(); - for (String verb : actions) { - Iterable links = - actions.get(verb); - obj.add( - verb, - context.serialize( - size(links) == 1 ? // if there's only one, serialize just 1 - getFirst(links,null) : // otherwise, serialize the list - linkValues().add(links).get(), - LinkValue.class)); - } - return obj; - } - @Override - protected ActionsValue.Builder builder() { - return actions(); - } - }; - - static final Adapter> ITERABLE = - new Adapter>() { - - public JsonElement serialize( - Iterable i, - Type type, - JsonSerializationContext context) { - JsonArray ary = new JsonArray(); - for (Object obj : i) - ary.add(context.serialize(obj, obj.getClass())); - return ary; - } - - public Iterable deserialize(JsonElement arg0, Type arg1, - JsonDeserializationContext arg2) throws JsonParseException { - return null; // handled elsewhere - } - - }; - - static final Adapter DATE = - new SimpleAdapter() { - protected String serialize(Date t) { - return ISODateTimeFormat.dateTime().print(new DateTime(t)); - } - public Date apply(String v) { - return DateTime.parse(v).toDate(); - } - }; - - static final Adapter DATETIME = - new SimpleAdapter() { - protected String serialize(DateTime t) { - return ISODateTimeFormat.dateTime().print(t); - } - public DateTime apply(String v) { - return DateTime.parse(v); - } - }; - - static final Adapter DURATION = - new SimpleAdapter() { - public Duration apply(String v) { - return Duration.parse(v); - } - }; - - static final Adapter PERIOD = - new SimpleAdapter() { - public Period apply(String v) { - return Period.parse(v); - } - }; - - static final Adapter INTERVAL = - new SimpleAdapter() { - public Interval apply(String v) { - return Interval.parse(v); - } - }; - - static final Adapter MIMETYPE = - new SimpleAdapter() { - public MediaType apply(String v) { - return MediaType.parse(v); - } - }; - - static final MultimapAdapter MULTIMAP = - new MultimapAdapter(); - - - static final Adapter> RANGE = - new Adapter>() { - - public JsonElement serialize( - Range src, - Type typeOfSrc, - JsonSerializationContext context) { - JsonObject el = new JsonObject(); - el.add("lower", makeBound(src.lowerBoundType(),src.lowerEndpoint(),context)); - el.add("upper", makeBound(src.upperBoundType(),src.upperEndpoint(),context)); - return el; - } - - private JsonElement makeBound( - BoundType type, - Object val, - JsonSerializationContext context) { - JsonObject obj = new JsonObject(); - obj.add("type", context.serialize(type.name().toLowerCase())); - obj.add("endpoint", context.serialize(val)); - return obj; - } - - @SuppressWarnings("rawtypes") - public Range deserialize( - JsonElement json, - Type typeOfT, - JsonDeserializationContext context) - throws JsonParseException { - checkArgument(json.isJsonObject()); - try { - JsonObject obj = json.getAsJsonObject(); - JsonObject upper = obj.getAsJsonObject("upper"); - JsonObject lower = obj.getAsJsonObject("lower"); - BoundType ubt = bt(upper.getAsJsonPrimitive("type")); - BoundType lbt = bt(lower.getAsJsonPrimitive("type")); - Object ub = des(upper.get("endpoint"),context); - Object lb = des(lower.get("endpoint"),context); - return Range.range((Comparable)lb, lbt, (Comparable)ub, ubt); - } catch (Throwable t) { - throw Throwables.propagate(t); - } - } - - private Object des(JsonElement val, JsonDeserializationContext context) { - if (val.isJsonArray()) - return MultimapAdapter.arraydes(val.getAsJsonArray(), context); - else if (val.isJsonObject()) - return context.deserialize(val, ASObject.class); - else if (val.isJsonPrimitive()) { - Object v = primConverter.convert(val.getAsJsonPrimitive()); - if (v instanceof LazilyParsedNumber) - v = new LazilyParsedNumberComparable((LazilyParsedNumber) v); - return v; - } - else - return null; - } - - private BoundType bt(JsonPrimitive p) { - try { - return BoundType.valueOf(p.toString()); - } catch (Throwable t) { - return BoundType.CLOSED; - } - } - }; - - static final Adapter> OPTIONAL = - new Adapter>() { - public JsonElement serialize( - Optional src, - Type typeOfSrc, - JsonSerializationContext context) { - return context.serialize(src.orNull()); - } - public Optional deserialize( - JsonElement json, - Type typeOfT, - JsonDeserializationContext context) - throws JsonParseException { - return null; - } - }; - - static final Adapter> TABLE = - new Adapter>() { - - public JsonElement serialize( - Table src, - Type typeOfSrc, - JsonSerializationContext context) { - - JsonObject obj = new JsonObject(); - for (Table.Cell cell : src.cellSet()) { - String r = cell.getRowKey().toString(); - String c = cell.getColumnKey().toString(); - JsonObject rowobj = null; - if (!obj.has(r)) { - rowobj = new JsonObject(); - obj.add(r, rowobj); - } else { - rowobj = obj.getAsJsonObject(r); - } - Object val = cell.getValue(); - if (val != null) - rowobj.add(c, context.serialize(val,val.getClass())); - } - - return obj; - } - - public Table deserialize( - JsonElement json, - Type typeOfT, - JsonDeserializationContext context) - throws JsonParseException { - ImmutableTable.Builder table = - ImmutableTable.builder(); - checkArgument(json.isJsonObject()); - JsonObject obj = json.getAsJsonObject(); - for (Map.Entry rowentry : obj.entrySet()) { - String row = rowentry.getKey(); - JsonElement cell = rowentry.getValue(); - checkArgument(cell.isJsonObject()); - for (Map.Entry cellentry : cell.getAsJsonObject().entrySet()) { - String ckey = cellentry.getKey(); - JsonElement val = cellentry.getValue(); - Object desval = null; - if (val.isJsonArray()) - desval = MultimapAdapter.arraydes(val.getAsJsonArray(),context); - else if (val.isJsonObject()) - desval = context.deserialize(val, ASObject.class); - else if (val.isJsonPrimitive()) - desval = primConverter.convert(val.getAsJsonPrimitive()); - if (desval != null) - table.put(row,ckey,desval); - } - } - return table.build(); - } - - }; -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/internal/EnumAdapter.java b/core/src/main/java/com/ibm/common/activitystreams/internal/EnumAdapter.java deleted file mode 100755 index c200757..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/internal/EnumAdapter.java +++ /dev/null @@ -1,128 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.internal; -import static com.google.common.base.Enums.stringConverter; -import static com.google.common.base.Preconditions.checkArgument; -import static com.ibm.common.activitystreams.util.Converters.stringConverter; -import static com.ibm.common.activitystreams.util.Converters.toLowerConverter; -import static com.ibm.common.activitystreams.util.Converters.toUpperConverter; - -import java.lang.reflect.Type; - -import com.google.common.base.Converter; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonElement; -import com.google.gson.JsonParseException; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; - -/** - * @author james - * @version $Revision: 1.0 $ - */ -public final class EnumAdapter> - extends Adapter { - - protected static final Converter toLower = - toLowerConverter(); - protected static final Converter toUpper = - toUpperConverter(); - - private final Converter des; - private final Converter ser; - /** - * Constructor for EnumAdapter. - * @param _enumClass Class - */ - public EnumAdapter(Class _enumClass) { - this(_enumClass, stringConverter(_enumClass)); - } - - /** - * Constructor for EnumAdapter - - - * @param _enumClass Class - * @param or E - */ - public EnumAdapter(Class _enumClass, E or) { - this(_enumClass, stringConverter(_enumClass,or)); - } - - /** - * Constructor for EnumAdapter. - * @param _enumClass Class - - * @param c Converter - */ - public EnumAdapter( - Class _enumClass, - Converter c) { - super(); - this.des = toUpper.andThen(c); - this.ser = c.reverse().andThen(toLower); - } - - /** - * Method serialize. - * @param src E - * @param typeOfSrc Type - * @param context JsonSerializationContext - * @return JsonElement - */ - public JsonElement serialize( - E src, - Type typeOfSrc, - JsonSerializationContext context) { - return context.serialize(ser.convert(src)); - } - - /** - * Method deserialize. - * @param json JsonElement - * @param typeOfT Type - * @param context JsonDeserializationContext - * @return E - * @throws JsonParseException - * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) - */ - public E deserialize( - JsonElement json, - Type typeOfT, - JsonDeserializationContext context) - throws JsonParseException { - checkArgument(json.isJsonPrimitive()); - JsonPrimitive jp = json.getAsJsonPrimitive(); - checkArgument(jp.isString()); - return des.convert(jp.getAsString()); - } - - /** - * Method convert. - * @param s String - * @return E - */ - protected E convert(String s) { - return des.convert(s); - } - -} \ No newline at end of file diff --git a/core/src/main/java/com/ibm/common/activitystreams/internal/GsonWrapper.java b/core/src/main/java/com/ibm/common/activitystreams/internal/GsonWrapper.java deleted file mode 100755 index 1f786bd..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/internal/GsonWrapper.java +++ /dev/null @@ -1,341 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.internal; - -import static com.google.gson.internal.bind.TypeAdapters.NUMBER; -import static com.ibm.common.activitystreams.internal.Adapters.DATE; -import static com.ibm.common.activitystreams.internal.Adapters.DATETIME; -import static com.ibm.common.activitystreams.internal.Adapters.NLV; -import static com.ibm.common.activitystreams.internal.Adapters.TABLE; -import static com.ibm.common.activitystreams.internal.Adapters.OPTIONAL; -import static com.ibm.common.activitystreams.internal.Adapters.ACTIONS; -import static com.ibm.common.activitystreams.internal.Adapters.DURATION; -import static com.ibm.common.activitystreams.internal.Adapters.INTERVAL; -import static com.ibm.common.activitystreams.internal.Adapters.ITERABLE; -import static com.ibm.common.activitystreams.internal.Adapters.MIMETYPE; -import static com.ibm.common.activitystreams.internal.Adapters.MULTIMAP; -import static com.ibm.common.activitystreams.internal.Adapters.RANGE; -import static com.ibm.common.activitystreams.internal.Adapters.PERIOD; -import static com.ibm.common.activitystreams.internal.Adapters.forEnum; - -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.Reader; -import java.io.StringWriter; -import java.io.Writer; -import java.util.Date; - -import org.joda.time.DateTime; -import org.joda.time.ReadableDuration; -import org.joda.time.ReadableInterval; -import org.joda.time.ReadablePeriod; - -import com.google.common.base.Optional; -import com.google.common.base.Supplier; -import com.google.common.base.Throwables; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Multimap; -import com.google.common.collect.Range; -import com.google.common.collect.Table; -import com.google.common.net.MediaType; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.internal.LazilyParsedNumber; -import com.ibm.common.activitystreams.ASObject; -import com.ibm.common.activitystreams.ActionsValue; -import com.ibm.common.activitystreams.Activity; -import com.ibm.common.activitystreams.Collection; -import com.ibm.common.activitystreams.LinkValue; -import com.ibm.common.activitystreams.NLV; -import com.ibm.common.activitystreams.TypeValue; -import com.ibm.common.activitystreams.Writable; - -/** - * @author james - * @version $Revision: 1.0 $ - */ -public final class GsonWrapper { - - /** - * Method make. - - * @return Builder */ - public static final Builder make() { - return new Builder(); - } - - /** - * @author james - * @version $Revision: 1.0 $ - */ - public static final class Builder - implements Supplier { - - private String charset = "UTF-8"; - private boolean pretty; - private Schema schema = null; // default - private ImmutableList.Builder> adapters = - ImmutableList.builder(); - - /** - * Method charset. - * @param charset String - - * @return Builder */ - public Builder charset(String charset) { - this.charset = charset; - return this; - } - - /** - * Method schema. - * @param schema Schema - - * @return Builder */ - public Builder schema(Schema schema) { - this.schema = schema; - return this; - } - - /** - * Method adapter. - * @param type Class - * @param adapter Adapter - - * @return Builder */ - public Builder adapter( - Class type, - Adapter adapter) { - return adapter(type,adapter,false); - } - - /** - * Method adapter. - * @param type Class - * @param adapter Adapter - * @param hier boolean - - * @return Builder */ - public Builder adapter( - Class type, - Adapter adapter, - boolean hier) { - adapters.add(new AdapterEntry(type,adapter,hier)); - return this; - } - - /** - * Method prettyPrint. - * @param on boolean - - * @return Builder */ - public Builder prettyPrint(boolean on) { - this.pretty = on; - return this; - } - - /** - * Method prettyPrint. - - * @return Builder */ - public Builder prettyPrint() { - return prettyPrint(true); - } - - /** - * Method get. - - - * @return GsonWrapper * @see com.google.common.base.Supplier#get() */ - public GsonWrapper get() { - return new GsonWrapper(this); - } - - } - - /** - * @author james - * @version $Revision: 1.0 $ - */ - private final static class AdapterEntry { - private final Class type; - private final Adapter adapter; - private final boolean hier; - /** - * Constructor for AdapterEntry. - * @param type Class - * @param adapter Adapter - * @param hier boolean - */ - AdapterEntry( - Class type, - Adapter adapter, - boolean hier) { - this.type = type; - this.adapter = adapter; - this.hier = hier; - } - } - - private final Gson gson; - private final String charset; - - /** - * Constructor for GsonWrapper. - * @param builder Builder - */ - protected GsonWrapper(Builder builder) { - Schema schema = - builder.schema != null ? - builder.schema : - Schema.make().get(); - ASObjectAdapter base = - new ASObjectAdapter(schema); - GsonBuilder b = initGsonBuilder( - builder, - schema, - base, - builder.adapters.build()); - if (builder.pretty) - b.setPrettyPrinting(); - this.gson = b.create(); - this.charset = builder.charset; - } - - /** - * Method initGsonBuilder. - * @param builder Builder - - * @return GsonBuilder */ - private static GsonBuilder initGsonBuilder( - Builder builder, - Schema schema, - ASObjectAdapter base, - Iterable> adapters) { - - GsonBuilder gson = new GsonBuilder() - .registerTypeHierarchyAdapter(TypeValue.class, new TypeValueAdapter(schema)) - .registerTypeHierarchyAdapter(LinkValue.class, new LinkValueAdapter(schema)) - .registerTypeHierarchyAdapter(Iterable.class, ITERABLE) - .registerTypeHierarchyAdapter(ASObject.class, base) - .registerTypeHierarchyAdapter(Collection.class, base) - .registerTypeHierarchyAdapter(Activity.class, base) - .registerTypeHierarchyAdapter(NLV.class, NLV) - .registerTypeHierarchyAdapter(ActionsValue.class, ACTIONS) - .registerTypeHierarchyAdapter(Optional.class, OPTIONAL) - .registerTypeHierarchyAdapter(Range.class, RANGE) - .registerTypeHierarchyAdapter(Table.class, TABLE) - .registerTypeHierarchyAdapter(LazilyParsedNumber.class, NUMBER) - .registerTypeHierarchyAdapter(LazilyParsedNumberComparable.class, NUMBER) - .registerTypeHierarchyAdapter(ReadableDuration.class, DURATION) - .registerTypeHierarchyAdapter(ReadablePeriod.class, PERIOD) - .registerTypeHierarchyAdapter(ReadableInterval.class, INTERVAL) - .registerTypeAdapter( - Activity.Status.class, - forEnum( - Activity.Status.class, - Activity.Status.OTHER)) - .registerTypeAdapter(Date.class, DATE) - .registerTypeAdapter(DateTime.class, DATETIME) - .registerTypeAdapter(MediaType.class, MIMETYPE) - .registerTypeHierarchyAdapter(Multimap.class, MULTIMAP); - - for (AdapterEntry entry : adapters) { - if (entry.hier) - gson.registerTypeHierarchyAdapter( - entry.type, - entry.adapter!=null ? - entry.adapter : base); - else - gson.registerTypeAdapter( - entry.type, - entry.adapter!=null ? - entry.adapter:base); - } - - return gson; - - } - - /** - * Method write. - * @param w Writable - * @param out OutputStream - */ - public void write(Writable w, OutputStream out) { - try { - OutputStreamWriter wout = - new OutputStreamWriter(out, charset); - gson.toJson(w,wout); - wout.flush(); - } catch (Throwable t) { - throw Throwables.propagate(t); - } - } - - /** - * Method write. - * @param w Writable - * @param out Writer - */ - public void write(Writable w, Writer out) { - gson.toJson(w,out); - } - - /** - * Method write. - * @param w Writable - - * @return String */ - public String write(Writable w) { - StringWriter sw = - new StringWriter(); - write(w,sw); - return sw.toString(); - } - - /** - * Method readAs. - * @param in InputStream - * @param type Class - - * @return A */ - public A readAs(InputStream in, Class type) { - try { - return readAs(new InputStreamReader(in, charset), type); - } catch (Throwable t) { - throw Throwables.propagate(t); - } - } - - /** - * Method readAs. - * @param in Reader - * @param type Class - - * @return A */ - public A readAs(Reader in, Class type) { - return (A)gson.fromJson(in, type); - } -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/internal/LazilyParsedNumberComparable.java b/core/src/main/java/com/ibm/common/activitystreams/internal/LazilyParsedNumberComparable.java deleted file mode 100755 index b07c039..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/internal/LazilyParsedNumberComparable.java +++ /dev/null @@ -1,128 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.internal; - -import java.io.ObjectStreamException; - -import com.google.common.primitives.Longs; -import com.google.gson.internal.LazilyParsedNumber; - -/** - */ -final class LazilyParsedNumberComparable - extends Number - implements Comparable { - private static final long serialVersionUID = 761729254455440231L; - private final LazilyParsedNumber inner; - /** - * Constructor for LazilyParsedNumberComparable. - * @param inner LazilyParsedNumber - */ - public LazilyParsedNumberComparable(LazilyParsedNumber inner) { - this.inner = inner; - } - /** - * Method compareTo. - * @param o Number - * @return int - */ - public int compareTo(Number o) { - return Longs.compare(inner.longValue(), o.longValue()); - } - - /** - * Method doubleValue. - * @return double - */ - public double doubleValue() { - return inner.doubleValue(); - } - - /** - * Method floatValue. - * @return float - */ - public float floatValue() { - return inner.floatValue(); - } - - /** - * Method intValue. - * @return int - */ - public int intValue() { - return inner.intValue(); - } - - /** - * Method longValue. - * @return long - */ - public long longValue() { - return inner.longValue(); - } - /** - * Method byteValue. - * @return byte - */ - public byte byteValue() { - return inner.byteValue(); - } - /** - * Method shortValue. - * @return short - */ - public short shortValue() { - return inner.shortValue(); - } - /** - * Method equals. - * @param obj Object - * @return boolean - */ - public boolean equals(Object obj) { - return inner.equals(obj); - } - /** - * Method hashCode. - * @return int - */ - public int hashCode() { - return inner.hashCode(); - } - /** - * Method toString. - * @return String - */ - public String toString() { - return inner.toString(); - } - - /** - * Method writeReplace. - * @return Object - * @throws ObjectStreamException - */ - private Object writeReplace() throws ObjectStreamException { - return inner; - } -} \ No newline at end of file diff --git a/core/src/main/java/com/ibm/common/activitystreams/internal/LinkValueAdapter.java b/core/src/main/java/com/ibm/common/activitystreams/internal/LinkValueAdapter.java deleted file mode 100755 index d47375a..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/internal/LinkValueAdapter.java +++ /dev/null @@ -1,136 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.internal; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.ibm.common.activitystreams.Makers.linkValue; -import static com.ibm.common.activitystreams.Makers.linkValues; - -import java.lang.reflect.Type; - -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.ibm.common.activitystreams.ASObject; -import com.ibm.common.activitystreams.LinkValue; -import com.ibm.common.activitystreams.LinkValue.SimpleLinkValue; -import com.ibm.common.activitystreams.TypeValue; - -/** - * @author james - * @version $Revision: 1.0 $ - */ -final class LinkValueAdapter - extends Adapter { - - private final Schema schema; - - /** - * Constructor for LinkValueAdapter. - * @param schema Schema - */ - public LinkValueAdapter(Schema schema) { - this.schema = schema; - } - - /** - * Method serialize. - * @param value LinkValue - * @param type Type - * @param context JsonSerializationContext - - * @return JsonElement */ - public JsonElement serialize( - LinkValue value, - Type type, - JsonSerializationContext context) { - switch(value.valueType()) { - case SIMPLE: - LinkValue.SimpleLinkValue simple = (SimpleLinkValue) value; - return context.serialize(simple.url(), String.class); - case ARRAY: - return context.serialize(value, Iterable.class); - case OBJECT: - return context.serialize(value, ASObject.class); - default: - throw new IllegalArgumentException(); - } - } - - /** - * Method deserialize. - * @param el JsonElement - * @param type Type - * @param context JsonDeserializationContext - - - - * @return LinkValue * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) */ - public LinkValue deserialize( - JsonElement el, - Type type, - JsonDeserializationContext context) - throws JsonParseException { - checkArgument( - el.isJsonArray() || - el.isJsonObject() || - el.isJsonPrimitive()); - if (el.isJsonArray()) { - LinkValue.ArrayLinkValue.Builder builder = - linkValues(); - for (JsonElement aryel : el.getAsJsonArray()) - builder.add( - context.deserialize( - aryel, - LinkValue.class)); - return builder.get(); - } else if (el.isJsonObject()) { - JsonObject obj = el.getAsJsonObject(); - if (obj.has("objectType")) { - TypeValue tv = - context.deserialize( - obj.get("objectType"), - TypeValue.class); - Model pMap = - schema.forObjectType(tv.id()); - return context.deserialize( - el, - pMap != null && pMap.type() != null ? - pMap.type() : - ASObject.class); - } else { - return context.deserialize( - el, - ASObject.class); - } - } else { - JsonPrimitive prim = - el.getAsJsonPrimitive(); - checkArgument(prim.isString()); - return linkValue(prim.getAsString()); - } - } - -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/internal/Model.java b/core/src/main/java/com/ibm/common/activitystreams/internal/Model.java deleted file mode 100755 index fb79d52..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/internal/Model.java +++ /dev/null @@ -1,529 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.internal; -import java.lang.reflect.Type; -import java.util.Map; - -import org.joda.time.DateTime; -import org.joda.time.ReadableDuration; -import org.joda.time.ReadableInterval; -import org.joda.time.ReadablePeriod; - -import com.google.common.base.Objects; -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import com.ibm.common.activitystreams.ASObject; -import com.ibm.common.activitystreams.ASObject.AbstractBuilder; -import com.ibm.common.activitystreams.LinkValue; -import com.ibm.common.activitystreams.NLV; -import com.ibm.common.activitystreams.TypeValue; - -/** - * @author james - * @version $Revision: 1.0 $ - */ -public final class Model { - - final String parent; - final ImmutableMap properties; - final Type _default; - final Type _type; - final Type _builder; - private transient Schema schema; - - /** - * Method schema. - * @param schema Schema - */ - protected void schema(Schema schema) { - this.schema = schema; - } - - /** - * Method make. - - * @return Builder */ - public static Builder make() { - return make(null); - } - - /** - * Method make. - * @param parent String - - * @return Builder */ - public static Builder make(String parent) { - return new Builder().parent(parent); - } - - /** - * @author james - * @version $Revision: 1.0 $ - */ - public static final class Builder - implements Supplier { - - Type _type; - Type _builder; - Type _default = null; - String parent = null; - - final Map properties = - Maps.newHashMap(); - - Builder() {} - - /** - * Constructor for Builder. - * @param template PropertyMap - */ - Builder(Model template) { - this.parent = template.parent; - this._default = template._default; - this._type = template._type; - this._builder = template._builder; - this.properties.putAll(template.properties); - } - - /** - * Method withDefault. - * @param _default Class - * @return Builder - **/ - public Builder withDefault(Class _default) { - this._default = _default; - return this; - } - - /** - * Method type. - * @param _type Class - * @param _builder Class - * @return Builder - **/ - @SuppressWarnings("unchecked") - public Builder type( - Class _type, Class _builder) { - this._type = (Class) _type; - this._builder = (Class>) _builder; - return this; - } - - - /** - * Method parent. - * @param parent String - * @return Builder - **/ - public Builder parent(String parent) { - this.parent = parent; - return this; - } - - /** - * Method naturalLanguageValue. - * @param name String - * @return Builder - **/ - public Builder naturalLanguageValue(String name) { - return as(name, NLV.class); - } - - /** - * Method naturalLanguageValue. - * @param names String[] - * @return Builder - **/ - public Builder naturalLanguageValue(String... names) { - for (String name : names) - naturalLanguageValue(name); - return this; - } - - /** - * Method object. - * @param name String - * @return Builder - **/ - public Builder object(String name) { - return as(name, ASObject.class); - } - - /** - * Method object. - * @param names String[] - * @return Builder - **/ - public Builder object(String... names) { - for (String name : names) - object(name); - return this; - } - - /** - * Method integer. - * @param name String - * @return Builder - **/ - public Builder integer(String name) { - return as(name, Integer.class); - } - - /** - * Method integer. - * @param names String[] - * @return Builder - **/ - public Builder integer(String... names) { - for (String name : names) - integer(name); - return this; - } - - /** - * Method doub. - * @param name String - * @return Builder - **/ - public Builder doub(String name) { - return as(name, Double.class); - } - - /** - * Method doub. - * @param names String[] - * @return Builder - **/ - public Builder doub(String... names) { - for (String name : names) - doub(name); - return this; - } - - /** - * Method doub. - * @param name String - * @return Builder - **/ - public Builder floatValue(String name) { - return as(name, Float.class); - } - - /** - * Method doub. - * @param names String[] - * @return Builder - **/ - public Builder floatValue(String... names) { - for (String name : names) - floatValue(name); - return this; - } - - /** - * Method string. - * @param name String - * @return Builder - **/ - public Builder string(String name) { - return as(name, String.class); - } - - /** - * Method string. - * @param names String[] - * @return Builder - **/ - public Builder string(String... names) { - for (String name : names) - string(name); - return this; - } - - /** - * Method linkValue. - * @param name String - * @return Builder - **/ - public Builder linkValue(String name) { - return as(name, LinkValue.class); - } - - /** - * Method linkValue. - * @param names String[] - * @return Builder - **/ - public Builder linkValue(String... names) { - for (String name : names) - linkValue(name); - return this; - } - - /** - * Method dateTime. - * @param name String - * @return Builder - **/ - public Builder dateTime(String name) { - return as(name, DateTime.class); - } - - /** - * Method dateTime. - * @param names String[] - * @return Builder - **/ - public Builder dateTime(String... names) { - for (String name : names) - dateTime(name); - return this; - } - - /** - * Method duration. - * @param name String - * @return Builder - */ - public Builder duration(String name) { - return as(name, ReadableDuration.class); - } - - /** - * Method duration. - * @param names String[] - * @return Builder - */ - public Builder duration(String... names) { - for (String name : names) - duration(name); - return this; - } - - /** - * Method period. - * @param name String - * @return Builder - */ - public Builder period(String name) { - return as (name, ReadablePeriod.class); - } - - /** - * Method period. - * @param names String[] - * @return Builder - */ - public Builder period(String... names) { - for (String name: names) - period(name); - return this; - } - - /** - * Method interval. - * @param name String - * @return Builder - */ - public Builder interval(String name) { - return as(name, ReadableInterval.class); - } - - /** - * Method interval. - * @param names String[] - * @return Builder - */ - public Builder interval(String... names) { - for (String name: names) - interval(name); - return this; - } - - /** - * Method typeValue. - * @param name String - - * @return Builder */ - public Builder typeValue(String name) { - return as(name, TypeValue.class); - } - - /** - * Method typeValue. - * @param names String[] - - * @return Builder */ - public Builder typeValue(String... names) { - for (String name : names) - typeValue(name); - return this; - } - - /** - * Method as. - * @param name String - * @param _class Class - - * @return Builder */ - public Builder as(String name, Class _class) { - this.properties.put(name,_class); - return this; - } - - /** - * Method get. - - - * @return PropertyMap * @see com.google.common.base.Supplier#get() */ - public Model get() { - return new Model(this); - } - - } - - /** - * Constructor for PropertyMap. - * @param builder Builder - */ - Model(Builder builder) { - this.parent = builder.parent; - this.properties = ImmutableMap.copyOf(builder.properties); - this._default = builder._default; - this._type = builder._type; - this._builder = builder._builder; - } - - /** - * Method parentPropertyMap. - - * @return PropertyMap */ - protected Model parentPropertyMap() { - if (schema == null) - return null; - if (parent == null) - return null; - return schema.forObjectClassOrType( - ASObject.Builder.class, - parent.equals("object") ? null : parent); - } - - /** - * Method get. - * @param name String - - * @return Class */ - @SuppressWarnings("unchecked") - public T get(String name) { - Model parent = parentPropertyMap(); - return (T)(properties.containsKey(name) ? - properties.get(name) : - parent != null && _default == null ? - parent.get(name) : _default); - } - - /** - * Method containsKey. - * @param name String - - * @return boolean */ - public boolean has(String name) { - Model parent = parentPropertyMap(); - return properties.containsKey(name) ? - true : parent != null ? - parent.has(name) : false; - } - - /** - * Method type. - - * @return Class */ - @SuppressWarnings("unchecked") - public Class type() { - return (Class) _type; - } - - /** - * Method builder. - - * @return Class> */ - @SuppressWarnings("unchecked") - public Class> builder() { - return (Class>) _builder; - } - - /** - * Method toString. - - * @return String */ - public String toString() { - return Objects.toStringHelper(Model.class) - .omitNullValues() - .add("Parent", parent) - .add("Properties", properties) - .toString(); - } - - /** - * Method template. - - * @return Builder */ - public Builder template() { - return new Builder(this); - } - - /** - * Method template. - * @param _type Class - * @param _builder Class - - * @return PropertyMap */ - public > Model template( - Class _type, Class _builder) { - return template().type(_type,_builder).get(); - } - - /** - * Method set. - * @param name String - * @param type Class - - * @return PropertyMap */ - public Model set(String name, Class type) { - return template() - .as(name, type) - .get(); - } - - /** - * Method set. - * @param map Map> - - * @return PropertyMap */ - public Model set(Map> map) { - Builder builder = template(); - for (Map.Entry> entry : map.entrySet()) - builder.as(entry.getKey(),entry.getValue()); - return builder.get(); - } -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/internal/MultimapAdapter.java b/core/src/main/java/com/ibm/common/activitystreams/internal/MultimapAdapter.java deleted file mode 100755 index b6f5b36..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/internal/MultimapAdapter.java +++ /dev/null @@ -1,143 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.internal; - -import static com.google.common.collect.Iterables.getFirst; -import static com.google.common.collect.Iterables.size; - -import static com.ibm.common.activitystreams.internal.ASObjectAdapter.primConverter; - -import java.lang.reflect.Type; -import java.util.Map; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMultimap; -import com.google.common.collect.Multimap; -import com.google.gson.JsonArray; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonSerializationContext; -import com.ibm.common.activitystreams.ASObject; - -/** - * @author james - * @version $Revision: 1.0 $ - */ -@SuppressWarnings({"rawtypes","unchecked"}) -final class MultimapAdapter - extends Adapter { - - /** - * Method getAdaptedClass. - - * @return Class */ - public Class getAdaptedClass() { - return Multimap.class; - } - - /** - * Method serialize. - * @param src Multimap - * @param typeOfSrc Type - * @param context JsonSerializationContext - - * @return JsonElement */ - public JsonElement serialize( - Multimap src, - Type typeOfSrc, - JsonSerializationContext context) { - JsonObject obj = new JsonObject(); - for (Object key : src.keySet()) { - Iterable vals = src.get(key); - if (size(vals) == 1) { - Object f = getFirst(vals, null); - if (f != null) - obj.add(key.toString(), context.serialize(f, f.getClass())); - } else { - obj.add(key.toString(), context.serialize(vals, Iterable.class)); - } - } - return obj; - } - - /** - * Method arraydes. - * @param array JsonArray - * @param context JsonDeserializationContext - - * @return ImmutableList */ - protected static ImmutableList arraydes( - JsonArray array, - JsonDeserializationContext context) { - ImmutableList.Builder builder = - ImmutableList.builder(); - for (JsonElement child : array) - if (child.isJsonArray()) - builder.add(arraydes(child.getAsJsonArray(),context)); - else if (child.isJsonObject()) - builder.add(context.deserialize(child, ASObject.class)); - else if (child.isJsonPrimitive()) - builder.add(primConverter.convert(child.getAsJsonPrimitive())); - return builder.build(); - } - - /** - * Method deserialize. - * @param json JsonElement - * @param typeOfT Type - * @param context JsonDeserializationContext - - - - * @return Multimap * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) */ - public Multimap deserialize( - JsonElement json, - Type typeOfT, - JsonDeserializationContext context) - throws JsonParseException { - ImmutableMultimap.Builder mm = - ImmutableMultimap.builder(); - JsonObject obj = json.getAsJsonObject(); - for (Map.Entry entry : obj.entrySet()) { - String key = entry.getKey(); - JsonElement val = entry.getValue(); - if (val.isJsonArray()) { - for (JsonElement el : val.getAsJsonArray()) { - if (el.isJsonArray()) - mm.put(key, arraydes(el.getAsJsonArray(),context)); - else if (el.isJsonObject()) - mm.put(key, context.deserialize(el, ASObject.class)); - else if (el.isJsonPrimitive()) - mm.put(key,primConverter.convert(el.getAsJsonPrimitive())); - } - } else if (val.isJsonObject()) { - mm.put(key, context.deserialize(val, ASObject.class)); - } else if (val.isJsonPrimitive()) { - mm.put(key, primConverter.convert(val.getAsJsonPrimitive())); - } - } - return mm.build(); - } - -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/internal/NaturalLanguageValueAdapter.java b/core/src/main/java/com/ibm/common/activitystreams/internal/NaturalLanguageValueAdapter.java deleted file mode 100755 index 41b2a80..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/internal/NaturalLanguageValueAdapter.java +++ /dev/null @@ -1,116 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.internal; - -import static com.google.common.base.Preconditions.checkArgument; - -import java.lang.reflect.Type; -import java.util.Map.Entry; - -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.ibm.common.activitystreams.NLV; -import com.ibm.common.activitystreams.NLV.MapNLV; - -/** - * @author james - * @version $Revision: 1.0 $ - */ -final class NaturalLanguageValueAdapter - extends Adapter { - - /** - * Method serialize. - * @param nlv NLV - * @param type Type - * @param context JsonSerializationContext - - * @return JsonElement */ - public JsonElement serialize( - NLV nlv, - Type type, - JsonSerializationContext context) { - JsonElement el = null; - switch (nlv.valueType()) { - case SIMPLE: - el = context.serialize(((NLV.SimpleNLV)nlv).value()); - break; - case OBJECT: - NLV.MapNLV map = - (MapNLV) nlv; - JsonObject obj = new JsonObject(); - for (String lang : map) - obj.addProperty( - lang.toString(), - map.value(lang)); - el = obj; - break; - default: - } - return el; - } - - /** - * Method deserialize. - * @param element JsonElement - * @param type1 Type - * @param context JsonDeserializationContext - - - - * @return NLV * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) */ - public NLV deserialize( - JsonElement element, - Type type1, - JsonDeserializationContext context) - throws JsonParseException { - checkArgument( - element.isJsonPrimitive() || - element.isJsonObject()); - if (element.isJsonPrimitive()) { - JsonPrimitive prim = - element.getAsJsonPrimitive(); - checkArgument(prim.isString()); - return NLV.SimpleNLV.make( - prim.getAsString()); - } else { - try { - JsonObject obj = - element.getAsJsonObject(); - NLV.MapNLV.Builder builder = - NLV.MapNLV.make(); - for (Entry entry : obj.entrySet()) - builder.set( - entry.getKey(), - entry.getValue().getAsString()); - return builder.get(); - } catch (Throwable t) { - throw new IllegalArgumentException(); - } - } - } - -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/internal/Schema.java b/core/src/main/java/com/ibm/common/activitystreams/internal/Schema.java deleted file mode 100755 index 1e56433..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/internal/Schema.java +++ /dev/null @@ -1,442 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ - -package com.ibm.common.activitystreams.internal; -import static com.google.common.base.Objects.toStringHelper; -import static com.google.common.base.Preconditions.checkNotNull; -import static com.google.common.collect.HashBiMap.create; -import static com.google.common.collect.Iterables.addAll; -import static com.google.common.collect.Maps.newHashMap; -import static com.google.common.collect.Sets.newHashSet; - -import java.util.Map; -import java.util.Set; - -import org.joda.time.Duration; - -import com.google.common.base.Converter; -import com.google.common.base.Supplier; -import com.google.common.collect.BiMap; -import com.google.common.collect.ImmutableBiMap; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.net.MediaType; -import com.ibm.common.activitystreams.ASObject; -import com.ibm.common.activitystreams.ActionsValue; -import com.ibm.common.activitystreams.Activity; -import com.ibm.common.activitystreams.Collection; - -/** - * @TODO: The Schema mechanism needs to be revisited and reworked - * to be much more efficient. - * @author james - * @version $Revision: 1.0 $ - */ -@SuppressWarnings("rawtypes") -public final class Schema { - - /** - * @author james - * @version $Revision: 1.0 $ - */ - public static final class Builder - implements Supplier { - - final Map objectTypeMap = - newHashMap(); - final Map> builderMap = - newHashMap(); - final Map,Model> objectClassMap = - newHashMap(); - final BiMap, Class> classMap = - create(100); - final Set> adapters = - newHashSet(); - - Builder() {} - - /** - * Constructor for Builder. - * @param template Schema - */ - Builder(Schema template) { - this.objectTypeMap.putAll(template.objectTypeMap); - this.builderMap.putAll(template.builderMap); - this.objectClassMap.putAll(template.objectClassMap); - this.classMap.putAll(template.classMap); - this.adapters.addAll(template.adapters); - } - - /** - * Method adapter. - * @param _enumClass Class - - * @return Builder */ - public >Builder adapter( - Class _enumClass) { - return adapter(new EnumAdapter(_enumClass)); - } - - /** - * Method adapter. - * @param _enumClass Class - - - * @param c Converter - * @return Builder */ - public >Builder adapter( - Class _enumClass, - Converter c) { - return adapter(new EnumAdapter(_enumClass,c)); - } - - /** - * Method adapter - * @param _enumClass Class - * @param or E - * @return Builder - */ - public >Builder adapter( - Class _enumClass, E or) { - return adapter(new EnumAdapter(_enumClass,or)); - } - - /** - * Method adapter. - * @param adapter Adapter - - * @return Builder */ - public Builder adapter(Adapter adapter) { - this.adapters.add(adapter); - return this; - } - - /** - * Method adapter. - * @param adapters Adapter[] - - * @return Builder */ - public Builder adapter(Adapter... adapters) { - if (adapters == null) return this; - for (Adapter a : adapters) - adapter(a); - return this; - } - - /** - * Method adapter. - * @param adapters Iterable> - - * @return Builder */ - public Builder adapter(Iterable> adapters) { - if (adapters == null) return this; - addAll(this.adapters, adapters); - return this; - } - - /** - * Method map. - * @param objectType String - * @param propertyMap Supplier - - * @return Builder */ - public Builder map(String objectType, Supplier propertyMap) { - return map(objectType, propertyMap.get()); - } - - /** - * Method map. - * @param propertyMap Supplier - - * @return Builder */ - public Builder map(Supplier propertyMap) { - return map(null,propertyMap); - } - - /** - * Method map. - * @param propertyMap PropertyMap - - * @return Builder */ - public Builder map(Model propertyMap) { - return map(null, propertyMap); - } - - /** - * Method map. - * @param objectType String - * @param propertyMap PropertyMap - - * @return Builder */ - public Builder map(String objectType, Model propertyMap) { - checkNotNull(propertyMap); - Class> _builder = propertyMap.builder(); - Class _type = propertyMap.type(); - if (objectType != null) objectTypeMap.put(objectType, propertyMap); - if (objectType != null && _builder != null) - builderMap.put(objectType,_builder); - if (_builder != null) objectClassMap.put(_builder, propertyMap); - if (_builder != null && _type != null) - classMap.put(_type,_builder); - return this; - } - - public Model model(String objectType) { - return objectTypeMap.get(objectType); - } - - public Model model() { - return objectClassMap.get(ASObject.Builder.class); - } - - /** - * Method get. - * @return Schema * @see com.google.common.base.Supplier#get() */ - public Schema get() { - return new Schema(this); - } - - } - - final ImmutableMap objectTypeMap; - final ImmutableMap, Model> objectClassMap; - final ImmutableMap> builderMap; - final ImmutableBiMap, Class> classMap; - final ImmutableSet> adapters; - - /** - * Constructor for Schema. - * @param builder Builder - */ - Schema(Builder builder) { - this.objectClassMap = ImmutableMap.copyOf(builder.objectClassMap); - this.objectTypeMap = ImmutableMap.copyOf(builder.objectTypeMap); - this.builderMap = ImmutableMap.copyOf(builder.builderMap); - this.adapters = ImmutableSet.copyOf(builder.adapters); - this.classMap = ImmutableBiMap.copyOf(builder.classMap); - - for (Model pmap : objectTypeMap.values()) - pmap.schema(this); - for (Model pmap : objectClassMap.values()) - pmap.schema(this); - - } - - /** - * Method adapters. - - * @return Iterable> */ - public Iterable> adapters() { - return adapters; - } - - /** - * Method builderForObjectTypeOrClass. - * @param ots String - * @param _class Class - - * @return Class */ - public Class builderForObjectTypeOrClass(String ots, Class _class) { - Class _builder = builderFor(ots); - return _builder != null ? - _builder : builderFor(_builder); - } - - /** - * Method builderFor. - * @param _class Class - - * @return Class */ - public Class builderFor(Class _class) { - if (_class == null) return null; - return classMap.get(_class); - } - - /** - * Method classFor. - * @param _builder Class - - * @return Class */ - public Class classFor(Class _builder) { - if (_builder == null) return null; - return classMap.inverse().get(_builder); - } - - /** - * Method builderFor. - * @param ots String - - * @return Class */ - public Class builderFor(String ots) { - if (ots == null) return null; - return builderMap.get(ots); - } - - /** - * Method forObjectType. - * @param objectType String - - * @return PropertyMap */ - public Model forObjectType(String objectType) { - return objectTypeMap.get(objectType); - } - - /** - * Method forObjectClass. - * @param _class Class - - * @return PropertyMap */ - public Model forObjectClass(Class _class) { - return objectClassMap.get(_class); - } - - /** - * Method forObjectClassOrType. - * @param _class Class - * @param objectType String - - * @return PropertyMap */ - public Model forObjectClassOrType(Class _class, String objectType) { - Model pm = forObjectClass(_class); - return pm != null ? pm : forObjectType(objectType); - } - - /** - * Method template. - - * @return Builder */ - public Builder template() { - return new Builder(this); - } - - /** - * Method toString. - - * @return String */ - public String toString() { - return toStringHelper(Schema.class) - .add("Object Types", objectTypeMap) - .add("Object Classes", objectClassMap) - .toString(); - } - - public final static Model object = - Model - .make() - .type( - ASObject.class, - ASObject.Builder.class) - .typeValue( - "objectType") - .linkValue( - "attachments", - "author", - "duplicates", - "icon", - "image", - "location", - "inReplyTo", - "tags", - "url", - "generator", - "provider", - "scope" - ) - .dateTime( - "published", - "updated", - "startTime", - "endTime") - .naturalLanguageValue( - "summary", - "title", - "content", - "displayName") - .as("language", String.class) - .as("actions", ActionsValue.class) - .string("id", "rel", "alias") - .doub("rating") - .integer("height", "width") - .as("mediaType", MediaType.class) - .as("duration", Duration.class) - .get(); - - public final static Model activity = - Model - .make("object") - .type( - Activity.class, - Activity.Builder.class) - .typeValue("verb") - .linkValue( - "actor", - "participant", - "instrument", - "object", - "target", - "result", - "to", - "bto", - "cc", - "bcc") - .doub("priority") - .as("status", Activity.Status.class) - .get(); - - public final static Model collection = - Model - .make("object") - .type( - Collection.class, - Collection.Builder.class) - .dateTime( - "itemsBefore", - "itemsAfter") - .linkValue( - "first", - "last", - "prev", - "next", - "current", - "self") - .object("items") - .integer( - "startIndex", - "itemsPerPage", - "totalItems") - .get(); - - /** - * Method make. - - * @return Schema.Builder */ - public static Schema.Builder make() { - return - new Builder() - .map(null, object) - .map("activity", activity) - .map("collection", collection); - } - - public static final Schema DEFAULT_SCHEMA = make().get(); - -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/internal/SimpleAdapter.java b/core/src/main/java/com/ibm/common/activitystreams/internal/SimpleAdapter.java deleted file mode 100755 index e672981..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/internal/SimpleAdapter.java +++ /dev/null @@ -1,90 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ - -package com.ibm.common.activitystreams.internal; - -import java.lang.reflect.Type; - -import com.google.common.base.Function; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonElement; -import com.google.gson.JsonParseException; -import com.google.gson.JsonSerializationContext; - -/** - * @author james - * @version $Revision: 1.0 $ - */ -public abstract class SimpleAdapter - extends Adapter - implements Function { - - /** - * Method serialize. - * @param t T - * @param type Type - * @param context JsonSerializationContext - - - * @return JsonElement * @see com.google.gson.JsonSerializer#serialize(T, Type, JsonSerializationContext) */ - public JsonElement serialize( - T t, - Type type, - JsonSerializationContext context) { - return context.serialize(serialize(t)); - } - - /** - * Method serialize. - * @param t T - - * @return String */ - protected String serialize(T t) { - return t != null ? t.toString() : null; - } - - /** - * Method deserialize. - * @param v String - - * @return T */ - protected T deserialize(String v) { - return apply(v); - } - - /** - * Method deserialize. - * @param json JsonElement - * @param type Type - * @param context JsonDeserializationContext - - - - * @return T * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) */ - public T deserialize( - JsonElement json, - Type type, - JsonDeserializationContext context) - throws JsonParseException { - return deserialize(json.getAsJsonPrimitive().getAsString()); - } -} \ No newline at end of file diff --git a/core/src/main/java/com/ibm/common/activitystreams/internal/TypeValueAdapter.java b/core/src/main/java/com/ibm/common/activitystreams/internal/TypeValueAdapter.java deleted file mode 100755 index b09bad0..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/internal/TypeValueAdapter.java +++ /dev/null @@ -1,121 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.internal; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.ibm.common.activitystreams.Makers.type; - -import java.lang.reflect.Type; - -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.ibm.common.activitystreams.ASObject; -import com.ibm.common.activitystreams.TypeValue; -import com.ibm.common.activitystreams.ValueType; - -/** - * @author james - * @version $Revision: 1.0 $ - */ -final class TypeValueAdapter - extends Adapter { - - private final Schema schema; - - /** - * Constructor for TypeValueAdapter. - * @param schema Schema - */ - public TypeValueAdapter( - Schema schema) { - this.schema = schema; - } - - /** - * Method serialize. - * @param value TypeValue - * @param type Type - * @param context JsonSerializationContext - - * @return JsonElement */ - public JsonElement serialize( - TypeValue value, - Type type, - JsonSerializationContext context) { - boolean simple = value.valueType() == ValueType.SIMPLE; - return context.serialize( - simple ? value.id() : value, - simple ? String.class : ASObject.class - ); - } - - /** - * Method deserialize. - * @param el JsonElement - * @param type Type - * @param context JsonDeserializationContext - - - - * @return TypeValue * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) */ - public TypeValue deserialize( - JsonElement el, - Type type, - JsonDeserializationContext context) - throws JsonParseException { - checkArgument( - el.isJsonPrimitive() || - el.isJsonObject()); - if (el.isJsonPrimitive()) { - JsonPrimitive prim = - el.getAsJsonPrimitive(); - checkArgument(prim.isString()); - return type(prim.getAsString()); - } else { - JsonObject obj = el.getAsJsonObject(); - if (obj.has("objectType")) { - TypeValue tv = - context.deserialize( - obj.get("objectType"), - TypeValue.class); - Model pMap = - schema.forObjectType(tv.id()); - return - context.deserialize( - el, - pMap.type() != null ? - pMap.type() : - ASObject.class); - } else { - return - context.deserialize( - el, - ASObject.class); - } - } - } - -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/util/AbstractDictionaryObject.java b/core/src/main/java/com/ibm/common/activitystreams/util/AbstractDictionaryObject.java deleted file mode 100755 index 12447fd..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/util/AbstractDictionaryObject.java +++ /dev/null @@ -1,305 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.util; - -import static com.google.common.collect.ImmutableList.of; -import static com.google.common.collect.Iterables.filter; -import static com.google.common.collect.Iterables.size; -import static com.google.common.collect.Iterables.transform; -import static com.google.common.collect.Maps.difference; -import static com.ibm.common.activitystreams.Makers.linkValue; -import static com.ibm.common.activitystreams.Makers.linkValues; - -import java.util.Iterator; -import java.util.Map; - -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import com.ibm.common.activitystreams.ASObject; -import com.ibm.common.activitystreams.LinkValue; -import com.ibm.common.activitystreams.ValueType; -import com.ibm.common.activitystreams.LinkValue.ArrayLinkValue; - -/** - * Utility abstract base used for objects that are JSON - * dictionaries as opposed to full Activity Stream objects. - * @author james - * @version $Revision: 1.0 $ - */ -public abstract class AbstractDictionaryObject - extends AbstractWritable - implements Iterable { - - public static abstract class AbstractBuilder - , B extends AbstractBuilder> - extends AbstractWritable.AbstractWritableBuilder { - - protected final Map map = - Maps.newHashMap(); - private boolean isempty = true; - - /** - * Returns true if items have been added - * @return boolean - */ - public boolean notEmpty() { - return !isempty; - } - - /** - * Sets an item in this dictionary object - * @param key String - * @param x X - * @return B - */ - @SuppressWarnings("unchecked") - public B set(String key, X x) { - if (x != null) { - map.put(key,x); - isempty = false; - } - return (B)this; - } - - /** - * Sets an item in this dictionary object - * @param key String - * @param x Supplier - * @return B - */ - public B set( - String key, - Supplier x) { - return set(key, x.get()); - } - - /** - * Add a link - * @param name String - * @param url String - * @return B - **/ - protected B link(String name, String url) { - return link(name, linkValue(url)); - } - - /** - * Add a link - * @param name String - * @param link LinkValue - * @return B - **/ - @SuppressWarnings("unchecked") - protected B link(String name, LinkValue link) { - if (link == null) - return (B)this; - isempty = false; - Object obj = map.get(name); - if (link.valueType() != ValueType.ARRAY) { - if (obj instanceof LinkValue) - link = - ((LinkValue) obj).valueType() == ValueType.ARRAY ? - linkValues() - .add((LinkValue.ArrayLinkValue)obj) - .add(link) - .get() : - linkValues() - .add((LinkValue)obj, link) - .get(); - map.put(name, (X) link); - } else map.put(name, (X)link); - return (B)this; - } - - /** - * Add a link - * @param name String - * @param link Supplier - * @return B - **/ - public B link(String name, Supplier link) { - return link(name,link.get()); - } - - /** - * Add a link - * @param name String - * @param links Object[] - * @return B - **/ - @SuppressWarnings("unchecked") - protected B link(String name, Object... links) { - if (links == null) return (B)this; - ArrayLinkValue.Builder b = - ArrayLinkValue.make(); - for (Object obj : links) - _add(b, obj); - return link(name,b.get()); - } - - /** - * Method _add. - * @param builder ArrayLinkValue.Builder - * @param obj Object - */ - private void _add(ArrayLinkValue.Builder builder, Object obj) { - if (obj == null) - return; - else if (obj instanceof String) - builder.add((String)obj); - else if (obj instanceof ASObject) - builder.add((ASObject)obj); - else if (obj instanceof Supplier) - _add(builder,((Supplier)obj).get()); - else throw new IllegalArgumentException(); - } - - } - - private final ImmutableMap map; - private transient int hash = 1; - - /** - * @param builder AbstractBuilder - */ - protected AbstractDictionaryObject(AbstractBuilder builder) { - super(builder); - this.map = ImmutableMap.copyOf(builder.map); - } - - /** - * Method getSingle. - * @param key String - * @return X - */ - protected X getSingle(String key) { - return map.get(key); - } - - /** - * Method getSingle. - * @param key String - * @param defaultValue X - * @return X - */ - protected X getSingle(String key, X defaultValue) { - X ret = getSingle(key); - return ret != null ? ret : defaultValue; - } - - /** - * Method getIterable. - * @param key String - * @return Iterable - */ - @SuppressWarnings("unchecked") - protected Iterable getIterable(String key) { - X x = map.get(key); - return x instanceof Iterable ? - (Iterable)x : - of(x); - } - - /** - * Method getIterable. - * @param key String - * @param filter Predicate - * @return Iterable - */ - protected Iterable getIterable( - String key, - Predicate filter) { - return filter(getIterable(key), filter); - } - - /** - * Method getIterable. - * @param key String - * @param transform Function - * @return Iterable - */ - protected Iterable getIterable( - String key, - Function transform) { - return transform(getIterable(key), transform); - } - - /** - * Method getIterable. - * @param key String - * @param filter Predicate - * @param transform Function - * @return Iterable - */ - protected Iterable getIterable( - String key, - Predicate filter, - Function transform) { - return transform(filter(getIterable(key),filter),transform); - } - - public Iterator iterator() { - return map.keySet().iterator(); - } - - /** - * Returns true if the verb appears in the ActionsValue object - * @param key String - * @return boolean */ - public boolean has(String key) { - return map.containsKey(key); - } - - /** - * Returns true if the verb appears in the ActionsValue object - * and there is at least one handler in the value. - * @param key String - * @return boolean - */ - protected boolean hasAtLeastOne(String key) { - return has(key) && size(getIterable(key)) > 0; - } - - public int hashCode() { - if (hash == 1) - hash = map.hashCode(); - return hash; - } - - - @SuppressWarnings({ "rawtypes", "unchecked" }) - public boolean equals(Object obj) { - if (this == obj) - return true; - if (obj == null) - return false; - if (getClass() != obj.getClass()) - return false; - AbstractDictionaryObject other = - (AbstractDictionaryObject) obj; - return difference(map,other.map).areEqual(); - } - -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/util/AbstractDictionaryObjectAdapter.java b/core/src/main/java/com/ibm/common/activitystreams/util/AbstractDictionaryObjectAdapter.java deleted file mode 100755 index 718e4af..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/util/AbstractDictionaryObjectAdapter.java +++ /dev/null @@ -1,95 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.util; - -import static com.google.common.base.Preconditions.checkArgument; - -import java.lang.reflect.Type; -import java.util.Map.Entry; - -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonSerializationContext; -import com.ibm.common.activitystreams.internal.Adapter; - -/** - * Abstract base GSON Serializer for AbstractDictionaryObject - * instances. - * @author james - * @version $Revision: 1.0 $ - */ -public abstract class AbstractDictionaryObjectAdapter - , - B extends AbstractDictionaryObject.AbstractBuilder> - extends Adapter { - - private final Class klass; - - /** - * Constructor for AbstractDictionaryObjectAdapter. - * @param klass Class - */ - protected AbstractDictionaryObjectAdapter(Class klass) { - this.klass = klass; - } - - public JsonElement serialize( - X x, - Type type, - JsonSerializationContext context) { - JsonObject obj = new JsonObject(); - for (String key : x) - obj.add( - key, - context.serialize( - x.getSingle(key), - klass)); - return obj; - } - - public X deserialize( - JsonElement element, - Type type1, - JsonDeserializationContext context) - throws JsonParseException { - checkArgument(element.isJsonObject()); - try { - JsonObject obj = - element.getAsJsonObject(); - B builder = builder(); - for (Entry entry : obj.entrySet()) - builder.set( - entry.getKey(), - context.deserialize( - entry.getValue(), - klass)); - return builder.get(); - } catch (Throwable t) { - t.printStackTrace(); - throw new IllegalArgumentException(); - } - } - - protected abstract B builder(); -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/util/AbstractWritable.java b/core/src/main/java/com/ibm/common/activitystreams/util/AbstractWritable.java deleted file mode 100755 index f7d6395..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/util/AbstractWritable.java +++ /dev/null @@ -1,153 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.util; - -import static com.ibm.common.activitystreams.IO.makeDefault; - -import java.io.OutputStream; -import java.io.StringWriter; -import java.io.Writer; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; - -import com.google.common.base.Supplier; -import com.ibm.common.activitystreams.IO; -import com.ibm.common.activitystreams.Writable; - -/** - * Utility base class for Writable instances. - * @author james - * @version $Revision: 1.0 $ - */ -public abstract class AbstractWritable - implements Writable { - - public static abstract class AbstractWritableBuilder - > - implements Supplier { - - private IO io = null; - - /** - * Set the IO instance that should be used - * by default for writing instances of this - * object. - */ - @SuppressWarnings("unchecked") - public B writeUsing(IO io) { - this.io = io; - return (B)this; - } - - public void writeTo(OutputStream out) { - get().writeTo(out); - } - - public Future writeTo(OutputStream out, ExecutorService executor) { - return get().writeTo(out,executor); - } - - public void writeTo(Writer out) { - get().writeTo(out); - } - - public Future writeTo(Writer out, ExecutorService executor) { - return get().writeTo(out,executor); - } - - - public void writeTo(OutputStream out, IO io) { - get().writeTo(out,io); - } - - public Future writeTo(OutputStream out, IO io, ExecutorService executor) { - return get().writeTo(out, io, executor); - } - - public void writeTo(Writer out, IO io) { - get().writeTo(out,io); - } - - public Future writeTo(Writer out, IO io, ExecutorService executor) { - return get().writeTo(out, io, executor); - } - - } - - private final IO io; - - protected AbstractWritable(AbstractWritableBuilder b) { - this.io = b.io != null ? b.io : makeDefault(); - } - - public void writeTo(OutputStream out) { - writeTo(out,io); - } - - public Future writeTo(OutputStream out, ExecutorService executor) { - return writeTo(out, io, executor); - } - - public void writeTo(OutputStream out, IO io) { - io.write(this,out); - } - - public Future writeTo(OutputStream out, IO io, ExecutorService executor) { - return io.write(this,out,executor); - } - - public void writeTo(Writer out) { - writeTo(out, io); - } - - public Future writeTo(Writer out, ExecutorService executor) { - return writeTo(out, io, executor); - } - - public void writeTo(Writer out, IO io) { - io.write(this,out); - } - - public Future writeTo(Writer out, IO io, ExecutorService executor) { - return io.write(this, out, executor); - } - - public String toString(IO io) { - StringWriter sw = - new StringWriter(); - io.write(this, sw); - return sw.toString(); - } - - public Future toString(ExecutorService executor) { - return io.write(this, executor); - } - - public Future toString(IO io, ExecutorService executor) { - return io.write(this, executor); - } - - public String toString() { - return toString(io); - } - -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/util/Converters.java b/core/src/main/java/com/ibm/common/activitystreams/util/Converters.java deleted file mode 100755 index bf55ebc..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/util/Converters.java +++ /dev/null @@ -1,362 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.util; - -import static com.google.common.base.Enums.getIfPresent; -import static com.google.common.base.Optional.absent; -import static com.google.common.base.Optional.fromNullable; -import static com.google.common.base.Optional.of; -import static com.google.common.base.Preconditions.checkNotNull; -import static org.joda.time.Duration.millis; -import static org.joda.time.Duration.standardDays; -import static org.joda.time.Duration.standardHours; -import static org.joda.time.Duration.standardMinutes; -import static org.joda.time.Duration.standardSeconds; - -import java.util.Date; -import java.util.Locale; -import java.util.concurrent.TimeUnit; - -import org.joda.time.DateTime; -import org.joda.time.Duration; -import org.joda.time.Interval; -import org.joda.time.Period; - -import com.google.common.base.Converter; -import com.google.common.base.Function; -import com.google.common.base.Optional; -import com.google.common.primitives.Doubles; -import com.google.common.primitives.Floats; -import com.google.common.primitives.Ints; -import com.google.common.primitives.Longs; - -public final class Converters { - - private Converters() {} - - /** - * Method toDuration. - * @param v long - * @param unit TimeUnit - * @return Duration - */ - public static Duration toDuration(long v, TimeUnit unit) { - switch(unit) { - case NANOSECONDS: - return millis(v / 1000 / 1000); - case MICROSECONDS: - return millis(v / 1000); - case MILLISECONDS: - return millis(v); - case SECONDS: - return standardSeconds(v); - case MINUTES: - return standardMinutes(v); - case HOURS: - return standardHours(v); - case DAYS: - return standardDays(v); - default: - throw new IllegalArgumentException(); - } - } - - /** - * Method tryParseShort. - * @param input String - * @return Short - */ - private static Short tryParseShort(String input) { - try { - return Short.parseShort(input); - } catch (Throwable t) { - return null; - } - } - - /** - * Method tryParseBoolean. - * @param input String - * @return Boolean - */ - private static Boolean tryParseBoolean(String input) { - try { - return Boolean.parseBoolean(input); - } catch (Throwable t) { - return null; - } - } - - /** - * Method tryParseDateTime. - * @param input String - * @return DateTime - */ - private static DateTime tryParseDateTime(String input) { - try { - return DateTime.parse(input); - } catch (Throwable t) { - return null; - } - } - - /** - * Method tryParseDuration. - * @param input String - * @return Duration - */ - private static Duration tryParseDuration(String input) { - try { - return Period.parse(input).toDurationFrom(DateTime.now()); - } catch (Throwable t) { - return null; - } - } - - /** - * Method tryParsePeriod. - * @param input String - * @return Period - */ - private static Period tryParsePeriod(String input) { - try { - return Period.parse(input); - } catch (Throwable t) { - return null; - } - } - - /** - * Method tryParseInterval. - * @param input String - * @return Interval - */ - private static Interval tryParseInterval(String input) { - try { - return Interval.parse(input); - } catch (Throwable t) { - return null; - } - } - - public static final Function> toInterval = - new Function>() { - public Optional apply(Object input) { - Optional ret = absent(); - if (input != null) - ret = input instanceof Interval ? - of((Interval)input) : - fromNullable(tryParseInterval(input.toString())); - return ret; - } - - }; - - public static final Function> toDuration = - new Function>() { - - public Optional apply(Object input) { - Optional ret = absent(); - if (input != null) - ret = input instanceof Duration ? - of((Duration)input) : - input instanceof Number ? - of(standardSeconds(((Number)input).longValue())) : - fromNullable(tryParseDuration(input.toString())); - return ret; - } - - }; - - public static final Function> toPeriod = - new Function>() { - public Optional apply(Object input) { - Optional ret = absent(); - if (input != null) - ret = input instanceof Period ? - of((Period)input) : - fromNullable(tryParsePeriod(input.toString())); - return ret; - } - }; - - public static final Function> toDateTime = - new Function>() { - public Optional apply(Object input) { - Optional ret = absent(); - if (input != null) - ret = input instanceof DateTime ? - of((DateTime)input) : - input instanceof Date ? - of(new DateTime((Date)input)) : - input instanceof Number ? - of(new DateTime(((Number)input).longValue())) : - fromNullable(tryParseDateTime(input.toString())); - return ret; - } - - }; - - public static final Function> toBoolean = - new Function>() { - public Optional apply(Object input) { - Optional ret = absent(); - if (input != null) - ret = input instanceof Boolean ? - of((Boolean)input) : - input instanceof Number ? - of(((Number)input).intValue() != 0) : - fromNullable(tryParseBoolean(input.toString())); - return ret; - } - }; - - public static final Function> toShort = - new Function>() { - public Optional apply(Object input) { - Optional ret = absent(); - if (input != null) - ret = input instanceof Number ? - of(((Number) input).shortValue()) : - fromNullable(tryParseShort(input.toString())); - return ret; - } - }; - - public static final Function> toInt = - new Function>() { - public Optional apply(Object input) { - Optional ret = absent(); - if (input != null) - ret = input instanceof Number ? - of(((Number) input).intValue()) : - fromNullable(Ints.tryParse(input.toString())); - return ret; - } - }; - - public static final Function> toLong = - new Function>() { - public Optional apply(Object input) { - Optional ret = absent(); - if (input != null) - ret = input instanceof Number ? - of(((Number) input).longValue()) : - fromNullable(Longs.tryParse(input.toString())); - return ret; - } - }; - - public static final Function> toDouble = - new Function>() { - public Optional apply(Object input) { - Optional ret = absent(); - if (input != null) - ret = input instanceof Number ? - of(((Number) input).doubleValue()) : - fromNullable(Doubles.tryParse(input.toString())); - return ret; - } - }; - - public static final Function> toFloat = - new Function>() { - public Optional apply(Object input) { - Optional ret = absent(); - if (input != null) - ret = input instanceof Number ? - of(((Number) input).floatValue()) : - fromNullable(Floats.tryParse(input.toString())); - return ret; - } - }; - - /** - * Method stringConverter. - * @param enumClass Class - * @param or E - * @return Converter - */ - public static > Converter stringConverter( - final Class enumClass, - final E or) { - return new Converter() { - - @Override - protected String doBackward(E e) { - return checkNotNull(e).name(); - } - - @Override - protected E doForward(String s) { - return getIfPresent(enumClass, s).or(or); - } - - }; - } - - /** - * Method toUpperConverter. - * @return Converter - */ - public static Converter toUpperConverter() { - return toLowerConverter().reverse(); - } - - /** - * Method toUpperConverter. - * @param locale Locale - * @return Converter - */ - public static Converter toUpperConverter(Locale locale) { - return toLowerConverter(locale).reverse(); - } - - /** - * Method toLowerConverter. - * @return Converter - */ - public static Converter toLowerConverter() { - return toLowerConverter(Locale.getDefault()); - } - - /** - * Method toLowerConverter. - * @param locale Locale - * @return Converter - */ - public static Converter toLowerConverter(final Locale locale) { - return new Converter() { - - @Override - protected String doForward(String a) { - return a.toLowerCase(locale); - } - - @Override - protected String doBackward(String b) { - return b.toUpperCase(locale); - } - - }; - } -} diff --git a/core/src/main/java/com/ibm/common/activitystreams/util/Util.java b/core/src/main/java/com/ibm/common/activitystreams/util/Util.java deleted file mode 100644 index 664b13a..0000000 --- a/core/src/main/java/com/ibm/common/activitystreams/util/Util.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.ibm.common.activitystreams.util; - -import static com.google.common.base.Preconditions.checkNotNull; - -import java.util.Locale; - -public final class Util { - - private Util() {} - - /** - * Method convLocale. - * @param locale Locale - * @return String - **/ - public static String convLocale(Locale locale) { - return checkNotNull(locale).toString().replaceAll("_", "-"); - } - - public static final String DEFAULT_LOCALE = - convLocale(Locale.getDefault()); - -} diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/ASObject.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/ASObject.kt new file mode 100644 index 0000000..750e6e9 --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/ASObject.kt @@ -0,0 +1,2548 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams + +import com.google.common.base.* +import com.google.common.base.Function +import com.google.common.collect.ImmutableList +import com.google.common.collect.ImmutableMap +import com.google.common.collect.Iterables +import com.google.common.collect.Maps +import com.google.common.net.MediaType +import com.ibm.common.activitystreams.LinkValue.ArrayLinkValue +import com.ibm.common.activitystreams.NLV.MapNLV +import com.ibm.common.activitystreams.NLV.SimpleNLV +import com.ibm.common.activitystreams.util.AbstractWritable +import com.ibm.common.activitystreams.util.Converters +import com.ibm.common.activitystreams.util.Util +import org.joda.time.* +import java.io.ObjectStreamException +import java.io.Serializable +import java.util.concurrent.Callable +import java.util.concurrent.TimeUnit +import kotlin.math.ceil +import kotlin.math.floor + +/** + * The Base for all Activity Streams objects. + * + * + * Creating an object: + *
+ * import static com.ibm.common.activitystreams.Makers.object;
+ *
+ * ASObject obj = object()
+ * .id("urn:example:object:1")
+ * .displayName("My Note")
+ * .objectType("note")
+ * .content("en", "This is my note in english")
+ * .get();
+
* + * @author james + * @version $Revision: 1.0 $ + */ +open class ASObject + (builder: AbstractBuilder<*, *>) : AbstractWritable(builder), + Iterable, LinkValue, TypeValue, Serializable { + /** + * Builder for concrete ASObject instances + */ + class Builder + + : AbstractBuilder() { + /** + * Returns the built ASObject instance + * @return ASObject + * @see com.google.common.base.Supplier.get + */ + override fun get(): ASObject { + return ASObject(this) + } + } + + /** + * Abstract base builder for ASObject instances. + */ + abstract class AbstractBuilder + ?> + : AbstractWritableBuilder(), Supplier, Writable { + val map: MutableMap = Maps.newLinkedHashMap() + val actions: ActionsValue.Builder = Makers.actions() + + /** + * Method _dt. + * @param key String + * @param dt DateTime + * @return B + */ + protected fun _dt(key: String, dt: DateTime?): B { + return set(key, dt) + } + + /** + * Method _dt. + * @param key String + * @param dt String + * @return B + */ + protected fun _dt(key: String, dt: String?): B { + return _dt(key, DateTime.parse(dt)) + } + + /** + * Method _dtNow. + * @param key String + * @return B + */ + protected fun _dtNow(key: String): B { + return _dt(key, DateTime.now(DateTimeZone.UTC)) + } + + /** + * Method _dtFromNow. + * @param key String + * @param duration Duration + * @return B + */ + protected fun _dtFromNow(key: String, duration: ReadableDuration?): B { + return _dt(key, DateTime.now(DateTimeZone.UTC).plus(duration)) + } + + /** + * Method _dtFromNow. + * @param key String + * @param period ReadablePeriod + * @return B + */ + protected fun _dtFromNow(key: String, period: ReadablePeriod?): B { + return _dt(key, DateTime.now(DateTimeZone.UTC).plus(period)) + } + + /** + * Method _dtFromNow. + * @param key String + * @param v long + * @param unit TimeUnit + * @return B + */ + protected fun _dtFromNow(key: String, v: Long, unit: TimeUnit): B { + return _dtFromNow(key, Converters.toDuration(v, unit)) + } + + /** + * Method _dtFrom. + * @param key String + * @param dt DateTime + * @param duration Duration + * @return B + */ + protected fun _dtFrom(key: String, dt: DateTime, duration: ReadableDuration?): B { + return _dt(key, dt.plus(duration)) + } + + /** + * Method _dtFrom. + * @param key String + * @param dt DateTime + * @param period ReadablePeriod + * @return B + */ + protected fun _dtFrom(key: String, dt: DateTime, period: ReadablePeriod?): B { + return _dt(key, dt.plus(period)) + } + + /** + * Method _dtFrom. + * @param key String + * @param dt DateTime + * @param v long + * @param unit TimeUnit + * @return B + */ + protected fun _dtFrom(key: String, dt: DateTime, v: Long, unit: TimeUnit): B { + return _dtFrom(key, dt, Converters.toDuration(v, unit)) + } + + /** + * Set the published timestamp + * @param dt DateTime + * @return B + */ + fun published(dt: DateTime?): B { + return _dt("published", dt) + } + + /** + * Set the published timestamp equal to the current time + * @return B + */ + fun publishedNow(): B { + return _dtNow("published") + } + + /** + * Set the published timestamp as a given duration from the current time. + * For instance: + *
+         * // Published one day ago
+         * ASObject obj = Makers.object()
+         * .publishedFromNow(Duration.standardDays(-1))
+         * .get();
+         * 
+         * @param duration Duration
+         * @return B
+        
*/ + fun publishedFromNow(duration: ReadableDuration?): B { + return _dtFromNow("published", duration) + } + + /** + * Set the published timestamp as a given period of time from the current time + *
+         * // Published one day ago
+         * ASObject obj = Makers.object()
+         * .publishedFromNow(Period.days(-1))
+         * .get();
+         * 
+         * @param period ReadablePeriod
+         * @return B
+        
*/ + fun publishedFromNow(period: ReadablePeriod?): B { + return _dtFromNow("published", period) + } + + /** + * Set the published timestamp as a given period of time from the current time + * @param v long + * @param unit TimeUnit + * @return B + */ + fun publishedFromNow(v: Long, unit: TimeUnit): B { + return _dtFromNow("published", v, unit) + } + + /** + * Set the updated timestamp + * @param dt DateTime + * @return B + */ + fun updated(dt: DateTime?): B { + return _dt("updated", dt) + } + + /** + * Set the updated timestamp equal to the current time + * @return B + */ + fun updatedNow(): B { + return _dtNow("updated") + } + + /** + * Set the updated timestamp as a given duration from the current time. + * For instance: + *
+         * // Published one day ago
+         * ASObject obj = Makers.object()
+         * .updatedFromNow(Duration.standardDays(-1))
+         * .get();
+         * 
+         * @param duration Duration
+         * @return B
+        
*/ + fun updatedFromNow(duration: ReadableDuration?): B { + return _dtFromNow("updated", duration) + } + + /** + * Set the updated timestamp as a given period from the current time. + * For instance: + *
+         * // Published one day ago
+         * ASObject obj = Makers.object()
+         * .updatedFromNow(Period.days(-1))
+         * .get();
+         * 
+         * @param period ReadablePeriod
+         * @return B
+        
*/ + fun updatedFromNow(period: ReadablePeriod?): B { + return _dtFromNow("updated", period) + } + + /** + * Set the updated timestamp as a given period from the current time + * @param v long + * @param unit TimeUnit + * @return B + */ + fun updatedFromNow(v: Long, unit: TimeUnit): B { + return _dtFromNow("updated", v, unit) + } + + /** + * Set the start time + * @param dt DateTime + * @return B + */ + fun startTime(dt: DateTime?): B { + return _dt("startTime", dt) + } + + /** + * Set the startTime timestamp as a given duration from the current time. + * For instance: + *
+         * // Published one day ago
+         * ASObject obj = Makers.object()
+         * .startTimeFromNow(Duration.standardDays(-1))
+         * .get();
+         * 
+         * @param duration Duration
+         * @return B
+        
*/ + fun startTimeFromNow(duration: ReadableDuration?): B { + return _dtFromNow("startTime", duration) + } + + /** + * Set the startTime timestamp as a given period from the current time. + * For instance: + *
+         * // Published one day ago
+         * ASObject obj = Makers.object()
+         * .startTimeFromNow(Period.days(-1))
+         * .get();
+         * 
+         * @param period ReadablePeriod
+         * @return B
+        
*/ + fun startTimeFromNow(period: ReadablePeriod?): B { + return _dtFromNow("startTime", period) + } + + /** + * Set the startTime timestamp as a given period from the current time. + * @param v long + * @param unit TimeUnit + * @return B + */ + fun startTimeFromNow(v: Long, unit: TimeUnit): B { + return _dtFromNow("startTime", v, unit) + } + + /** + * Set the start time to the current time + * @return B + */ + fun startTimeNow(): B { + return _dtNow("startTime") + } + + /** + * Set the end time + * @param dt DateTime + * @return B + */ + fun endTime(dt: DateTime?): B { + return _dt("endTime", dt) + } + + /** + * Set the endTime timestamp as a given duration from the current time. + * For instance: + *
+         * // Published one day ago
+         * ASObject obj = Makers.object()
+         * .startTimeFromNow(Duration.standardDays(-1))
+         * .get();
+         * 
+         * @param duration Duration
+         * @return B
+        
*/ + fun endTimeFromNow(duration: ReadableDuration?): B { + return _dtFromNow("endTime", duration) + } + + /** + * Set the endTime timestamp as a given period from the current time. + * For instance: + *
+         * // Published one day ago
+         * ASObject obj = Makers.object()
+         * .startTimeFromNow(Period.days(-1))
+         * .get();
+         * 
+         * @param period ReadablePeriod
+         * @return B
+        
*/ + fun endTimeFromNow(period: ReadablePeriod?): B { + return _dtFromNow("endTime", period) + } + + /** + * Set the endTime timestamp as a given period from the current time + * @param v long + * @param unit TimeUnit + * @return B + */ + fun endTimeFromNow(v: Long, unit: TimeUnit): B { + return _dtFromNow("endTime", v, unit) + } + + /** + * Set the end time + * @return B + */ + fun endTimeNow(): B { + return _dtNow("endTimeNow") + } + + /** + * Set the rating as a value in the range 0.00-1.00; + * @param d double + * @return B + * @throws IllegalArgumentException if the value is not + * within the proper range + */ + fun rating(d: Double): B { + return set("rating", checkRating(d)) + } + + /** + * Set the duration + * @param s int + * @return B + * @throws IllegalArgumentException if the value + * is less than zero + */ + fun duration(s: Long): B { + return duration(Duration.standardSeconds(checkNotNegative(s))) + } + + /** + * Set the duration as a Joda-Time Duration + * @param d Duration + * @return B + */ + fun duration(d: ReadableDuration?): B { + return set("duration", d) + } + + /** + * Set the duration as a Joda-Time Period + * @param period ReadablePeriod + * @return B + */ + fun duration(period: ReadablePeriod): B { + return duration(period.toPeriod().toStandardDuration()) + } + + /** + * Set the duration + * @param v long + * @param unit TimeUnit + * @return B + */ + fun duration(v: Long, unit: TimeUnit): B { + return duration(Converters.toDuration(v, unit)) + } + + /** + * Set the duration as a given period of time from the given reference + * @param p ReadablePeriod + * @param dt DateTime + * @return B + */ + fun durationFrom(p: ReadablePeriod, dt: DateTime?): B { + return duration(p.toPeriod().toDurationFrom(dt)) + } + + /** + * Set the duration as a given period of time from the current time + * @param p ReadablePeriod + * @return B + */ + fun durationFromNow(p: ReadablePeriod): B { + return duration(p.toPeriod().toDurationFrom(DateTime.now(DateTimeZone.UTC))) + } + + /** + * Set the height of the object in terms of number of device-independent + * pixels. + * @param h int + * @return B + */ + fun height(h: Int): B { + return set("height", checkNotNegative(h)) + } + + /** + * Set the width of the object in terms of number of device-independent + * pixels. + * @param h int + * @return B + */ + fun width(h: Int): B { + return set("width", checkNotNegative(h)) + } + + /** + * Set the MIME Media Type of the object + * @param mt String + * @return B + */ + fun mediaType(mt: String): B { + return mediaType(MediaType.parse(mt)) + } + + /** + * Set the MIME Media Type of the object + * @param mt com.google.common.net.MediaType + * @return B + */ + open fun mediaType(mt: MediaType?): B { + return set("mediaType", mt) + } + + /** + * Set the link relation + * @param rel String + * @return B + */ + fun rel(rel: String?): B { + return set("rel", rel) + } + + /** + * An objects alias is an alternative to it's "id". + * @param iri String + * @return B + */ + fun alias(iri: String?): B { + return set("alias", iri) + } + + /** + * Add an attachment + * @param url String + * @return B + */ + fun attachments(url: String?, vararg urls: String?): B { + if (url != null) link("attachments", Makers.linkValue(url)) + if (urls != null) for (u in urls) link("attachments", Makers.linkValue(u)) + return this as B + } + + /** + * Add an attachment. + * @param link LinkValue + * @return B + */ + fun attachments(link: LinkValue?, vararg links: LinkValue?): B { + if (link != null) link("attachments", link) + if (links != null) for (l in links) link("attachments", l) + return this as B + } + + /** + * Add an attachment + * @param link Supplier + * @return B + */ + fun attachments(link: Supplier): B { + return link("attachments", link.get()) + } + + /** + * Set the author + * @param url String + * @return B + */ + fun author(url: String?, vararg urls: String?): B { + if (url != null) link("author", Makers.linkValue(url)) + if (urls != null) for (u in urls) link("author", Makers.linkValue(u)) + return this as B + } + + /** + * Set the author + * @param link LinkValue + * @return B + */ + fun author(link: LinkValue?, vararg links: LinkValue?): B { + if (link != null) link("author", link) + if (links != null) for (l in links) link("author", l) + return this as B + } + + /** + * Set the author + * @param link Supplier + * @return B + */ + fun author(link: Supplier): B { + return link("author", link.get()) + } + + /** + * Add a duplicate + * @param url String + * @return B + */ + fun duplicates(url: String?, vararg urls: String?): B { + if (url != null) link("duplicates", Makers.linkValue(url)) + if (urls != null) for (u in urls) link("duplicates", Makers.linkValue(u)) + return this as B + } + + /** + * Add a duplicate + * @param link LinkValue + * @return B + */ + fun duplicates(link: LinkValue?, vararg links: LinkValue?): B { + if (link != null) link("duplicates", link) + if (links != null) for (l in links) link("duplicates", l) + return this as B + } + + /** + * Add a duplicate + * @param link Supplier + * @return B + */ + fun duplicates(link: Supplier): B { + return link("duplicates", link.get()) + } + + /** + * Set the icon + * @param url String + * @return B + */ + fun icon(url: String?, vararg urls: String?): B { + if (url != null) link("icon", Makers.linkValue(url)) + if (urls != null) for (u in urls) link("icon", Makers.linkValue(u)) + return this as B + } + + /** + * Set the icon + * @param link LinkValue + * @return B + */ + fun icon(link: LinkValue?, vararg links: LinkValue?): B { + if (link != null) link("icon", link) + if (links != null) for (l in links) link("icon", l) + return this as B + } + + /** + * Set the icon + * @param link Supplier + * @return B + */ + fun icon(link: Supplier): B { + return link("icon", link.get()) + } + + /** + * Set the image + * @param url String + * @return B + */ + fun image(url: String?, vararg urls: String?): B { + if (url != null) link("image", Makers.linkValue(url)) + if (urls != null) for (u in urls) link("image", Makers.linkValue(u)) + return this as B + } + + /** + * Set the image. + * @param link LinkValue + * @return B + */ + fun image(link: LinkValue?, vararg links: LinkValue?): B { + if (link != null) link("image", link) + if (links != null) for (l in links) link("image", l) + return this as B + } + + /** + * Set the image + * @param link Supplier + * @return B + */ + fun image(link: Supplier): B { + return link("image", link.get()) + } + + /** + * Set the location + * @param url String + * @return B + */ + fun location(url: String?, vararg urls: String?): B { + if (url != null) link("location", Makers.linkValue(url)) + if (urls != null) for (u in urls) link("location", Makers.linkValue(u)) + return this as B + } + + /** + * Set the location + * @param link LinkValue + * @return B + */ + fun location(link: LinkValue?, vararg links: LinkValue?): B { + if (link != null) link("location", link) + if (links != null) for (u in links) link("location", u) + return this as B + } + + /** + * Set the location + * @param link Supplier + * @return B + */ + fun location(link: Supplier): B { + return link("location", link.get()) + } + + /** + * Set the generator + * @param url String + * @return B + */ + fun generator(url: String?, vararg urls: String?): B { + if (url != null) link("generator", Makers.linkValue(url)) + if (urls != null) for (u in urls) link("generator", Makers.linkValue(u)) + return this as B + } + + /** + * Set the generator + * @param link LinkValue + * @return B + */ + fun generator(link: LinkValue?, vararg links: LinkValue?): B { + if (link != null) link("generator", link) + if (links != null) for (u in links) link("generator", u) + return this as B + } + + /** + * Set the generator. + * @param link Supplier + * @return B + */ + fun generator(link: Supplier): B { + return link("generator", link.get()) + } + + /** + * Set the provider + * @param url String + * @return B + */ + fun provider(url: String?, vararg urls: String?): B { + if (url != null) link("provider", Makers.linkValue(url)) + if (urls != null) for (u in urls) link("provider", Makers.linkValue(u)) + return this as B + } + + /** + * Set the provider + * @param link LinkValue + * @return B + */ + fun provider(link: LinkValue?, vararg links: LinkValue?): B { + if (link != null) link("provider", link) + if (links != null) for (l in links) link("provider", l) + return this as B + } + + /** + * Set the provider + * @param link Supplier + * @return B + */ + fun provider(link: Supplier): B { + return link("provider", link.get()) + } + + /** + * Add a tag + * @param url String + * @return B + */ + fun tags(url: String?, vararg urls: String?): B { + if (url != null) link("tags", Makers.linkValue(url)) + if (urls != null) for (u in urls) link("tags", Makers.linkValue(u)) + return this as B + } + + /** + * Add a tag + * @param link LinkValue + * @return B + */ + fun tags(link: LinkValue?, vararg links: LinkValue?): B { + if (link != null) link("tags", link) + if (links != null) for (l in links) link("tags", l) + return this as B + } + + /** + * Add a tag + * @param link Supplier + * @return B + */ + fun tags(link: Supplier): B { + return link("tags", link.get()) + } + + /** + * Add in-reply-to + * @param url String + * @return B + */ + fun inReplyTo(url: String?, vararg urls: String?): B { + if (url != null) link("inReplyTo", Makers.linkValue(url)) + if (urls != null) for (u in urls) link("inReplyTo", Makers.linkValue(u)) + return this as B + } + + /** + * Add in-reply-to + * @param link LinkValue + * @return B + */ + fun inReplyTo(link: LinkValue?, vararg links: LinkValue?): B { + if (link != null) link("inReplyTo", link) + if (links != null) for (l in links) link("inReplyTo", l) + return this as B + } + + /** + * Add in-reply-to + * @param link Supplier + * @return B + */ + fun inReplyTo(link: Supplier): B { + return link("inReplyTo", link.get()) + } + + /** + * Add a replies collection + * @param collection Collection + * @return B + */ + fun replies(collection: Collection?): B { + return set("replies", collection) + } + + /** + * Add a replies collection + * @param collection Supplier + * @return B + */ + fun replies(collection: Supplier): B { + return set("replies", collection.get()) + } + + /** + * Set the ID + * @param iri String + * @return B + */ + fun id(iri: String?): B { + return set("id", iri) + } + + /** + * Set the objectType + * @param iri String + * @return B + */ + fun objectType(iri: String?): B { + return set("objectType", Makers.type(iri)) + } + + /** + * Set the objectType + * @param tv TypeValue + * @return B + */ + fun objectType(tv: TypeValue?): B { + return set("objectType", tv) + } + + /** + * Set the objectType + * @param tv Supplier + * @return B + */ + fun objectType(tv: Supplier): B { + return objectType(tv.get()) + } + + /** + * Set the language + * @param lang String + * @return B + */ + fun language(lang: String?): B { + return set("language", lang) + } + + /** + * Set the displayName + * @param name String + * @return B + */ + fun displayName(name: String?): B { + return _nlv("displayName", name) + } + + /** + * Set the displayName + * @param nlv NLV + * @return B + */ + fun displayName(nlv: NLV?): B { + return _nlv("displayName", nlv) + } + + /** + * Set the displayName + * @param nlv Supplier + * @return B + */ + fun displayName(nlv: Supplier): B { + return _nlv("displayName", nlv) + } + + /** + * Set the displayName + * @param lang String + * @param name String + * @return B + */ + fun displayName(lang: String, name: String?): B { + return _nlv("displayName", lang, name) + } + + /** + * Set the displayName + * @param map Map,String> + * @return B + */ + fun displayName(map: Map): B { + return _nlv("displayName", map) + } + + /** + * Set the content + * @param name String + * @return B + */ + fun content(name: String?): B { + return _nlv("content", name) + } + + /** + * Set the content + * @param nlv NLV + * @return B + */ + fun content(nlv: NLV?): B { + return _nlv("content", nlv) + } + + /** + * Set the content + * @param nlv Supplier + * @return B + */ + fun content(nlv: Supplier): B { + return _nlv("content", nlv) + } + + /** + * Set the content + * @param lang String + * @param name String + * @return B + */ + fun content(lang: String, name: String?): B { + return _nlv("content", lang, name) + } + + /** + * Set the content + * @param map Map,String> + * @return B + */ + fun content(map: Map): B { + return _nlv("content", map) + } + + /** + * Set the summary + * @param name String + * @return B + */ + fun summary(name: String?): B { + return _nlv("summary", name) + } + + /** + * Set the summary + * @param nlv NLV + * @return B + */ + fun summary(nlv: NLV?): B { + return _nlv("summary", nlv) + } + + /** + * Set the summary + * @param nlv Supplier + * @return B + */ + fun summary(nlv: Supplier): B { + return _nlv("summary", nlv) + } + + /** + * Set the summary + * @param lang String + * @param name String + * @return B + */ + fun summary(lang: String, name: String?): B { + return _nlv("summary", lang, name) + } + + /** + * Set the summary + * @param map Map,String> + * @return B + */ + fun summary(map: Map): B { + return _nlv("summary", map) + } + + /** + * Set the title + * @param name String + * @return B + */ + fun title(name: String?): B { + return _nlv("title", name) + } + + /** + * Set the title + * @param nlv NLV + * @return B + */ + fun title(nlv: NLV?): B { + return _nlv("title", nlv) + } + + /** + * Set the title + * @param nlv Supplier + * @return B + */ + fun title(nlv: Supplier): B { + return _nlv("title", nlv) + } + + /** + * Set the title + * @param lang String + * @param value String + * @return B + */ + fun title(lang: String, value: String?): B { + return _nlv("title", lang, value) + } + + /** + * Set the title + * @param map Map,String> + * @return B + */ + fun title(map: Map): B { + return _nlv("title", map) + } + + /** + * Add an action handler + * @param verb String + * @param iri String + * @return B + */ + fun action(verb: String, iri: String?, vararg iris: String?): B { + if (iri != null) actions[verb] = iri + if (iris != null) for (i in iris) actions[verb] = i + return this as B + } + + /** + * Add an action handler + * @param verb String + * @param lv LinkValue + * @return B + */ + fun action(verb: String, lv: LinkValue?, vararg links: LinkValue): B { + if (lv != null) actions[verb] = lv + if (links != null) for (l in links) actions[verb] = l + return this as B + } + + /** + * Add an action handler + * @param verb String + * @param lv Supplier + * @return B + */ + fun action(verb: String, lv: Supplier): B { + return action(verb, lv.get()) + } + + /** + * Method _nlv. + * @param key String + * @param value String + * @return B + */ + protected fun _nlv(key: String, value: String?): B { + return set(key, Makers.nlv(value)) + } + + /** + * Method _nlv. + * @param key String + * @param nlv NLV + * @return B + */ + protected fun _nlv(key: String, nlv: NLV?): B { + return set(key, nlv) + } + + /** + * Method _nlv. + * @param key String + * @param nlv Supplier + * @return B + */ + protected fun _nlv(key: String, nlv: Supplier): B { + return set(key, nlv.get()) + } + + /** + * Method _nlv. + * @param key String + * @param map Map,String> + * @return B + */ + protected fun _nlv(key: String, map: Map): B { + for ((key1, value) in map) _nlv( + key, + key1, + value + ) + return this as B + } + + /** + * Method _nlv. + * @param key String + * @param lang String + * @param value String + * @return B + */ + protected fun _nlv(key: String, lang: String, value: String?): B { + if (map.containsKey(key)) { + val obj = map[key] + if (obj is NLV) { + when (obj.valueType()) { + ValueType.SIMPLE -> { + var l = map["language"] as String? + if (l == null) l = Util.DEFAULT_LOCALE + val b = + Makers.nlv() + if (lang == l) b[lang] = value + else b.set(l, (obj as SimpleNLV).value())[lang] = value + return set(key, b) + } + + ValueType.OBJECT -> return set( + key, + Makers.nlv() + .from(obj as MapNLV, lang) + .set(lang, value) + ) + + else -> throw IllegalArgumentException() + } + } else if (obj is MapNLV.Builder) { + obj[lang] = value + return this as B + } + } + set(key, Makers.nlv().set(lang, value)) + return this as B + } + + /** + * Set the "url" + * @param url String + * @return B + */ + fun url(url: String?, vararg urls: String?): B { + if (url != null) link("url", Makers.linkValue(url)) + if (urls != null) for (u in urls) link("url", Makers.linkValue(u)) + return this as B + } + + /** + * Set the "url" + * @param link Supplier + * @return B + */ + fun url(link: Supplier): B { + return url(link.get()) + } + + /** + * Set the "url" + * @param link LinkValue + * @return B + */ + fun url(link: LinkValue?, vararg links: LinkValue?): B { + if (link != null) link("url", link) + if (links != null) for (l in links) link("url", l) + return this as B + } + + /** + * Add a link + * @param name String + * @param url String + * @return B + */ + fun link(name: String, url: String?): B { + return link(name, Makers.linkValue(url)) + } + + /** + * Add a link + * @param name String + * @param link LinkValue + * @return B + */ + fun link(name: String, link: LinkValue?): B { + var link = link + ?: return this as B + val obj = map[name] + if (link.valueType() != ValueType.ARRAY) { + if (obj is LinkValue) link = + if (obj.valueType() == ValueType.ARRAY) Makers.linkValues() + .add(obj as Iterable) + .add(link) + .get() else Makers.linkValues() + .add(obj, link) + .get() + map[name] = link + } else set(name, link) + return this as B + } + + /** + * Add a link + * @param name String + * @param link Supplier + * @return B + */ + fun link(name: String, link: Supplier): B { + return link(name, link.get()) + } + + /** + * Add a link + * @param name String + * @param links Object[] + * @return B + */ + protected fun link(name: String, vararg links: Any?): B { + if (links == null) return this as B + val b: ArrayLinkValue.Builder = + ArrayLinkValue.Companion.make() + for (obj in links) _add(b, obj) + return link(name, b.get()) + } + + /** + * Method _add. + * @param builder ArrayLinkValue.Builder + * @param obj Object + */ + private fun _add(builder: ArrayLinkValue.Builder, obj: Any?) { + if (obj == null) return + else if (obj is String) builder.add(obj) + else if (obj is ASObject) builder.add(obj) + else if (obj is Supplier<*>) _add(builder, obj.get()) + else throw IllegalArgumentException() + } + + /** + * Set a property + * @param key String + * @param value V + * @return B + */ + open operator fun set(key: String, value: Any?): B { + if (value == null) return this as B + if (value is Supplier<*>) map[key] = + value.get() + else map[key] = value + return this as B + } + + /** + * Set a property + * @param key String + * @param value Supplier + * @return B + */ + fun set(key: String, value: Supplier<*>?): B { + try { + return if (value == null) this as B else set(key, value.get()) + } catch (t: Throwable) { + throw Throwables.propagate(t) + } + } + + /** + * Set a property from a given callable + * @param key String + * @param value Callable + * @return B + */ + fun set(key: String, value: Callable<*>?): B { + try { + return if (value == null) this as B else set(key, value.call()) + } catch (t: Throwable) { + throw Throwables.propagate(t) + } + } + + /** + * Set the scope + * @param url String + * @return B + */ + fun scope(url: String?, vararg urls: String?): B { + if (url != null) link("scope", Makers.linkValue(url)) + if (urls != null) for (u in urls) link("scope", Makers.linkValue(u)) + return this as B + } + + /** + * Set the scope + * @param link LinkValue + * @return B + */ + fun scope(link: LinkValue?, vararg links: LinkValue?): B { + if (link != null) link("scope", link) + if (links != null) for (l in links) link("scope", l) + return this as B + } + + /** + * Set the scope + * @param link Supplier + * + * @return B + */ + fun scope(link: Supplier): B { + return link("scope", link.get()) + } + } + + protected val map: ImmutableMap + + @Transient + private var hash = 1 + + /** + * Returns true if the given property exists, does not + * determine if the value is non-null + * @param key String + * @return boolean + */ + fun has(key: String?): Boolean { + return map.containsKey(key) + } + + /** + * Return the value of the property if it exists, null otherwise + * @param key String + * @return V + */ + fun get(key: String): V? { + return _get(key).orNull() + } + + /** + * Return the value of the property if it exists, casting to a DateTime + * object. + * @param key String + * @return DateTime + */ + fun getDateTime(key: String): DateTime? { + return get(key, Converters.toDateTime, Optional.absent()).orNull() + } + + /** + * Return the value of the property if it exists, converting the value + * to the given Enum class. + * @param key String + * @param _enumClass Class + * @return E + */ + fun ?> getEnum(key: String, _enumClass: Class): E? { + return getEnum(key, _enumClass, null as E?) + } + + /** + * Method getEnum. + * @param key String + * @param _enumClass Class + * @param or E + * @return E + */ + fun ?> getEnum(key: String, _enumClass: Class, or: E?): E? { + val `val` = getString(key) + val op = Enums.getIfPresent(_enumClass, `val`!!) + return if (or != null) op.or(or) else op.orNull() + } + + /** + * Return the value of the property if it exists, casting to a String + * object. + * @param key String + * @return String + */ + fun getString(key: String): String? { + return getString(key, null) + } + + /** + * Method getDuration. + * @param key String + * @return Duration + */ + fun getDuration(key: String): Duration? { + return get(key, Converters.toDuration, Optional.absent()).orNull() + } + + /** + * Method getPeriod. + * @param key String + * @return Period + */ + fun getPeriod(key: String): Period? { + return get(key, Converters.toPeriod, Optional.absent()).orNull() + } + + /** + * Method getInterval. + * @param key String + * @return Interval + */ + fun getInterval(key: String): Interval? { + return get(key, Converters.toInterval, Optional.absent()).orNull() + } + + /** + * Return the value of the property as a string if it exists or defaultValue if + * it does not. + * @param key String + * @param defaultValue String + * @return String + */ + fun getString(key: String, defaultValue: String?): String? { + return if (defaultValue != null) _get(key).or(defaultValue) else _get( + key + ).orNull() + } + + /** + * Return the value of the property as an int if it exists or 0 if it does not. + * @param key String + * @return int + */ + fun getInt(key: String): Int { + return getInt(key, 0) + } + + /** + * Return the value of the property as an int if it exists or defaultValue if + * it does not + * @param key String + * @param defaultValue int + * @return int + */ + fun getInt(key: String, defaultValue: Int): Int { + return get(key, Converters.toInt, Optional.absent()).or(defaultValue) + } + + /** + * Return the value of the property as a long if it exists or 0 if it does not + * @param key String + * @return long + */ + fun getLong(key: String): Long { + return getLong(key, 0L) + } + + /** + * Return the value of the property as a long if it exists or defaultValue if + * it does not + * @param key String + * @param defaultValue long + * @return long + */ + fun getLong(key: String, defaultValue: Long): Long { + return get(key, Converters.toLong, Optional.absent()).or(defaultValue) + } + + /** + * Return the value of the property as a double if it exists, or 0.0 if it + * does not + * @param key String + * @return double + */ + fun getDouble(key: String): Double { + return getDouble(key, 0.0) + } + + /** + * Return the value of the property as a double if it exists or defaultValue + * if it does not + * @param key String + * @param defaultValue double + * @return double + */ + fun getDouble(key: String, defaultValue: Double): Double { + return get(key, Converters.toDouble, Optional.absent()).or(defaultValue) + } + + /** + * Return the value of the property as a float if it exists or 0f if it + * does not + * @param key String + * @return float + */ + fun getFloat(key: String): Float { + return getFloat(key, 0f) + } + + /** + * Return the value of the property as a float if it exists or defaultValue + * if it does not + * @param key String + * @param defaultValue float + * @return float + */ + fun getFloat(key: String, defaultValue: Float): Float { + return get(key, Converters.toFloat, Optional.absent()).or(defaultValue) + } + + /** + * Return the value of the property as a short if it exists or 0 if it + * does not + * @param key String + * @return short + */ + fun getShort(key: String): Short { + return getShort(key, 0.toShort()) + } + + /** + * Return the value of the property as a short if it exists or defaultValue + * if it does not + * @param key String + * @param defaultValue short + * @return short + */ + fun getShort(key: String, defaultValue: Short): Short { + return get(key, Converters.toShort, Optional.absent()).or(defaultValue) + } + + /** + * return the value of the property as a boolean if it exists or false + * if it does not + * @param key String + * @return boolean + */ + fun getBoolean(key: String): Boolean { + return getBoolean(key, false) + } + + /** + * Return the value of the property as a boolean if it exists or defaultValue + * if it does not + * @param key String + * @param defaultValue boolean + * @return boolean + */ + fun getBoolean( + key: String, + defaultValue: Boolean + ): Boolean { + return get(key, Converters.toBoolean, Optional.absent()).or(defaultValue) + } + + /** + * Method _get. + * @param key String + * @return Optional + */ + private fun _get(key: String): Optional { + return Optional.fromNullable(map[key] as V?) + } + + /** + * Method _get. + * @param key String + * @param transform Function,V2> + * @return Optional + */ + private fun _get(key: String, transform: Function): Optional { + return _get(key).transform(transform) + } + + /** + * Return the value if it exists or defaultValue if it does not + * @param key String + * @param defaultValue V + * @return V + */ + fun get(key: String, defaultValue: V?): V? { + return if (defaultValue != null) _get(key).or(defaultValue) else _get(key).orNull() + } + + /** + * Returns the value of the property, transformed using the given function + * @param key String + * @param transform Function,V2> + * @return V2 + */ + fun get(key: String, transform: Function, defaultValue: V2): V2 { + return _get(key, transform).or(defaultValue) + } + + /** + * Returns the value of the given property converted using the given converter + * @param key String + * @param converter Converter,V2> + * @return V2 + */ + fun get(key: String, converter: Converter): V2? { + return _get(key, converter).orNull() + } + + /** + * Returns the value of the property if it exists or defaultValue if it + * does not + * @param key String + * @param def V2 + * @param transform Function,V2> + * @return V2 + */ + fun get(key: String, def: V2, transform: Function): V2 { + return _get(key, transform).or(def) + } + + /** + * Returns an iterator listing all of the properties defined on this object + * @return Iterator + * @see java.lang.Iterable.iterator + */ + override fun iterator(): MutableIterator { + return map.keys.iterator() + } + + /** + * Return this objects identifier + * @return String + * @see com.ibm.common.activitystreams.TypeValue.id + */ + override fun id(): String? { + return this.getString("id") + } + + /** + * Return the objectType + * @return T + */ + fun objectType(): T? { + return this.get("objectType") + } + + /** + * Return this object's type identifier as a string + * @return String + */ + fun objectTypeString(): String? { + return typeValueAsString("objectType") + } + + /** + * Method typeValueAsString. + * @param name String + * @return String + */ + protected fun typeValueAsString(name: String): String? { + val tv = this.get(name) + return tv?.id() + } + + /** + * Return this object's language context + * @return String + */ + fun language(): String? { + return this.getString("language") + } + + /** + * Return this objects displayName as an NLV object + * @return NLV + */ + fun displayName(): NLV { + return get("displayName")!! + } + + /** + * Return this objects displayName + * @return String + */ + fun displayNameString(): String? { + return _nlv("displayName") + } + + /** + * Method displayNameString. + * @param lang String + * @return String + */ + fun displayNameString(lang: String?): String? { + return _nlv("displayName", lang) + } + + /** + * Method _nlv. + * @param key String + * @return String + */ + protected fun _nlv(key: String): String? { + val lang = language() + return _nlv(key, lang ?: Util.DEFAULT_LOCALE) + } + + /** + * Method _nlv. + * @param key String + * @param lang String + * @return String + */ + protected fun _nlv(key: String, lang: String?): String? { + val nlv = + get(key)!! + when (nlv.valueType()) { + ValueType.SIMPLE -> { + val sim = + nlv as SimpleNLV + val l = language() + return if (l == null || Objects.equal(l, lang)) sim.value() else null + } + + ValueType.OBJECT -> { + val map = + nlv as MapNLV + return map.value(lang) + } + + else -> return null + } + } + + /** + * Return this objects URL LinkValues + * @return java.util.Iterable<LinkValue> + */ + fun url(): Iterable { + return links("url") + } + + /** + * Return the matching URL LinkValues + * @return java.util.Iterable<LinkValue> + */ + fun url(test: Predicate): Iterable { + return links("url", test) + } + + /** + * Return this objects first URL LinkValue + * @return LinkValue + */ + fun firstUrl(): LinkValue? { + return firstLink("url") + } + + /** + * Return this objects first matching LinkValue + * @param test + * @return LinkValue + */ + fun firstMatchingUrl(test: Predicate): LinkValue? { + return firstMatchingLink("url", test) + } + + /** + * Return this object's mediaType + * @return MediaType + */ + open fun mediaType(): MediaType? { + return this.get("mediaType") + } + + /** + * Returns the value of this objects's rel property + * @return String + */ + fun rel(): String? { + return this.getString("rel") + } + + /** + * Returns this value of this object's alias property + * @return String + */ + fun alias(): String? { + return this.getString("alias") + } + + /** + * Return the given set of links + * @param name String + * @return java.util.Iterable + */ + protected fun links(name: String): Iterable { + val lv = + get(name) ?: return ImmutableList.of() + return if (lv.valueType() == ValueType.ARRAY) lv as Iterable else ImmutableList.of(lv) + } + + protected fun links( + name: String, + test: Predicate + ): Iterable { + return Iterables.filter(links(name), test) + } + + protected fun firstLink(name: String): LinkValue? { + return Iterables.getFirst(links(name), null) + } + + protected fun firstMatchingLink( + name: String, + test: Predicate + ): LinkValue? { + return Iterables.getFirst(links(name, test), null) + } + + /** + * Return the set of attachments + * @return java.util.Iterable + */ + fun attachments(): Iterable { + return links("attachments") + } + + /** + * Return the matching set of attachments; + * @param test + * @return java.util.Iterable<LinkValue> + */ + fun attachments(test: Predicate): Iterable { + return links("attachments", test) + } + + /** + * Return the first attachment for this object + * @return LinkValue + */ + fun firstAttachment(): LinkValue? { + return firstLink("attachments") + } + + /** + * Return the first matching attachment + * @param test + * @return LinkValue + */ + fun firstMatchingAttachment(test: Predicate): LinkValue? { + return firstMatchingLink("attachments", test) + } + + /** + * Return this authors of this object + * @return java.util.Iterable + */ + fun author(): Iterable { + return links("author") + } + + /** + * Return the matching authors of this object + * @return java.util.Iterable + */ + fun author(test: Predicate): Iterable { + return links("author", test) + } + + /** + * Return the first author + * @return LinkValue + */ + fun firstAuthor(): LinkValue? { + return firstLink("author") + } + + /** + * Return the first matching author + * @param test + * @return LinkValue + */ + fun firstMatchingAuthor(test: Predicate): LinkValue? { + return firstMatchingLink("author", test) + } + + /** + * Return the collection of duplicates for this object + * @return java.util.Iterable + */ + fun duplicates(): Iterable { + return links("duplicates") + } + + /** + * Return the matching duplicates + * @param test + * @return java.util.Iterable<LinkValue> + */ + fun duplicates(test: Predicate): Iterable { + return links("duplicates", test) + } + + /** + * Return the first duplicate + * @return LinkValue + */ + fun firstDuplicate(): LinkValue? { + return firstLink("duplicates") + } + + /** + * Return the first matching duplicate + * @param test + * @return LinkValue + */ + fun firstMatchingDuplicate(test: Predicate): LinkValue? { + return firstMatchingLink("duplicates", test) + } + + /** + * Return the icons for this object + * @return java.util.Iterable + */ + fun icon(): Iterable { + return links("icon") + } + + /** + * Return the matching icons for this object + * @return java.util.Iterable + */ + fun icon(test: Predicate): Iterable { + return links("icon", test) + } + + /** + * Return the first icon + * @return LinkValue + */ + fun firstIcon(): LinkValue? { + return firstLink("icon") + } + + /** + * Return thie first matching icon + * @param test + * @return LinkValue + */ + fun firstMatchingIcon(test: Predicate): LinkValue? { + return firstMatchingLink("icon", test) + } + + /** + * Return the image for this object + * @return java.util.Iterable + */ + fun image(): Iterable { + return links("image") + } + + /** + * Return the matching images for this object + * @param test + * @return java.util.Iterable + */ + fun image(test: Predicate): Iterable { + return links("image", test) + } + + /** + * Return the first image + * @return LinkValue + */ + fun firstImage(): LinkValue? { + return firstLink("image") + } + + /** + * Return the first matching image + * @param test + * @return LinkValue + */ + fun firstMatchingImage(test: Predicate): LinkValue? { + return firstMatchingLink("image", test) + } + + /** + * Return the location associated with this object + * @return java.util.Iterable + */ + fun location(): Iterable { + return links("location") + } + + /** + * Return the matching locations associated with this object + * @param test + * @return java.util.Iterable + */ + fun location(test: Predicate): Iterable { + return links("location", test) + } + + /** + * Return the first location associated with this object + * @return LinkValue + */ + fun firstLocation(): LinkValue? { + return firstLink("location") + } + + /** + * Return the first matching location associated with this object + * @param test + * @return LinkValue + */ + fun firstMatchingLocation(test: Predicate): LinkValue? { + return firstMatchingLink("location", test) + } + + /** + * Return the generators for this object + * @return java.util.Iterable + */ + fun generator(): Iterable { + return links("generator") + } + + /** + * Return the matching generators for this object + * @return java.util.Iterable + */ + fun generator(test: Predicate): Iterable { + return links("generator", test) + } + + /** + * Return the first generator for this object + * @return LinkValue + */ + fun firstGenerator(): LinkValue? { + return firstLink("generator") + } + + /** + * Return the first matching generator for this object + * @param test + * @return LinkValue + */ + fun firstMatchingGenerator(test: Predicate): LinkValue? { + return firstMatchingLink("generator", test) + } + + /** + * Return the providers for this object + * @return java.util.Iterable + */ + fun provider(): Iterable { + return links("provider") + } + + /** + * Return the matching providers for this object + * @return java.util.Iterable + */ + fun provider(test: Predicate): Iterable { + return links("provider", test) + } + + /** + * Return the first provider for this object + * @return LinkValue + */ + fun firstProvider(): LinkValue? { + return firstLink("provider") + } + + /** + * Return the first matching providers for this object + * @param test + * @return LinkValue + */ + fun firstMatchingProvider(test: Predicate): LinkValue? { + return firstMatchingLink("provider", test) + } + + /** + * Return the tags for this object + * @return java.util.Iterable + */ + fun tags(): Iterable { + return links("tags") + } + + /** + * Return the matching tags for this object + * @return java.util.Iterable + */ + fun tags(test: Predicate): Iterable { + return links("tags", test) + } + + /** + * Return the first tag for this object + * @return LinkValue + */ + fun firstTag(): LinkValue? { + return firstLink("tags") + } + + /** + * Return this first matching tag for this object + * @param test + * @return LinkValue + */ + fun firstMatchingTag(test: Predicate): LinkValue? { + return firstMatchingLink("tags", test) + } + + /** + * Return the inReplyTo links for this object + * @return java.util.Iterable + */ + fun inReplyTo(): Iterable { + return links("inReplyTo") + } + + /** + * Return the matching inReplyTo links for this object + * @return java.util.Iterable + */ + fun inReplyTo(test: Predicate): Iterable { + return links("inReplyTo", test) + } + + /** + * Return the first inReplyTo link for this object + * @return LinkValue + */ + fun firstInReplyTo(): LinkValue? { + return firstLink("inReplyTo") + } + + /** + * Return the first matching inReplyTo link for this object + * @param test + * @return LinkValue + */ + fun firstMatchingInReplyTo(test: Predicate): LinkValue? { + return firstMatchingLink("inReplyTo", test) + } + + /** + * Return the content of this object + * @return NLV + */ + fun content(): NLV { + return get("content")!! + } + + /** + * Return the content of this object + * @return String + */ + fun contentString(): String? { + return _nlv("content") + } + + /** + * Return the content of this object for the given language + * @param lang String + * @return String + */ + fun contentString(lang: String?): String? { + return _nlv("content", lang) + } + + /** + * Return the title of this object + * @return NLV + */ + fun title(): NLV { + return get("title")!! + } + + /** + * Return the title of this object + * @return String + */ + fun titleString(): String? { + return _nlv("title") + } + + /** + * Return the title of this object for the given language + * @param lang String + * @return String + */ + fun titleString(lang: String?): String? { + return _nlv("title", lang) + } + + /** + * Return the summary of this object + * @return NLV + */ + fun summary(): NLV { + return get("summary")!! + } + + /** + * Return the summary of this object + * @return String + */ + fun summaryString(): String? { + return _nlv("summary") + } + + /** + * Return the summary of this object for the given language + * @param lang String + * @return String + */ + fun summaryString(lang: String?): String? { + return _nlv("summary", lang) + } + + /** + * Return the published timestamp for this object + * @return DateTime + */ + fun published(): DateTime? { + return this.getDateTime("published") + } + + /** + * Return the updated timestamp for this object + * @return DateTime + */ + fun updated(): DateTime? { + return this.getDateTime("updated") + } + + /** + * Return the startTime timestamp for this object + * @return DateTime + */ + fun startTime(): DateTime? { + return this.getDateTime("startTime") + } + + /** + * Return the endTime timestamp for this object + * @return DateTime + */ + fun endTime(): DateTime? { + return this.getDateTime("endTime") + } + + /** + * Return the rating property for this object + * @return double + */ + fun rating(): Double { + return checkRating(getDouble("rating")) + } + + /** + * Return the duration of this object + * @return Duration + */ + fun duration(): Duration? { + return get("duration", Converters.toDuration, Optional.absent()).orNull() + } + + /** + * Return the height of this object in device independent pixels + * @return int + */ + fun height(): Int { + return checkNotNegative(getInt("height")) + } + + /** + * Return the width of this object in device independent pixels + * @return int + */ + fun width(): Int { + return checkNotNegative(getInt("width")) + } + + /** + * Return the replies collection for this object + * @return Collection + */ + fun replies(): Collection { + return get("replies")!! + } + + /** + * Return the actions collection for this object + * @return ActionsValue + */ + fun actions(): ActionsValue { + return get("actions")!! + } + + /** + * Return the scope + * @return java.util.Iterable + */ + fun scope(): Iterable { + return links("scope") + } + + /** + * Return the matching scope items + * @return java.util.Iterable + */ + fun scope(test: Predicate): Iterable { + return links("scope", test) + } + + /** + * Return the first scope item + * @return LinkValue + */ + fun firstScope(): LinkValue? { + return firstLink("scope") + } + + /** + * Return the first matching scope item + * @param test + * @return LinkValue + */ + fun firstMatchingScope(test: Predicate): LinkValue? { + return firstMatchingLink("scope", test) + } + + override fun hashCode(): Int { + if (hash == 1) hash = Objects.hashCode(map) + return hash + } + + override fun equals(obj: Any?): Boolean { + if (this === obj) return true + if (obj == null) return false + if (javaClass != obj.javaClass) return false + val other = obj as ASObject + return Maps.difference(map, other.map) + .areEqual() + } + + /** + * Return the valueType of this object (always returns ValueType.OBJECT) + * @return ValueType + * @see com.ibm.common.activitystreams.LinkValue.valueType + */ + override fun valueType(): ValueType { + return ValueType.OBJECT + } + + + // Java Serialization support... + @Throws(ObjectStreamException::class) + open fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: ASObject) : AbstractSerializedForm(obj) { + override fun builder(): Builder { + return Makers.`object`() + } + + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + companion object { + private const val serialVersionUID = -1975376657749952999L + } + } + + protected abstract class AbstractSerializedForm
+ protected constructor(obj: A) : Serializable { + private val map: ImmutableMap = + ImmutableMap.copyOf( + Maps.transformValues( + obj!!.map, SerializableTransform + ) + ) + + protected abstract fun builder(): AbstractBuilder<*, *> + + @Throws(ObjectStreamException::class) + protected fun doReadResolve(): Any? { + val builder = builder() + for (entry in map.entries) { + var obj = entry.value + if (obj is SerializableMediaType) obj = obj.mediaType() + builder.set(entry.key, obj) + } + return builder.get() + } + + companion object { + private const val serialVersionUID = -801787904013409277L + } + } + + /** + * Constructor for ASObject. + * @param builder ASObject.AbstractBuilder + */ + init { + if (builder.actions.notEmpty()) builder.map["actions"] = builder.actions.get() + this.map = ImmutableMap.copyOf(builder.map) + } + + private class SerializableMediaType + (mt: MediaType) : Serializable { + private val mediaType = mt.toString() + fun mediaType(): MediaType { + return MediaType.parse(mediaType) + } + + companion object { + private const val serialVersionUID = -3162545492169619570L + } + } + + companion object { + /** + * Verifies that the rating value is within the proper range + * @param d double + * @return double + */ + private fun checkRating(d: Double): Double { + Preconditions.checkArgument(floor(d) >= 1 && ceil(d) <= 5) + return d + } + + /** + * Verifies that the value is non-negative + * @param i int + * @return int + */ + private fun checkNotNegative(i: Int): Int { + Preconditions.checkArgument(i >= 0) + return i + } + + /** + * Method checkNotNegative. + * @param l long + * @return long + */ + private fun checkNotNegative(l: Long): Long { + Preconditions.checkArgument(l >= 0) + return l + } + + private val SerializableTransform: Function = + Function { input -> + var input = input + if (input is MediaType) input = + SerializableMediaType(input) + input + } + } +} diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/ActionsValue.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/ActionsValue.kt new file mode 100644 index 0000000..4042194 --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/ActionsValue.kt @@ -0,0 +1,234 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams + +import com.google.common.base.Function +import com.google.common.base.Predicate +import com.google.common.base.Supplier +import com.google.common.collect.ImmutableMap +import com.ibm.common.activitystreams.LinkValue.SimpleLinkValue +import com.ibm.common.activitystreams.util.AbstractDictionaryObject +import java.io.ObjectStreamException +import java.io.Serializable + +/** + * + * The value of the "actions" property... used to map potential verbs + * with objects capable of "handling" those verbs. Each of the keys + * must be a valid verb (either a token or an absolute IRI). + * + * + * Specifying Actions while creating AS Objects: + * + *
+ * import static com.ibm.common.activitystreams.Makers.object;
+ * import static com.ibm.common.activitystreams.Makers.actions;
+ * import static com.ibm.common.activitystreams.actions.ActionMakers.intentAction;
+ * ...
+ *
+ * ASObject obj = object()
+ * .action("like", "http://example.org/like-action")
+ * .action("follow", intentAction())
+ * .get();
+
* + * + * + * Accessing Actions when consuming AS Objects: + * + *
+ * ActionsValue actions = obj.actions();
+ * for (LinkValue lv : actions.get("like")) {
+ * ...
+ * }
+
* + * + * + * The Actions object itself is a JSON Dictonary that maps + * verb identifiers to a Link Value that contains one or more + * Action Handlers. A call to the get(...) method returns an + * Iterable of Simple or Object LinkValue instances representing + * each of the associated Action Handlers. + * + * + * A Serialized Activity Stream object with Actions: + *
+ * {
+ * "objectType": "note",
+ * "displayName": "My Note",
+ * "actions": {
+ * "like": "http://example.org/like-action",
+ * "follow": {
+ * "objectType": "IntentActionHandler",
+ * "displayName": "Follow updates to this note!"
+ * }
+ * }
+ * }
+
* + * + * @author james + * @version $Revision: 1.0 $ + */ +class ActionsValue +private constructor(builder: Builder) : AbstractDictionaryObject(builder), + Serializable { + /** + * Builder for ActionsValue objects. + *
+     * Makers.actions()
+     * .set("like", "http://example.org/like-action")
+     * .set("follow", ActionMakers.intentAction())
+     * .get();
+    
* + */ + class Builder + + : AbstractBuilder() { + /** + * Add an action handler for the given verb. + * Calling this multiple times results in + * multiple action handlers. + * @param verb String + * @param iri String + * @return Builder + */ + operator fun set(verb: String, iri: String?): Builder { + return set( + verb, + SimpleLinkValue.Companion.make(iri) + ) + } + + override operator fun set(key: String, x: LinkValue?): Builder { + return super.link(key, x)!! + } + + override fun set(key: String, x: Supplier): Builder { + return super.link(key, x)!! + } + + /** + * Get the built ActionsValue instance + * @return ParametersValue + * @see com.google.common.base.Supplier.get + */ + override fun get(): ActionsValue { + return ActionsValue(this) + } + } + + /** + * Get all Action Handlers associated with the given verb. + * @param verb String + * @return java.util.Iterable + */ + fun get(verb: String?): Iterable { + return super.getIterable(verb) + } + + /** + * Get all Action Handlers associated with the given verb + * that satisfy the given filter + * @param verb String + * @param filter Predicate + * @return java.util.Iterable + */ + fun get( + verb: String?, + filter: Predicate + ): Iterable { + return super.getIterable(verb, filter) + } + + /** + * Get all Action Handlers associated with the given verb, + * transformed using the given Transform function + * @param verb String + * @param transform Function,Y> + * @return java.util.Iterable + */ + fun get( + verb: String?, + transform: Function + ): Iterable { + return super.getIterable(verb, transform) + } + + /** + * Get all Action Handlers associated with the given verb, + * filtered using the given Predicate and transformed + * using the given Transform function. + * @param verb String + * @param filter Predicate + * @param transform Function,Y> + * @return java.util.Iterable + */ + fun get( + verb: String?, + filter: Predicate, + transform: Function + ): Iterable { + return super.getIterable(verb, filter, transform) + } + + /** + * True if there is at least one Action Handler associated + * with the given verb + * @param verb String + * @return boolean + */ + public override fun hasAtLeastOne(verb: String?): Boolean { + return super.hasAtLeastOne(verb) + } + + // Java serialization support + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: ActionsValue) : Serializable { + private val map: ImmutableMap + + init { + val builder = + ImmutableMap.builder() + for (key in obj) builder.put(key, obj.get(key)) + this.map = builder.build() + } + + @Throws(ObjectStreamException::class) + fun readResolve(): Any { + val builder = + Makers.actions() + for ((key, value) in map) { + val list = value as Iterable + for (link in list) builder[key] = link + } + return builder.get() + } + + companion object { + private const val serialVersionUID = -1975376657749952999L + } + } +} diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/Activity.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/Activity.kt new file mode 100644 index 0000000..87b7447 --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/Activity.kt @@ -0,0 +1,820 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams + +import com.google.common.base.Preconditions +import com.google.common.base.Predicate +import com.google.common.base.Supplier +import java.io.ObjectStreamException +import java.io.Serializable +import java.util.* +import kotlin.math.ceil +import kotlin.math.floor + +/** + * An Activity Streams 2.0 Activity + * + * + * Creating an Activity: + *
+ * import static com.ibm.common.activitystreams.Makers.activity;
+ * import static com.ibm.common.activitystreams.Makers.object;
+ * ...
+ *
+ * Activity activity = activity()
+ * .actor("acct:joe@example.org")
+ * .verb("post")
+ * .object(object().content("This is a note"))
+ * .get();
+
* + * + * + * Consuming an Activity: + *
+ * Activity activity = IO.makeDefault().readAsActivity(...);
+ *
+ * System.out.println(activity.verbAsString());
+ * ASObject actor = activity.firstActor();
+ * ASObject object = activity.firstObject();
+
* + * + * @author james + * @version $Revision: 1.0 $ + */ +class Activity +internal constructor(builder: AbstractBuilder<*, *>) : ASObject(builder), Serializable { + enum class Audience { + /** + * Primary public audience + */ + TO, + + /** + * Primary private audience + */ + BTO, + + /** + * Secondary public audience + */ + CC, + + /** + * Secondary private audience + */ + BCC, + + /** + * Public origin + */ + FROM, + + /** + * Private origin + */ + BFROM; + + val label: String = name.lowercase(Locale.getDefault()) + + /** + * Returns the "from" target(s) + * @return java.util.Iterable<LinkValue> + */ + fun get( + activity: Activity + ): Iterable? { + return activity.links(label) + } + + fun get( + activity: Activity, + filter: Predicate + ): Iterable { + return activity.links(label, filter) + } + + fun first(activity: Activity): LinkValue? { + return activity.firstLink(label) + } + + fun firstMatching( + activity: Activity, + test: Predicate + ): LinkValue? { + return activity.firstMatchingLink(label, test) + } + } + + enum class Status { + /** The Activity is tentatively scheduled to begin */ + TENTATIVE, + + /** The Activity is scheduled to begin */ + PENDING, + + /** The Activity has been completed */ + COMPLETED, + + /** The Activity has been canceled or aborted */ + CANCELED, + + /** The Activity is currently active */ + ACTIVE, + + /** The Activity has been voided. */ + VOIDED, + OTHER + } + + /** + * + * Builder for concrete Activity object instances. + * + * @author james + * @version $Revision: 1.0 $ + */ + class Builder + + : AbstractBuilder() { + /** + * Get the built Activity object + * @return Activity + * @see com.google.common.base.Supplier.get + */ + override fun get(): Activity { + return Activity(this) + } + } + + /** + * Abstract builder for Activity classes. This is defined this way + * to make it easier to build extensions of the Activity class. + * @author james + * @version $Revision: 1.0 $ + */ + abstract class AbstractBuilder +
?> + : ASObject.AbstractBuilder() { + /** + * Set the Activity status property. + * @param status Status + * @return B + */ + fun status(status: Status?): B { + if (status != null) set("status", status) + return this as B + } + + /** + * Mark the status of this activity as being "voided" + * @return B + */ + fun voided(): B { + return status(Status.VOIDED) + } + + /** + * Mark the status of this activity as being "tentative" + * @return B + */ + fun tentative(): B { + return status(Status.TENTATIVE) + } + + /** + * Mark the status of this activity as being "pending" + * @return B + */ + fun pending(): B { + return status(Status.PENDING) + } + + /** + * Mark the status of this activity as being "active" + * @return B + */ + fun active(): B { + return status(Status.ACTIVE) + } + + /** + * Mark the status of this activity as being "canceled" + * @return B + */ + fun canceled(): B { + return status(Status.CANCELED) + } + + /** + * Mark the status of this activity as being "completed" + * @return B + */ + fun completed(): B { + return status(Status.COMPLETED) + } + + /** + * Set the verb for this activity + * @param iri String + * @return B + */ + fun verb(iri: String?): B { + set("verb", Makers.type(iri)) + return this as B + } + + /** + * Set the verb for this activity + * @param tv TypeValue + * @return B + */ + fun verb(tv: TypeValue?): B { + set("verb", tv) + return this as B + } + + /** + * Set the verb for this activity + * @param tv Supplier + * @return B + */ + fun verb(tv: Supplier): B { + return verb(tv.get()) + } + + /** + * Set a participant that indirectly contributed to the activity. + * @param url String + * @return B + */ + fun participant(url: String?, vararg urls: String?): B { + if (url != null) link("participant", Makers.linkValue(url)) + if (urls != null) for (u in urls) link("participant", Makers.linkValue(u)) + return this as B + } + + /** + * Set a participant that indirectly contributed to the activity + * @param link LinkValue + * @return B + */ + fun participant(link: LinkValue?, vararg links: LinkValue?): B { + if (link != null) link("participant", link) + if (links != null) for (l in links) link("participant", l) + return this as B + } + + /** + * Set a participant that indirectly contributed to the activity + * @param link Supplier + * @return B + */ + fun participant(link: Supplier): B? { + return link("participant", link.get()) + } + + /** + * Set the instrument used to complete the activity + * @param url String + * @return B + */ + fun instrument(url: String?, vararg urls: String?): B { + if (url != null) link("instrument", Makers.linkValue(url)) + if (urls != null) for (u in urls) link("instument", Makers.linkValue(u)) + return this as B + } + + /** + * Set the instrument used to complete the activity + * @param link LinkValue + * @return B + */ + fun instrument(link: LinkValue?, vararg links: LinkValue?): B { + if (link != null) link("instrument", link) + if (links != null) for (l in links) link("instrument", l) + return this as B + } + + /** + * Set the instrument used to complete the activity + * @param link Supplier + * @return B + */ + fun instrument(link: Supplier): B? { + return link("instrument", link.get()) + } + + /** + * Set the primary actor/agent for this activity + * @param url String + * @return B + */ + fun actor(url: String?, vararg urls: String?): B { + if (url != null) link("actor", Makers.linkValue(url)) + if (urls != null) for (u in urls) link("actor", Makers.linkValue(u)) + return this as B + } + + /** + * Set the primary actor/agent for this activity + * @param link LinkValue + * @return B + */ + fun actor(link: LinkValue?, vararg links: LinkValue?): B { + if (link != null) link("actor", link) + if (links != null) for (l in links) link("actor", l) + return this as B + } + + /** + * Set the actor + * @param link Supplier + * @return B + */ + fun actor(link: Supplier): B? { + return link("actor", link.get()) + } + + /** + * Set the direct object of this activity (the object that has been + * or will be acted upon) + * @param url String + * @return B + */ + fun `object`(url: String?, vararg urls: String?): B { + if (url != null) link("object", Makers.linkValue(url)) + if (urls != null) for (u in urls) link("object", Makers.linkValue(u)) + return this as B + } + + /** + * Set the direct object of this activity (the object that has been + * or will be acted upon) + * @param link LinkValue + * @return B + */ + fun `object`(link: LinkValue?, vararg links: LinkValue?): B { + if (link != null) link("object", link) + if (links != null) for (l in links) link("object", l) + return this as B + } + + /** + * Set the direct object of this activity (the object that has been + * or will be acted upon) + * @param link Supplier + * @return B + */ + fun `object`(link: Supplier): B? { + return link("object", link.get()) + } + + /** + * Set an object that is indirectly affected by the activity + * @param url String + * @return B + */ + fun target(url: String?, vararg urls: String?): B { + if (url != null) link("target", Makers.linkValue(url)) + if (urls != null) for (u in urls) link("target", Makers.linkValue(u)) + return this as B + } + + /** + * Set an object that is indirectly affected by the activity + * @param link LinkValue + * @return B + */ + fun target(link: LinkValue?, vararg links: LinkValue?): B { + if (link != null) link("target", link) + if (links != null) for (l in links) link("target", l) + return this as B + } + + /** + * Set an object that is indirectly affected by the activity + * @param link Supplier + * @return B + */ + fun target(link: Supplier): B? { + return link("target", link.get()) + } + + /** + * Set a URI that describes the result of this activity + * @param url String + * @return B + */ + fun result(url: String?, vararg urls: String?): B { + if (url != null) link("result", Makers.linkValue(url)) + if (urls != null) for (u in urls) link("result", Makers.linkValue(u)) + return this as B + } + + /** + * Set an object that describes the result of this activity + * @param link LinkValue + * @return B + */ + fun result(link: LinkValue?, vararg links: LinkValue?): B { + if (link != null) link("result", link) + if (links != null) for (l in links) link("result", l) + return this as B + } + + /** + * Set an object that describes the result of this activity + * @param link Supplier + * @return B + */ + fun result(link: Supplier): B? { + return link("result", link.get()) + } + + /** + * Set the audience for this activity + * @param audience + * @param url + * @param urls + * @return B + */ + fun audience(audience: Audience, url: String?, vararg urls: String?): B { + link(audience.label, Makers.linkValue(url)) + for (u in urls) link(audience.label, u) + return this as B + } + + /** + * Set the audience for this activity + * @param audience + * @param link + * @param links + * @return B + */ + fun audience(audience: Audience, link: LinkValue?, vararg links: LinkValue?): B { + link(audience.label, link) + for (lv in links) link(audience.label, lv) + return this as B + } + + /** + * Set the audience for this activity + * @param audience + * @param link + * @return B + */ + fun audience(audience: Audience, link: Supplier): B? { + return link(audience.label, link) + } + + /** + * Set the priority as value in the range 0.00 to 1.00. + * Value will be checked to ensure it is within the valid range. + * The value SHOULD be limited to two decimal places but the + * number of decimals will not be checked. + * @param d double + * @return B + * @throws IllegalArgumentException if the value is not within 0.00-1.00 + */ + fun priority(d: Double): B? { + return set("priority", checkPriority(d)) + } + } + + /** + * returns the verb as TypeValue object + * @return T + */ + fun verb(): T? { + return this.get("verb") + } + + /** + * Returns the verb as a string + * @return String + */ + fun verbString(): String? { + return typeValueAsString("verb") + } + + /** + * Return the participant(s) + * @return java.util.Iterable<LinkValue> + */ + fun participant(): Iterable? { + return links("participant") + } + + /** + * Return the matching participant(s) + * @param filter + * @return java.util.Iterable + */ + fun participant(filter: Predicate?): Iterable { + return links("participant", filter!!) + } + + /** + * Return the first paticipant + * @return LinkValue + */ + fun firstParticipant(): LinkValue? { + return firstLink("participant") + } + + /** + * Return the first matching participant + * @param test + * @return LinkValue + */ + fun firstMatchingParticipant(test: Predicate?): LinkValue? { + return firstMatchingLink("participan", test!!) + } + + /** + * Return the instrument(s) + * @return java.util.Iterable<LinkValue> + */ + fun instrument(): Iterable? { + return links("instrument") + } + + /** + * Return the matching instrument(s) + * @param filter + * @return java.util.Iterable + */ + fun instrument(filter: Predicate?): Iterable { + return links("instrument", filter!!) + } + + /** + * Return the first instrument + * @return LinkValue + */ + fun firstInstrument(): LinkValue? { + return firstLink("instrument") + } + + /** + * Return the first matching instrument + * @param test + * @return LinkValue + */ + fun firstMatchingInstrument(test: Predicate?): LinkValue? { + return firstMatchingLink("instrument", test!!) + } + + /** + * Returns the actor(s) + * @return java.util.Iterable<LinkValue> + */ + fun actor(): Iterable? { + return links("actor") + } + + /** + * Return the matching actor(s) + * @param filter + * @return java.util.Iterable + */ + fun actor(filter: Predicate?): Iterable { + return links("actor", filter!!) + } + + /** + * Return the first actor + * @return LinkValue + */ + fun firstActor(): LinkValue? { + return firstLink("actor") + } + + /** + * Return the first matching actor + * @param test + * @return LinkValue + */ + fun firstMatchingActor(test: Predicate?): LinkValue? { + return firstMatchingLink("actor", test!!) + } + + /** + * Returns the object(s) + * @return java.util.Iterable<LinkValue> + */ + fun `object`(): Iterable? { + return links("object") + } + + /** + * Return the matching object(s) + * @param filter + * @return java.util.Iterable + */ + fun `object`(filter: Predicate?): Iterable { + return links("object", filter!!) + } + + /** + * Return the first object + * @return LinkValue + */ + fun firstObject(): LinkValue? { + return firstLink("object") + } + + /** + * Return the first matching object + * @param test + * @return LinkValue + */ + fun firstMatchingObject(test: Predicate?): LinkValue? { + return firstMatchingLink("object", test!!) + } + + /** + * Returns the target(s) + * @return java.util.Iterable<LinkValue> + */ + fun target(): Iterable? { + return links("target") + } + + /** + * Return the matching target(s) + * @param filter + * @return java.util.Iterable + */ + fun target(filter: Predicate?): Iterable { + return links("target", filter!!) + } + + /** + * Return the first target + * @return LinkValue + */ + fun firstTarget(): LinkValue? { + return firstLink("target") + } + + /** + * Return the first matching target + * @param test + * @return LinkValue + */ + fun firstMatchingTarget(test: Predicate?): LinkValue? { + return firstMatchingLink("target", test!!) + } + + /** + * Returns the result(s) + * @return java.util.Iterable<LinkValue> + */ + fun result(): Iterable? { + return links("result") + } + + /** + * Returns the matching result(s) + * @param filter + * @return java.util.Iterable<LinkValue> + */ + fun result(filter: Predicate?): Iterable { + return links("result", filter!!) + } + + /** + * Return the first result + * @return LinkValue + */ + fun firstResult(): LinkValue? { + return firstLink("result") + } + + /** + * Return the first matching result + * @param test + * @return LinkValue + */ + fun firstMatchingResult(test: Predicate?): LinkValue? { + return firstMatchingLink("result", test!!) + } + + /** + * Returns the priority. + * @return double + * @throws IllegalArgumentException if the priority is not within + * the range 0.00-1.00 + */ + fun priority(): Double { + return checkPriority(getDouble("priority")) + } + + /** + * Return the audience for this activity + * @param audience + * @return java.util.Iterable<LinkValue> + */ + fun audience( + audience: Audience + ): Iterable? { + return audience.get(this) + } + + /** + * Return the audience for this activity + * @param audience + * @param filter + * @return java.util.Iterable<LinkValue> + */ + fun audience( + audience: Audience, + filter: Predicate + ): Iterable { + return audience.get(this, filter) + } + + /** + * Return the first audience for this activity + * @param audience + * @return LinkValue + */ + fun firstAudience(audience: Audience): LinkValue? { + return audience.first(this) + } + + /** + * Return the first matching audience for this activity + * @param audience + * @param test + * @return LinkValue + */ + fun firstMatchingAudience( + audience: Audience, + test: Predicate + ): LinkValue? { + return audience.firstMatching(this, test) + } + + /** + * Return the status of this activity + * @return Status + */ + fun status(): Status? { + return get("status") + } + + // Java Serialization Support + @Throws(ObjectStreamException::class) + override fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: Activity) : AbstractSerializedForm(obj) { + override fun builder(): Builder { + return Makers.activity() + } + + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + companion object { + private const val serialVersionUID = -1975376657749952999L + } + } + + companion object { + /** + * Ensures that the priority value is within the acceptable range (0.0-1.0) + * @param d double + * @return double + */ + private fun checkPriority(d: Double): Double { + Preconditions.checkArgument(floor(d) >= 0 && ceil(d) >= 1) + return d + } + } +} diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/Collection.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/Collection.kt new file mode 100644 index 0000000..e6bc078 --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/Collection.kt @@ -0,0 +1,529 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams + +import com.google.common.base.Preconditions +import com.google.common.base.Predicate +import com.google.common.base.Supplier +import com.google.common.collect.ImmutableList +import com.google.common.collect.ImmutableSet +import com.google.common.collect.Iterables +import com.ibm.common.activitystreams.LinkValue.ArrayLinkValue +import org.joda.time.DateTime +import org.joda.time.ReadableDuration +import org.joda.time.ReadablePeriod +import java.io.ObjectStreamException +import java.io.Serializable +import java.util.* +import java.util.concurrent.TimeUnit + +/** + * + * An Activity Streams collection object + * + *
+ * import static com.ibm.common.activitystreams.Makers.collection;
+ * import static com.ibm.common.activitystreams.Makers.object;
+ * ...
+ *
+ * Collection collection = collection()
+ * .items(object()...)
+ * .items(object()...)
+ * .get();
+
* + * + * @author james + * @version $Revision: 1.0 $ + */ +class Collection + +/** + * Constructor for Collection. + * @param builder Collection.AbstractBuilder + */ +internal constructor(builder: AbstractBuilder<*, *>) : ASObject(builder), Serializable { + /** Standardized Paging Links */ + enum class Page { + /** + * Reference to the first page in the logical set + */ + FIRST, + + /** + * Reference to the next page in the logical set + */ + NEXT, + + /** + * Reference to the final page in the logical set + */ + LAST, + + /** + * Reference to the previous page in the logical set + */ + PREVIOUS, + + /** + * Reference to the previous page in the logical set (treated as an alias for "previous") + */ + @Deprecated("Use Page.PREVIOUS instead") + PREV, + + /** + * Reference to the page containing the most recently published/updated + * items in the logical set + */ + CURRENT, + + /** + * Reference to this page + */ + SELF; + + val label: String = name.lowercase(Locale.getDefault()) + + private fun checkPrev(col: Collection, or: String): String { + if (this == PREVIOUS) { + if (!col.has(label) && col.has(label)) return label + } else if (this == PREV) { + if (!col.has(label) && col.has(label)) return label + } + return or + } + + fun links(col: Collection): Iterable? { + return col.links(checkPrev(col, label)) + } + + fun links( + col: Collection, + filter: Predicate + ): Iterable { + return col.links(checkPrev(col, label), filter) + } + + fun first(col: Collection): LinkValue? { + return col.firstLink(checkPrev(col, label)) + } + + fun firstMatching( + col: Collection, + filter: Predicate + ): LinkValue? { + return col.firstMatchingLink(checkPrev(col, label), filter) + } + } + + /** + * @author james + * @version $Revision: 1.0 $ + */ + class Builder + + : AbstractBuilder() { + /** + * Method create. + * @return Collection + */ + override fun create(): Collection { + return Collection(this) + } + } + + /** + * @author james + * @version $Revision: 1.0 $ + */ + abstract class AbstractBuilder +
?> + : ASObject.AbstractBuilder() { + protected val list: ImmutableList.Builder = ImmutableList.builder() + + /** + * Method create. + * @return A + */ + protected abstract fun create(): A + + override fun set(key: String, value: Any?): B? { + if (key == "items") { + if (value is ArrayLinkValue) { + for (lv in value) { + list.add(lv as ASObject) + } + } else if (value is ASObject) list.add(value) + return this as B + } else return super.set(key, value) + } + + + /** + * Method get. + * @return A + * @see com.google.common.base.Supplier.get + */ + override fun get(): A { + super.set("items", list.build()) + return create() + } + + /** + * Add items to this collection + * @param objs java.util.Iterable + * @return B + */ + fun items(objs: Iterable?): B { + if (objs == null) return this as B + for (obj in objs) items(obj) + return this as B + } + + /** + * Add items to this collection + * @param obj ASObject The object to add + * @param objs ASObject[] Additional objects to add (vararg) + * @return B + */ + fun items(obj: ASObject?, vararg objs: ASObject): B { + if (obj == null) return this as B + list.add(obj) + if (objs != null) for (o in objs) list.add(o) + return this as B + } + + /** + * Add an item to this collection + * @param obj com.google.common.base.Supplier + * @return B + */ + fun items(obj: Supplier?): B { + if (obj == null) return this as B + items(obj.get()) + return this as B + } + + /** + * Set the total number of items (must be non-negative) + * @param i int + * @return B + */ + fun totalItems(i: Int): B { + Preconditions.checkArgument(i >= 0) + set("totalItems", i) + return this as B + } + + /** + * Set the number of items per page (must be non-negative) + * @param i int + * @return B + */ + fun itemsPerPage(i: Int): B { + Preconditions.checkArgument(i >= 0) + set("itemsPerPage", i) + return this as B + } + + /** + * Set the starting index (must be non-negative) + * @param i int + * @return B + */ + fun startIndex(i: Int): B { + Preconditions.checkArgument(i >= 0) + set("startIndex", i) + return this as B + } + + /** + * Specify that the collection contains items updated after the specified time + * @param dt DateTime + * @return B + */ + fun itemsAfter(dt: DateTime?): B? { + return _dt("itemsAfter", dt) + } + + /** + * Specify that the collection contains items updated after right now + * @return B + */ + fun itemsAfterNow(): B? { + return _dtNow("itemsAfter") + } + + /** + * Specify that the collection contains items updated a specific duration after now + * @param duration Duration + * @return B + */ + fun itemsAfterFromNow(duration: ReadableDuration?): B? { + return _dtFromNow("itemsAfter", duration) + } + + /** + * Specify that the collection contains items updated a specific period after now + * @param period + * @return B + */ + fun itemsAfterFromNow(period: ReadablePeriod?): B? { + return _dtFromNow("itemsAfter", period) + } + + /** + * Specify that the collection contains items updated a specific duration after now + * @param v long + * @param unit TimeUnit + * @return B + */ + fun itemsAfterFromNow(v: Long, unit: TimeUnit?): B? { + return _dtFromNow("itemsAfter", v, unit!!) + } + + /** + * Specify that the collection contains items updated before a specific time + * @param dt DateTime + * @return B + */ + fun itemsBefore(dt: DateTime?): B? { + return _dt("itemsBefore", dt) + } + + /** + * Specify that the collection contains items updated before now + * @return B + */ + fun itemsBeforeNow(): B? { + return _dtNow("itemsBefore") + } + + /** + * Specify that the collection contains items updated a specific duration + * before now + * @param duration Duration + * @return B + */ + fun itemsBeforeFromNow(duration: ReadableDuration?): B? { + return _dtFromNow("itemsBefore", duration) + } + + /** + * Specify that the collection contains items updated a specific period + * before now + * @param period + * @return B + */ + fun itemsBeforeFromNow(period: ReadablePeriod?): B? { + return _dtFromNow("itemsBefore", period) + } + + /** + * Method itemsBeforeFromNow. + * @param v long + * @param unit TimeUnit + * @return B + */ + fun itemsBeforeFromNow(v: Long, unit: TimeUnit?): B? { + return _dtFromNow("itemsBefore", v, unit!!) + } + + /** + * Adds a paging link + *
+         * Collection collection = Makers.collection()
+         * .pageLink(Page.NEXT, "http://example.org")
+         * .get();
+        
* + * @param page + * @param url + * @return B + */ + fun pageLink(page: Page, url: String?): B? { + return link(page.label, Makers.linkValue(url)) + } + + /** + * Adds a paging link + * @param page + * @param link + * @return B + */ + fun pageLink(page: Page, link: LinkValue?): B? { + return link(page.label, link) + } + + /** + * Adds a paging link + * @param page + * @param link + * @return B + */ + fun pageLink(page: Page, link: Supplier): B? { + return link(page.label, link) + } + } + + /** + * Returns the total number of items + * @return int + */ + fun totalItems(): Int { + return getInt("totalItems") + } + + /** + * If not null, indicates that the collection only contains items + * updated after the given instant + * @return DateTime + */ + fun itemsAfter(): DateTime? { + return this.getDateTime("itemsAfter") + } + + /** + * If not null, indicates that the collection only contains items + * updated before the given instant + * @return DateTime + */ + fun itemsBefore(): DateTime? { + return this.getDateTime("itemsBefore") + } + + /** + * Returns the number of items per page + * @return int + */ + fun itemsPerPage(): Int { + return this.getInt("itemsPerPage") + } + + /** + * Returns the start index for this page + * @return int + */ + fun startIndex(): Int { + return this.getInt("startIndex") + } + + /** + * Returns a listing of Paging links that + * exist on this collection + * @return Iterable<Page> + */ + fun pages(): Iterable { + val pages = + ImmutableSet.builder() + for (page in Page.entries) if (has(page.label)) pages.add(page) + return pages.build() + } + + /** + * Returns a listing of Paging LinkValues + * @param page Page The type of paging link to return + * @return Iterable<LinkValue> + */ + fun pageLink( + page: Page + ): Iterable? { + return page.links(this) + } + + /** + * Returns a listing of Paging LinkValues + * @param page Page The type of paging link to return + * @param filter Predicate A filter + * @return Iterable<LinkValue> + */ + fun pageLink( + page: Page, + filter: Predicate + ): Iterable { + return page.links(this, filter) + } + + /** + * Returns the first matching paging LinkValue + * @param page Page The type of paging link to return + * @return LinkValue + */ + fun firstPageLink( + page: Page + ): LinkValue? { + return page.first(this) + } + + /** + * Returns the first matching paging LinkValue + * @param page Page the type of paging link to return + * @param test com.google.common.base.Predicate a filter + * @return LinkValue + */ + fun firstMatchingPageLink( + page: Page, + test: Predicate + ): LinkValue? { + return page.firstMatching(this, test) + } + + /** + * Returns the collection of items + * @return java.util.Iterable
+ */ + fun items(): Iterable { + return get("items")!! + } + + /** + * Returns a filtered collection of items + * @param filter com.google.common.base.Predicate filter + * @return java.util.Iterable + */ + fun items( + filter: Predicate + ): Iterable { + return Iterables.filter(this.items(), filter) + } + + // Java Serialization Support + @Throws(ObjectStreamException::class) + override fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: Collection) : + AbstractSerializedForm(obj) { + override fun builder(): Builder { + return Makers.collection() + } + + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + companion object { + private const val serialVersionUID = -1975376657749952999L + } + } +} diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/IO.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/IO.kt new file mode 100644 index 0000000..f60f875 --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/IO.kt @@ -0,0 +1,608 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams + +import com.google.common.base.Supplier +import com.google.common.collect.ImmutableSet +import com.ibm.common.activitystreams.i.Adapter +import com.ibm.common.activitystreams.i.GsonWrapper +import com.ibm.common.activitystreams.i.Schema +import com.ibm.common.activitystreams.util.Module +import java.io.* +import java.util.concurrent.ExecutorService +import java.util.concurrent.Future + +/** + * The IO object is responsible for serializing and deserializing + * Activity Stream objects. Instances of IO should be created and + * defined statically. IO instances are threadsafe and immutable + * once created. + * + * + * You can choose to use one of the default IO instances: + * + *
+ * public static final IO io = IO.makeDefault();
+ *
+ * public static final IO prettyIo = IO.makeDefaultPrettyPrint();
+
* + * + * + * Or you can use the IO.Builder to construct and configure your + * own IO instance with custom adapters, object properties and + * type mappings: + * + *
+ * import static
+ *
+ * public static final IO io =
+ * IO.make()
+ * .schema(
+ * Makers.makeSchema().map(
+ * Schema.object.template()
+ * .as("foo", Foo.class)))
+ * .adapter(Foo.class, new MyFooAdapter())
+ * .get();
+
* + * + * + * Once created, you can use IO instances to parse Activity Streams + * documents: + * + *
+ * InputStream in = ...
+ * Activity activity = io.readAsActivity(in);
+
* + * + * + * Or can use the IO instance to serialize: + * + *
+ * OutputStream out = ...
+ * Activity activity = ...
+ * activity.writeTo(out, io);
+
* + * + * @author james + * @version $Revision: 1.0 $ + */ +class IO protected constructor(builder: Builder) { + class Builder + + : Supplier { + val inner: GsonWrapper.Builder = GsonWrapper.make() + private var schema: Schema? = null + private val modules: ImmutableSet.Builder = ImmutableSet.builder() + + fun using(module: Module): Builder { + modules.add(module) + return this + } + + /** + * Turn pretty print on or off + * @param on boolean + * @return Builder + */ + fun prettyPrint(on: Boolean): Builder { + inner.prettyPrint(on) + return this + } + + /** + * Turn pretty print on + * @return Builder + */ + fun prettyPrint(): Builder { + return prettyPrint(true) + } + + /** + * Add an adapter + * @param type Class + * @param adapter Adapter + * @return Builder + */ + fun adapter( + type: Class?, + adapter: Adapter? + ): Builder { + inner.adapter(type, adapter) + return this + } + + /** + * Add an adapter + * @param type Class<? extends T> + * @return Builder + */ + fun adapter( + type: Class? + ): Builder { + return adapter(type, null) + } + + /** + * Add an adapter + * @param type Class<? extends T> + * @return Builder + */ + fun hierarchicalAdapter( + type: Class + ): Builder { + return hierarchicalAdapter(type, null) + } + + /** + * Add an adapter. + * @param type Class + * @param adapter Adapter + * @param hier boolean + * @return Builder + */ + fun hierarchicalAdapter( + type: Class, + adapter: Adapter? + ): Builder { + inner.adapter(type, adapter, true) + return this + } + + /** + * Set the schema + * @param schema Schema + * @return Builder + */ + fun schema(schema: Schema?): Builder { + //inner.schema(schema); + this.schema = schema + return this + } + + /** + * Set the schema. + * @param schema Supplier + * @return Builder + */ + fun schema(schema: Supplier): Builder { + return schema(schema.get()) + } + + override fun get(): IO { + val mods: Iterable = modules.build() + var schema = this.schema + if (schema == null) { + val builder = Schema.make() + for (mod in mods) mod.apply(builder) + schema = builder.get() + } + inner.schema(schema) + for (module in modules.build()) module.apply(this, schema) + return IO(this) + } + } + + private val gson: GsonWrapper = builder.inner.get() + + /** + * Write the given object + * @param w Writable + * @return String + */ + fun write(w: Writable): String { + val sw = StringWriter() + w.writeTo(sw, this) + return sw.toString() + } + + /** + * Asynchronously write the given object + * @param w + * @param executor + * @return java.util.concurrent.Future<String> + */ + fun write( + w: Writable, + executor: ExecutorService + ): Future { + return executor.submit { write(w) } + } + + /** + * Write the object to the given outputstream + * @param w Writable + * @param out OutputStream + */ + fun write(w: Writable?, out: OutputStream) { + gson.write(w, out) + } + + /** + * Asychronously write the object to the given output stream + * @param w + * @param out + * @param executor + * @return java.util.concurrent.Future<?> + */ + fun write( + w: Writable?, + out: OutputStream, + executor: ExecutorService + ): Future<*> { + return executor.submit { write(w, out) } + } + + /** + * Asychronously write the object to the given writer + * @param w + * @param out + * @param executor + * @return java.util.concurrent.Future<?> + */ + fun write( + w: Writable?, + out: Writer?, + executor: ExecutorService + ): Future<*> { + return executor.submit { write(w, out) } + } + + /** + * Write the object to the given writer + * @param w Writable + * @param out Writer + */ + fun write(w: Writable?, out: Writer?) { + gson.write(w, out) + } + + /** + * Asynchronously read the given input stream and + * return a parsed object of the given type + * @param in + * @param type + * @param executor + * @return java.util.concurrent.Future<A extends ASObject> + */ + fun
readAs( + `in`: InputStream, + type: Class?, + executor: ExecutorService + ): Future { + return executor.submit { readAs(`in`, type) } + } + + /** + * Read the given input stream and return a parsed object + * of the given type + * @param in InputStream + * @param type Class + * @return A + */ + fun readAs( + `in`: InputStream, + type: Class? + ): A { + return gson.readAs(`in`, type) + } + + /** + * Asynchronously read the given reader and return a parsed + * object of the given type + * @param in + * @param type + * @param executor + * @return java.util.concurrent.Future<A extends ASObject> + */ + fun readAs( + `in`: Reader, + type: Class?, + executor: ExecutorService + ): Future { + return executor.submit { readAs(`in`, type) } + } + + /** + * Read the given reader and return a parsed object of the given type + * @param in Reader + * @param type Class + * @return A + */ + fun readAs( + `in`: Reader, + type: Class? + ): A { + return gson.readAs(`in`, type) + } + + /** + * Asynchronously read the given string and return a parsed object of + * the given type + * @param in + * @param type + * @param executor + * @return java.util.concurrent.Future<A extends ASObject> + */ + fun readAs( + `in`: String, + type: Class?, + executor: ExecutorService + ): Future { + return executor.submit { readAs(`in`, type) } + } + + /** + * Read the given string and return a parsed object of the given type + * @param in String + * @param type Class + * @return A + */ + fun readAs( + `in`: String, + type: Class? + ): A { + return readAs(StringReader(`in`), type) + } + + /** + * Asynchronously read the given string + * @param in + * @param executor + * @return java.util.concurrent.Future<ASObject> + */ + fun read(`in`: String, executor: ExecutorService): Future { + return read(StringReader(`in`), executor) + } + + /** + * Read the given string + * @param in String + * @return ASObject + */ + fun read(`in`: String): ASObject { + return read(StringReader(`in`)) + } + + /** + * Asynchronously read the given inputstream + * @param in + * @param executor + * @return java.util.concurrent.Future<ASObject> + */ + fun read(`in`: InputStream, executor: ExecutorService): Future { + return readAs(`in`, ASObject::class.java, executor) + } + + /** + * Asynchronously read the given reader + * @param in + * @param executor + * @return java.util.concurrent.Future<ASObject> + */ + fun read(`in`: Reader, executor: ExecutorService): Future { + return readAs(`in`, ASObject::class.java, executor) + } + + /** + * Read the given input stream. + * @param in InputStream + * @return ASObject + */ + fun read(`in`: InputStream): ASObject { + return readAs(`in`, ASObject::class.java) + } + + /** + * Return the given input stream + * @param in InputStream + * @return A + */ + fun readAs(`in`: InputStream): A { + return read(`in`) as A + } + + /** + * Read the given string as an Activity object + * @param in String + * @return Activity + */ + fun readAsActivity(`in`: String): Activity { + return readAsActivity(StringReader(`in`)) + } + + /** + * Asynchronously read the given string as an Activity object + * @param in + * @param executor + * @return java.util.concurrent.Future<Activity> + */ + fun readAsActivity(`in`: String, executor: ExecutorService): Future { + return readAsActivity(StringReader(`in`), executor) + } + + /** + * Asynchronously read the given inputstream as an Activity object + * @param in + * @param executor + * @return java.util.concurrent.Future<Activity> + */ + fun readAsActivity(`in`: InputStream, executor: ExecutorService): Future { + return readAs( + `in`, + Activity::class.java, executor + ) + } + + /** + * Asynchronously read the given reader as an Activity object + * @param in + * @param executor + * @return java.util.concurrent.Future<Activity> + */ + fun readAsActivity(`in`: Reader, executor: ExecutorService): Future { + return readAs( + `in`, + Activity::class.java, executor + ) + } + + /** + * Asynchronously read the given string as a Collection object + * @param in + * @param executor + * @return java.util.concurrent.Future<Collection> + */ + fun readAsCollection(`in`: String, executor: ExecutorService): Future { + return readAsCollection(StringReader(`in`), executor) + } + + /** + * Asynchronously read the given input stream as a Collection object + * @param in + * @param executor + * @return java.util.concurrent.Future<Collection> + */ + fun readAsCollection(`in`: InputStream, executor: ExecutorService): Future { + return readAs( + `in`, + Collection::class.java, executor + ) + } + + /** + * Asynchronously read the given reader as a Collection object + * @param in + * @param executor + * @return java.util.concurrent.Future<Collection> + */ + fun readAsCollection(`in`: Reader, executor: ExecutorService): Future { + return readAs( + `in`, + Collection::class.java, executor + ) + } + + /** + * Read the given inputstream as an Activity. + * @param in InputStream + * @return Activity + */ + fun readAsActivity(`in`: InputStream): Activity { + return readAs(`in`, Activity::class.java) + } + + /** + * Read the given string as a Collection. + * @param in InputStream + * @return Collection + */ + fun readAsCollection(`in`: String): Collection { + return readAsCollection(StringReader(`in`)) + } + + /** + * Read the given inputstream as a Collection. + * @param in InputStream + * @return Collection + */ + fun readAsCollection(`in`: InputStream): Collection { + return readAs(`in`, Collection::class.java) + } + + /** + * Read the given reader + * @param in + * @return ASObject + */ + fun read(`in`: Reader): ASObject { + return readAs(`in`, ASObject::class.java) + } + + /** + * Read the given reader as an Activity + * @param in Reader + * @return Activity + */ + fun readAsActivity(`in`: Reader): Activity { + return readAs(`in`, Activity::class.java) + } + + /** + * Read the given reader as a Collection + * @param in Reader + * @return Collection + */ + fun readAsCollection(`in`: Reader): Collection { + return readAs(`in`, Collection::class.java) + } + + companion object { + /** + * Create a new IO.Builder + * @return Builder + */ + @JvmStatic + fun make(): Builder { + return Builder() + } + + /** + * Create a new IO.Builder that uses the given schema + * @param schema Schema + * @return IO + */ + fun makeWithSchema(schema: Schema?): IO { + return make().schema(schema).get() + } + + /** + * Create a new IO.Builder that uses the given schema + * @param schema Supplier + * @return IO + */ + fun makeWithSchema(schema: Supplier): IO { + return makeWithSchema(schema.get()) + } + + /** + * Make or return the default IO instance + * @return IO + */ + @JvmStatic + fun makeDefault(vararg modules: Module): IO { + val builder = make() + if (modules != null) for (mod in modules) builder.using(mod) + return builder.get() + } + + /** + * Make or return a default IO instance with Pretty Print enabled + * @return IO + */ + @JvmStatic + fun makeDefaultPrettyPrint(vararg modules: Module): IO { + val builder = make().prettyPrint() + if (modules != null) for (mod in modules) builder.using(mod) + return builder.get() + } + } +} diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/LinkValue.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/LinkValue.kt new file mode 100644 index 0000000..76a71ce --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/LinkValue.kt @@ -0,0 +1,327 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams + +import com.google.common.base.Preconditions +import com.google.common.base.Supplier +import com.google.common.collect.ImmutableList +import com.ibm.common.activitystreams.util.AbstractWritable +import java.io.ObjectStreamException +import java.io.Serializable + +/** + * An Activity Streams 2.0 Link Value. + * + * + * In Actvity Streams 2.0, Link Values can take one of three possible + * forms: + * + * + * * A String containing an absolute IRI + * * An Activity String object + * * An Array containing a mix of Strings or Objects + * + * + * + * For instance, the following are all valid examples of Link Values: + * + *
+ * {
+ * "actor": "acct:joe@example.org"
+ * }
+ *
+ * {
+ * "actor": {
+ * "objectType": "person",
+ * "id": "acct:sally@example.org"
+ * }
+ * }
+ *
+ * {
+ * "actor": [
+ * "acct:joe@example.org",
+ * {
+ * "objectType": "person",
+ * "id": "acct:sally@example.org"
+ * }
+ * ]
+ * }
+
* + * + * + * The LinkValue interface provides a minimal abstraction over these + * value options. Developers will have to check the ValueType of the LinkValue + * (or do an instanceof check) in order to determine which kind of value + * they are working with. + * + *
+ * Activity activity = ...;
+ * Iterable actors = activity.actor();
+ * for (LinkValue actor : actors) {
+ * switch(actor.valueType()) {
+ * case SIMPLE:
+ * SimpleLinkValue s = (SimpleLinkValue)actor;
+ * //...
+ * break;
+ * case OBJECT:
+ * ASObject obj = (ASObject)actor;
+ * //...
+ * break;
+ * }
+ * }
+
* + * + * + * Methods that return Iterable will never include an instance + * of ArrayLinkValue as one of the Iterable values + * + * @author james + * @version $Revision: 1.0 $ + */ +interface LinkValue + + : Writable, Serializable { + /** + * Returns the LinkValue type + * @return ValueType + */ + fun valueType(): ValueType + + /** + * A "Simple Link Value" is a string with a relative or absolute + * URI or IRI value. + */ + class SimpleLinkValue + internal constructor(builder: Builder) : AbstractWritable(builder), + LinkValue, Serializable { + class Builder + + : AbstractWritableBuilder() { + var iri: String? = null + + /** + * Set the url + * @param iri String + * @return Builder + */ + fun url(iri: String?): Builder { + this.iri = iri + return this + } + + /** + * Method get. + * @return SimpleLinkValue + * @see com.google.common.base.Supplier.get + */ + override fun get(): SimpleLinkValue { + return SimpleLinkValue(this) + } + } + + private val iri: String + + init { + this.iri = builder.iri!! + } + + /** + * Return the url + * @return String + */ + fun url(): String { + return iri + } + + override fun toString(): String { + return iri + } + + override fun valueType(): ValueType { + return ValueType.SIMPLE + } + + // Java Serialization Support + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: SimpleLinkValue) : Serializable { + private val iri = obj.iri + + @Throws(ObjectStreamException::class) + fun readResolve(): Any { + return Makers.linkValue(iri) + } + + companion object { + private const val serialVersionUID = -1975376657749952999L + } + } + + companion object { + /** + * Creates a new builder + * @return Builder + */ + fun make(): Builder { + return Builder() + } + + /** + * Creates a new instance + * @param url String + * @return LinkValue + */ + @JvmStatic + fun make(url: String?): LinkValue { + return Builder().url(url).get() + } + } + } + + /** + * An Array Link value is a JSON Array of one or more Simple or Object + * Link Values. Array Link Values MUST NOT contain nested arrays. + */ + class ArrayLinkValue + internal constructor(builder: Builder) : AbstractWritable(builder), + Iterable, LinkValue, Serializable { + class Builder + + : AbstractWritableBuilder() { + val links: ImmutableList.Builder = ImmutableList.builder() + + /** + * Add one or more items + * @param value String + * @param values String[] + * @return Builder + */ + fun add(value: String?, vararg values: String?): Builder { + if (value != null) add(SimpleLinkValue.make(value)) + if (values != null) for (v in values) add(SimpleLinkValue.make(v)) + return this + } + + /** + * Add one or more link values + * @param links Iterable + * @return Builder + */ + fun add(links: Iterable): Builder { + for (l in links) add(l) + return this + } + + /** + * Add one or more link values + * @param values LinkValue[] + * @return Builder + */ + fun add(value: LinkValue?, vararg values: LinkValue): Builder { + if (value != null) { + Preconditions.checkArgument(value.valueType() != ValueType.ARRAY) + links.add(value) + } + if (values != null) for (v in values) { + Preconditions.checkArgument(v.valueType() != ValueType.ARRAY) + links.add(v) + } + return this + } + + /** + * Add a link value + * @param value Supplier + * @return Builder + */ + fun add(value: Supplier): Builder { + val `val` = value.get() + Preconditions.checkArgument(`val`.valueType() != ValueType.ARRAY) + links.add(`val`) + return this + } + + /** + * Method get. + * @return ArrayLinkValue + * @see com.google.common.base.Supplier.get + */ + override fun get(): ArrayLinkValue { + return ArrayLinkValue(this) + } + } + + private val links: ImmutableList = builder.links.build() + + /** + * Method iterator. + * @return Iterator + * @see java.lang.Iterable.iterator + */ + override fun iterator(): MutableIterator { + return links.iterator() + } + + override fun toString(): String { + return links.toString() + } + + override fun valueType(): ValueType { + return ValueType.ARRAY + } + + // Java Serialization Support + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: ArrayLinkValue) : Serializable { + private val list = obj.links + + @Throws(ObjectStreamException::class) + fun readResolve(): Any { + return Makers.linkValues().add(list) + } + + companion object { + private const val serialVersionUID = -1975376657749952999L + } + } + + companion object { + /** + * Create a new builder + * @return ArrayLinkValue.Builder + */ + @JvmStatic + fun make(): Builder { + return Builder() + } + } + } +} diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/Makers.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/Makers.kt new file mode 100644 index 0000000..8076703 --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/Makers.kt @@ -0,0 +1,187 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams + +import com.google.common.collect.ImmutableMap +import com.ibm.common.activitystreams.LinkValue.ArrayLinkValue +import com.ibm.common.activitystreams.LinkValue.SimpleLinkValue +import com.ibm.common.activitystreams.NLV.MapNLV +import com.ibm.common.activitystreams.NLV.SimpleNLV +import com.ibm.common.activitystreams.TypeValue.SimpleTypeValue +import com.ibm.common.activitystreams.i.Schema + +/** + * Utility class for creating Makers for all of the various objects. + */ +object Makers { + /** + * Make a new ActionsValue.Builder + * @return ParametersValue.Builder + */ + @JvmStatic + fun actions(): ActionsValue.Builder { + return ActionsValue.Builder() + } + + /** + * Make a new Schema.Builder + * @return Schema.Builder + */ + fun schema(): Schema.Builder { + return Schema.make() + } + + /** + * Make a new IO.builder + * @return IO.Builder + */ + fun io(): IO.Builder { + return IO.Companion.make() + } + + /** + * Make a new Activity.Builder + * @return Activity.Builder + */ + @JvmStatic + fun activity(): Activity.Builder { + return Activity.Builder() + } + + /** + * Make a new Collection.Builder + * @return Collection.Builder + */ + @JvmStatic + fun collection(): Collection.Builder { + return Collection.Builder() + } + + /** + * Make a new ASObject.Builder + * @return ASObject.Builder + */ + @JvmStatic + fun `object`(): ASObject.Builder { + return ASObject.Builder() + } + + /** + * Make a new ASObject.Builder with a specific objectType + * @param type String + * @return ASObject.Builder + */ + @JvmStatic + fun `object`(type: String?): ASObject.Builder? { + return `object`().objectType(type) + } + + /** + * Return an Object from the given Map + * @param map + * @return ASObject + */ + fun objectFrom(map: Map): ASObject { + val builder = `object`() + for ((key, value) in ImmutableMap.copyOf( + map + )) builder[key!!] = + value + return builder.get() + } + + /** + * Make a new ASObject.Builder + * @param type TypeValue + * @return ASObject.Builder + */ + @JvmStatic + fun `object`(type: TypeValue?): ASObject.Builder? { + return `object`().objectType(type) + } + + /** + * Make a new TypeValue + * @param iri String + * @return TypeValue + */ + @JvmStatic + fun type(iri: String?): TypeValue { + return SimpleTypeValue.Companion.make(iri) + } + + /** + * Make a new LinkValue + * @param iri String + * @return LinkValue + */ + @JvmStatic + fun linkValue(iri: String?): LinkValue { + return SimpleLinkValue.Companion.make(iri) + } + + /** + * Make a new ArrayLinkValue.Builder + * @return LinkValue.ArrayLinkValue.Builder + */ + @JvmStatic + fun linkValues(): ArrayLinkValue.Builder { + return ArrayLinkValue.Companion.make() + } + + /** + * Make a new MapNLV.Builder + * @return NLV.MapNLV.Builder + */ + @JvmStatic + fun nlv(): MapNLV.Builder { + return MapNLV.Companion.make() + } + + /** + * Make a new SimpleNLV value + * @param val String + * @return NLV.SimpleNLV + */ + @JvmStatic + fun nlv(`val`: String?): SimpleNLV { + return SimpleNLV.Companion.make(`val`) + } + + /** + * Make a new verb ASObject.Builder + * @param id String + * @return ASObject.Builder + */ + fun verb(id: String?): ASObject.Builder? { + return `object`("verb")!!.id(id) + } + + /** + * Make a new objectType ASObject.Builder + * @param id String + * @return ASObject.Builder + */ + fun objectType(id: String?): ASObject.Builder? { + return `object`("objectType")!!.id(id) + } +} diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/NLV.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/NLV.kt new file mode 100644 index 0000000..9e1db2d --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/NLV.kt @@ -0,0 +1,265 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams + +import com.google.common.base.Objects +import com.google.common.collect.ImmutableMap +import com.google.common.collect.Maps +import com.ibm.common.activitystreams.util.AbstractWritable +import java.io.ObjectStreamException +import java.io.Serializable + +/** + * An Activity Streams 2.0 Natural Language Value... + * + * + * The value is either a simple string or an object + * with multiple Language-Tag keys and values... + * + *
+ * {
+ * "objectType": "note",
+ * "displayName": {
+ * "en": "My Title In English",
+ * "fr": "Mon titre en français"
+ * }
+ * }
+
* + * + * + * + * ASObject obj = ... + * System.out.println(obj.displayNameString("en")); + * System.out.println(obj.displayNameString("fr")); + * + * NLV nlv = obj.displayName(); + * switch(nlv.valueType()) { + * case SIMPLE: + * SimpleNLV s = (SimpleNLV)nlv; + * ... + * break; + * case OBJECT: + * MapNLV m = (MapNLV)nlv; + * ... + * break; + * } + * + * + * @author james + * @version $Revision: 1.0 $ + */ +interface NLV + + : Writable, Serializable { + /** + * Returns the value type. Either ValueType.SIMPLE or ValueType.OBJECT + * @return ValueType + */ + fun valueType(): ValueType + + class SimpleNLV + internal constructor(builder: Builder) : AbstractWritable(builder), NLV, + Serializable { + private val `val`: String + + init { + this.`val` = builder.`val`!! + } + + /** + * Return the value + * @return String + */ + fun value(): String { + return `val` + } + + override fun hashCode(): Int { + return Objects.hashCode(`val`) + } + + override fun equals(obj: Any?): Boolean { + if (this === obj) return true + if (obj == null) return false + if (javaClass != obj.javaClass) return false + val other = obj as SimpleNLV + return Objects.equal(`val`, other.`val`) + } + + override fun toString(): String { + return `val` + } + + class Builder + + : AbstractWritableBuilder() { + var `val`: String? = null + + fun value(`val`: String?): Builder { + this.`val` = `val` + return this + } + + override fun get(): SimpleNLV { + return SimpleNLV(this) + } + } + + override fun valueType(): ValueType { + return ValueType.SIMPLE + } + + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: SimpleNLV) : Serializable { + private val value = obj.`val` + + @Throws(ObjectStreamException::class) + fun readResolve(): Any { + return Makers.nlv(value) + } + + companion object { + private const val serialVersionUID = -1975376657749952999L + } + } + + companion object { + /** + * Create a new builder + * @return Builder + */ + fun make(): Builder { + return Builder() + } + + /** + * Create a new instance + * @param value String + * @return SimpleNLV + */ + @JvmStatic + fun make(value: String?): SimpleNLV { + return make().value(value).get() + } + } + } + + class MapNLV + internal constructor(builder: Builder) : AbstractWritable(builder), NLV, + Iterable { + private val vals: ImmutableMap = builder.vals.build() + + @Transient + private var hash = 1 + + fun value(lang: String?): String? { + return vals[lang] + } + + fun has(lang: String?): Boolean { + return vals.containsKey(lang) + } + + override fun hashCode(): Int { + if (hash == 1) hash = Objects.hashCode(vals) + return hash + } + + override fun equals(obj: Any?): Boolean { + if (this === obj) return true + if (obj == null) return false + if (javaClass != obj.javaClass) return false + val other = obj as MapNLV + return Maps.difference(vals, other.vals) + .areEqual() + } + + override fun iterator(): MutableIterator { + return vals.keys.iterator() + } + + class Builder + + : AbstractWritableBuilder() { + val vals: ImmutableMap.Builder = ImmutableMap.builder() + + fun from(other: MapNLV, lang: String?): Builder { + for (l in other) if (!l.equals(lang, ignoreCase = true)) set(l, other.value(l)) + return this + } + + operator fun set(lang: String?, `val`: String?): Builder { + vals.put(lang!!, `val`!!) + return this + } + + override fun get(): MapNLV { + return MapNLV(this) + } + } + + override fun valueType(): ValueType { + return ValueType.OBJECT + } + + fun toMap(): Map { + return vals + } + + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: MapNLV) : Serializable { + private val map = obj.vals + + @Throws(ObjectStreamException::class) + fun readResolve(): Any { + val builder = + Makers.nlv() + for ((key, value) in map) builder.set( + key, + value + ) + return builder.get() + } + + companion object { + private const val serialVersionUID = -1975376657749952999L + } + } + + companion object { + @JvmStatic + fun make(): Builder { + return Builder() + } + } + } +} diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/TypeValue.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/TypeValue.kt new file mode 100644 index 0000000..4dc17e7 --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/TypeValue.kt @@ -0,0 +1,177 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams + +import com.ibm.common.activitystreams.util.AbstractWritable +import java.io.ObjectStreamException +import java.io.Serializable +import java.util.* + +/** + * In Activity Streams 2.0, the "objectType" and "verb" properties, + * as well as several other properties, are defined as "Type Values". + * A "Type Value" can be either a simple token string, an absolute + * IRI string, or an ASObject. + * + *
+ * {
+ * "verb": "post"
+ * }
+ *
+ * {
+ * "verb": "urn:example:verbs:foo"
+ * }
+ *
+ * {
+ * "verb": {
+ * "id": "urn:example:verbs:foo",
+ * "displayName": "Foo"
+ * }
+ * }
+
* + * + * + * The TypeValue interface provides a minimal abstraction + * over these possible values. Developers should check valueType + * to determine which type of TypeValue they are working with. + * + *
+ * Activity activity = ...
+ * TypeValue tv = activity.verb();
+ *
+ * System.out.println(tv.id());
+ *
+ * switch(tv.valueType()) {
+ * case SIMPLE:
+ * SimpleTypeValue s = (SimpleTypeValue)tv;
+ * ...
+ * break;
+ * case OBJECT:
+ * ASObject o (ASObject)tv;
+ * ...
+ * break;
+ * }
+
* + * + * @author james + * @version $Revision: 1.0 $ + */ +interface TypeValue + + : Writable, Serializable { + /** + * Return the type value identifier + * @return String + */ + fun id(): String? + + fun valueType(): ValueType + + class SimpleTypeValue + internal constructor(builder: Builder) : AbstractWritable(builder), + TypeValue, Serializable { + class Builder + + : AbstractWritableBuilder() { + var iri: String? = null + + /** + * Set the url + * @param iri String + * @return Builder + */ + fun url(iri: String?): Builder { + this.iri = iri + return this + } + + override fun get(): SimpleTypeValue { + return SimpleTypeValue(this) + } + } + + private val iri: String + + init { + this.iri = builder.iri!! + } + + override fun hashCode(): Int { + return Objects.hash(iri) + } + + override fun equals(obj: Any?): Boolean { + if (this === obj) return true + if (obj == null) return false + if (javaClass != obj.javaClass) return false + val other = obj as SimpleTypeValue + return iri == other.iri + } + + /** + * Return the type value identifier + * @return String + * @see com.ibm.common.activitystreams.TypeValue.id + */ + override fun id(): String? { + return iri + } + + override fun toString(): String { + return iri + } + + override fun valueType(): ValueType { + return ValueType.SIMPLE + } + + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: SimpleTypeValue) : Serializable { + private val iri = obj.iri + + @Throws(ObjectStreamException::class) + fun readResolve(): Any { + return Makers.type(iri) + } + + companion object { + private const val serialVersionUID = -1975376657749952999L + } + } + + companion object { + fun make(): Builder { + return Builder() + } + + @JvmStatic + fun make(url: String?): TypeValue { + return make().url(url).get() + } + } + } +} diff --git a/core/src/main/java/com/ibm/common/activitystreams/ValueType.java b/core/src/main/kotlin/com/ibm/common/activitystreams/ValueType.kt old mode 100755 new mode 100644 similarity index 91% rename from core/src/main/java/com/ibm/common/activitystreams/ValueType.java rename to core/src/main/kotlin/com/ibm/common/activitystreams/ValueType.kt index 510a9cf..1ce344f --- a/core/src/main/java/com/ibm/common/activitystreams/ValueType.java +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/ValueType.kt @@ -19,18 +19,18 @@ * * @author James M Snell (jasnell@us.ibm.com) */ -package com.ibm.common.activitystreams; +package com.ibm.common.activitystreams /** * Used for TypeValue, LinkValue and NLV interfaces to distinguish * between the possible value options. - * + * * LinkValue.valueType() can return SIMPLE, OBJECT or ARRAY * TypeValue.valueType() can return SIMPLE or OBJECT * NLV.valueType() can return SIMPLE or OBJECT */ -public enum ValueType { - SIMPLE, - OBJECT, - ARRAY; +enum class ValueType { + SIMPLE, + OBJECT, + ARRAY } diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/Writable.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/Writable.kt new file mode 100644 index 0000000..242ba3c --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/Writable.kt @@ -0,0 +1,96 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams + +import java.io.OutputStream +import java.io.Writer +import java.util.concurrent.ExecutorService +import java.util.concurrent.Future + +/** + * Base interface for all objects that serialize to IO object instances + * @author james + * @version $Revision: 1.0 $ + */ +interface Writable { + /** + * Write the object to the output stream using the default IO instance + * @param out OutputStream + */ + fun writeTo(out: OutputStream) + + /** + * Asynchronously write the object to the output stream using the + * default IO instance + * @param out + * @param executor + * @return Future<?> + */ + fun writeTo(out: OutputStream, executor: ExecutorService): Future<*> + + /** + * Write the object to the Writer using the default IO instance + * @param out Writer + */ + fun writeTo(out: Writer) + + /** + * Asynchronously write the object to the writer using the default IO instance + * @param out + * @param executor + * @return Future<?> + */ + fun writeTo(out: Writer, executor: ExecutorService): Future<*> + + /** + * Write the object to the output stream using the given IO instance + * @param out OutputStream + * @param io IO + */ + fun writeTo(out: OutputStream, io: IO) + + /** + * Asynchronously write the object to the output stream using the given + * IO instance. + * @param out + * @param io + * @param executor + * @return Future<?> + */ + fun writeTo(out: OutputStream, io: IO, executor: ExecutorService): Future<*> + + /** + * Write the object to the writer using the given IO instance + * @param out Writer + * @param io IO + */ + fun writeTo(out: Writer, io: IO) + + /** + * Asynchronously write the object to the writer using the given IO instance + * @param out + * @param io + * @param executor + * @return Future<?> + */ + fun writeTo(out: Writer, io: IO, executor: ExecutorService): Future<*> +} diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/i/ASObjectAdapter.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/i/ASObjectAdapter.kt new file mode 100644 index 0000000..fca4abd --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/i/ASObjectAdapter.kt @@ -0,0 +1,303 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.i + +import com.google.common.base.Converter +import com.google.common.collect.ImmutableList +import com.google.common.collect.ImmutableSet +import com.google.gson.* +import com.ibm.common.activitystreams.* +import com.ibm.common.activitystreams.Collection +import com.ibm.common.activitystreams.Makers.activity +import com.ibm.common.activitystreams.Makers.collection +import com.ibm.common.activitystreams.Makers.`object` +import java.lang.reflect.Type +import kotlin.collections.Map +import kotlin.collections.contains + + +/** + * @author james + * @version $Revision: 1.0 $ + */ +open class ASObjectAdapter + +/** + * Constructor for ASObjectAdapter. + * @param schema Schema + */(private val schema: Schema) : Adapter() { + protected fun schema(): Schema { + return schema + } + + /** + * Method serialize. + * @param obj ASObject + * @param type Type + * @param context JsonSerializationContext + * + * @return JsonElement + */ + override fun serialize( + obj: ASObject, + type: Type, + context: JsonSerializationContext + ): JsonElement { + val el: JsonObject = + JsonObject() + for (key: String in obj) { + val `val`: Any? = obj.get(key) + if (`val` != null) { + el.add( + key, + context.serialize( + `val`, + `val`.javaClass + ) + ) + } + } + return el + } + + protected open fun knowsType(type: Type?): Boolean { + return knownTypes.contains(type) + } + + protected open fun builderFor(type: Type): ASObject.AbstractBuilder<*, *>? { + if (type === Collection::class.java) return collection() + else if (type === Activity::class.java) return activity() + else return null + } + + protected open fun modelFor(type: Type): Model? { + if (type === Collection::class.java) return schema.forObjectClassOrType( + Collection.Builder::class.java, + "collection" + ) + else if (type === Activity::class.java) return schema.forObjectClassOrType( + Activity.Builder::class.java, + "activity" + ) + else return null + } + + /** + * Method deserialize. + * @param element JsonElement + * @param type Type + * @param context JsonDeserializationContext + * @return ASObject + * @throws JsonParseException + * @see com.google.gson.JsonDeserializer.deserialize + */ + @Throws(JsonParseException::class) + override fun deserialize( + element: JsonElement, + type: Type, + context: JsonDeserializationContext + ): ASObject { + val obj: JsonObject = element as JsonObject + var builder: ASObject.AbstractBuilder<*, *>? = null + var propMap: Model? = null + var tv: TypeValue? = null + + if (knowsType(type)) { + builder = builderFor(type) + propMap = modelFor(type) + } else { + if (obj.has("objectType")) { + tv = context.deserialize( + obj.get("objectType"), + TypeValue::class.java + ) + val _class: Class?>? = + schema.builderForObjectTypeOrClass(tv?.id(), type as Class<*>?) + if (_class != null) { + propMap = schema.forObjectClassOrType(_class, tv?.id()) + if (!_class.isInterface()) { + try { + builder = _class.getConstructor(String::class.java).newInstance(tv?.id()) + } catch (t: Throwable) { + try { + builder = _class.newInstance() + builder!!.set("objectType", tv) + } catch (t2: Throwable) { + builder = `object`(tv) + } + } + } else builder = `object`(tv) + } else { + builder = `object`(tv) + propMap = schema.forObjectClassOrType( + ASObject.Builder::class.java, tv?.id() + ) + } + } else { + if (obj.has("verb") && + (obj.has("actor") || + obj.has("object") || + obj.has("target")) + ) { + builder = activity() + propMap = schema.forObjectClassOrType( + Activity.Builder::class.java, "activity" + ) + } else if (obj.has("items")) { + builder = collection() + propMap = schema.forObjectClassOrType( + Collection.Builder::class.java, + "collection" + ) + } else { + val _class: Class?>? = + schema.builderFor(type as Class<*>?) + if (_class != null) { + if (!_class.isInterface()) { + try { + builder = _class.newInstance() + } catch (t: Throwable) { + builder = `object`() + } + } else builder = `object`() + } + if (builder == null) builder = `object`() // anonymous + + propMap = schema.forObjectClass(builder.javaClass) + propMap = if (propMap != null) propMap else schema.forObjectClass( + ASObject.Builder::class.java + ) + } + } + } + + for (entry: Map.Entry in obj.entrySet()) { + val name: String = entry.key + if (name.equals("objectType", ignoreCase = true)) continue + val _class: Class<*>? = propMap!!.get(name) + val `val`: JsonElement = entry.value + if (`val`.isJsonPrimitive()) builder!!.set( + name, + if (_class != null) context.deserialize( + `val`, + _class + ) else primConverter.convert(`val`.getAsJsonPrimitive()) + ) + else if (`val`.isJsonArray()) { + builder!!.set( + name, + if (LinkValue::class.java.isAssignableFrom(if (_class != null) _class else Any::class.java)) context.deserialize( + `val`, + LinkValue::class.java + ) else convert( + `val`.getAsJsonArray(), + _class, + context, + ImmutableList.builder() + ) + ) + } else if (`val`.isJsonObject()) builder!!.set( + name, + context.deserialize( + `val`, + if (propMap.has(name)) propMap.get(name) else ASObject::class.java + ) as Any? + ) + } + return builder!!.get()!! + } + + /** + * Method convert. + * @param arr JsonArray + * @param _class Class + * @param context JsonDeserializationContext + * @param list ImmutableList.Builder + * @return ImmutableList + */ + private fun convert( + arr: JsonArray, + _class: Class<*>?, + context: JsonDeserializationContext, + list: ImmutableList.Builder + ): ImmutableList { + processArray(arr, _class, context, list) + return list.build() + } + + /** + * Method processArray. + * @param arr JsonArray + * @param _class Class + * @param context JsonDeserializationContext + * @param list ImmutableList.Builder + */ + private fun processArray( + arr: JsonArray, + _class: Class<*>?, + context: JsonDeserializationContext, + list: ImmutableList.Builder + ) { + for (mem: JsonElement in arr) { + if (mem.isJsonPrimitive()) list.add( + if (_class != null) context.deserialize(mem, _class) else primConverter.convert( + mem.getAsJsonPrimitive() + ) + ) + else if (mem.isJsonObject()) list.add( + *context.deserialize( + mem, + if (_class != null) _class else ASObject::class.java + ) + ) + else if (mem.isJsonArray()) list.add( + convert( + mem.getAsJsonArray(), + _class, + context, + ImmutableList.builder() + ) + ) + } + } + + companion object { + private val knownTypes: ImmutableSet = ImmutableSet.of( + Collection::class.java, + Activity::class.java + ) + + val primConverter: Converter = object : Converter() { + override fun doBackward(a: Any): JsonPrimitive { + if (a is Boolean) return JsonPrimitive(a) + else if (a is Number) return JsonPrimitive(a) + else return JsonPrimitive(a.toString()) + } + + override fun doForward(b: JsonPrimitive): Any { + if (b.isBoolean()) return b.getAsBoolean() + else if (b.isNumber()) return b.getAsNumber() + else return b.getAsString() + } + } + } +} diff --git a/core/src/main/java/com/ibm/common/activitystreams/internal/Adapter.java b/core/src/main/kotlin/com/ibm/common/activitystreams/i/Adapter.kt old mode 100755 new mode 100644 similarity index 79% rename from core/src/main/java/com/ibm/common/activitystreams/internal/Adapter.java rename to core/src/main/kotlin/com/ibm/common/activitystreams/i/Adapter.kt index 4f9a19b..0f44661 --- a/core/src/main/java/com/ibm/common/activitystreams/internal/Adapter.java +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/i/Adapter.kt @@ -19,16 +19,14 @@ * * @author James M Snell (jasnell@us.ibm.com) */ -package com.ibm.common.activitystreams.internal; +package com.ibm.common.activitystreams.i -import com.google.gson.JsonDeserializer; -import com.google.gson.JsonSerializer; +import com.google.gson.JsonDeserializer +import com.google.gson.JsonSerializer /** * @author james * @version $Revision: 1.0 $ */ -public abstract class Adapter - implements JsonSerializer, JsonDeserializer { - -} +abstract class Adapter + : JsonSerializer, JsonDeserializer diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/i/Adapters.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/i/Adapters.kt new file mode 100644 index 0000000..a5328db --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/i/Adapters.kt @@ -0,0 +1,304 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.i + +import com.google.common.base.Optional +import com.google.common.base.Preconditions +import com.google.common.base.Throwables +import com.google.common.collect.* +import com.google.common.net.MediaType +import com.google.gson.* +import com.google.gson.internal.LazilyParsedNumber +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.ActionsValue +import com.ibm.common.activitystreams.LinkValue +import com.ibm.common.activitystreams.Makers.actions +import com.ibm.common.activitystreams.Makers.linkValues +import com.ibm.common.activitystreams.NLV +import com.ibm.common.activitystreams.util.AbstractDictionaryObjectAdapter +import org.joda.time.DateTime +import org.joda.time.Duration +import org.joda.time.Interval +import org.joda.time.Period +import org.joda.time.format.ISODateTimeFormat +import java.lang.reflect.Type +import java.util.* + +/** + * @author james + * @version $Revision: 1.0 $ + */ +internal object Adapters { + /** + * Method forEnum. + * @param _enumClass Class + * @return EnumAdapter + */ + fun > forEnum(_enumClass: Class): EnumAdapter { + return EnumAdapter(_enumClass) + } + + /** + * Method forEnum. + * @param _enumClass Class + * @param or E + * @return EnumAdapter + */ + fun > forEnum(_enumClass: Class, or: E): EnumAdapter { + return EnumAdapter(_enumClass) + } + + val NLV: Adapter = NaturalLanguageValueAdapter() + + val ACTIONS: Adapter = + object : AbstractDictionaryObjectAdapter( + LinkValue::class.java + ) { + override fun serialize( + actions: ActionsValue, + type: Type, + context: JsonSerializationContext + ): JsonElement { + val obj = JsonObject() + for (verb: String? in actions) { + val links = + actions.get(verb) + obj.add( + verb, + context.serialize( + if (Iterables.size(links) == 1) { + // if there's only one, serialize just 1 + Iterables.getFirst(links, null) + } else { + // otherwise, serialize the list + linkValues().add(links).get() + }, + LinkValue::class.java + ) + ) + } + return obj + } + + override fun builder(): ActionsValue.Builder { + return actions() + } + } + + val ITERABLE: Adapter> = object : Adapter>() { + override fun serialize( + i: Iterable<*>, + type: Type, + context: JsonSerializationContext + ): JsonElement { + val ary = JsonArray() + for (obj in i) ary.add(context.serialize(obj, obj?.javaClass)) + return ary + } + + @Throws(JsonParseException::class) + override fun deserialize( + arg0: JsonElement, arg1: Type, + arg2: JsonDeserializationContext + ): Iterable<*> { + return listOf() // handled elsewhere + } + } + + val DATE: Adapter = object : SimpleAdapter() { + override fun serialize(t: Date?): String? { + return ISODateTimeFormat.dateTime().print(DateTime(t)) + } + + override fun apply(v: String?): Date? { + return DateTime.parse(v).toDate() + } + } + + val DATETIME: Adapter = object : SimpleAdapter() { + override fun serialize(t: DateTime?): String? { + return ISODateTimeFormat.dateTime().print(t) + } + + override fun apply(v: String?): DateTime? { + return DateTime.parse(v) + } + } + + val DURATION: Adapter = object : SimpleAdapter() { + override fun apply(v: String?): Duration? { + return Duration.parse(v) + } + } + + val PERIOD: Adapter = object : SimpleAdapter() { + override fun apply(v: String?): Period? { + return Period.parse(v) + } + } + + val INTERVAL: Adapter = object : SimpleAdapter() { + override fun apply(v: String?): Interval? { + return Interval.parse(v) + } + } + + val MIMETYPE: Adapter = object : SimpleAdapter() { + override fun apply(v: String?): MediaType? { + return MediaType.parse(v) + } + } + + val MULTIMAP: MultimapAdapter = MultimapAdapter() + + + val RANGE: Adapter> = object : Adapter>() { + override fun serialize( + src: Range<*>, + typeOfSrc: Type, + context: JsonSerializationContext + ): JsonElement { + val el = JsonObject() + el.add("lower", makeBound(src.lowerBoundType(), src.lowerEndpoint(), context)) + el.add("upper", makeBound(src.upperBoundType(), src.upperEndpoint(), context)) + return el + } + + private fun makeBound( + type: BoundType, + `val`: Any, + context: JsonSerializationContext + ): JsonElement { + val obj = JsonObject() + obj.add("type", context.serialize(type.name.lowercase(Locale.getDefault()))) + obj.add("endpoint", context.serialize(`val`)) + return obj + } + + @Throws(JsonParseException::class) + override fun deserialize( + json: JsonElement, + typeOfT: Type, + context: JsonDeserializationContext + ): Range<*> { + Preconditions.checkArgument(json.isJsonObject) + try { + val obj = json.asJsonObject + val upper = obj.getAsJsonObject("upper") + val lower = obj.getAsJsonObject("lower") + val ubt = bt(upper.getAsJsonPrimitive("type")) + val lbt = bt(lower.getAsJsonPrimitive("type")) + val ub = des(upper["endpoint"], context) + val lb = des(lower["endpoint"], context) + return Range.range(lb as Comparable<*>?, lbt, ub as Comparable<*>?, ubt) + } catch (t: Throwable) { + throw Throwables.propagate(t) + } + } + + private fun des(`val`: JsonElement, context: JsonDeserializationContext): Any? { + if (`val`.isJsonArray) return MultimapAdapter.Companion.arraydes(`val`.asJsonArray, context) + else if (`val`.isJsonObject) return context.deserialize(`val`, ASObject::class.java) + else if (`val`.isJsonPrimitive) { + var v: Any? = ASObjectAdapter.Companion.primConverter.convert(`val`.asJsonPrimitive) + if (v is LazilyParsedNumber) v = LazilyParsedNumberComparable(v) + return v + } else return null + } + + private fun bt(p: JsonPrimitive): BoundType { + try { + return BoundType.valueOf(p.toString()) + } catch (t: Throwable) { + return BoundType.CLOSED + } + } + } + + val OPTIONAL: Adapter> = object : Adapter>() { + override fun serialize( + src: Optional<*>, + typeOfSrc: Type, + context: JsonSerializationContext + ): JsonElement { + return context.serialize(src.orNull()) + } + + @Throws(JsonParseException::class) + override fun deserialize( + json: JsonElement, + typeOfT: Type, + context: JsonDeserializationContext + ): Optional<*> { + return Optional.absent() + } + } + + val TABLE: Adapter> = object : Adapter>() { + override fun serialize( + src: Table<*, *, *>, + typeOfSrc: Type, + context: JsonSerializationContext + ): JsonElement { + val obj = JsonObject() + for (cell: Table.Cell<*, *, *> in src.cellSet()) { + val r = cell.rowKey.toString() + val c = cell.columnKey.toString() + var rowobj: JsonObject? = null + if (!obj.has(r)) { + rowobj = JsonObject() + obj.add(r, rowobj) + } else { + rowobj = obj.getAsJsonObject(r) + } + val `val` = cell.value + if (`val` != null) rowobj!!.add(c, context.serialize(`val`, `val`.javaClass)) + } + + return obj + } + + @Throws(JsonParseException::class) + override fun deserialize( + json: JsonElement, + typeOfT: Type, + context: JsonDeserializationContext + ): Table<*, *, *> { + val table = + ImmutableTable.builder() + Preconditions.checkArgument(json.isJsonObject) + val obj = json.asJsonObject + for ((row, cell) in obj.entrySet()) { + Preconditions.checkArgument(cell.isJsonObject) + for (cellentry in cell.asJsonObject.entrySet()) { + var desval: Any? = null + if (`json`.isJsonArray) desval = MultimapAdapter.Companion.arraydes(`json`.asJsonArray, context) + else if (`json`.isJsonObject) desval = context.deserialize(`json`, ASObject::class.java) + else if (`json`.isJsonPrimitive) desval = + ASObjectAdapter.Companion.primConverter.convert(`json`.asJsonPrimitive) + if (desval != null) table.put(row, cellentry.key, desval) + } + } + return table.build() + } + } +} diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/i/EnumAdapter.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/i/EnumAdapter.kt new file mode 100644 index 0000000..e7e59d6 --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/i/EnumAdapter.kt @@ -0,0 +1,118 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.i + +import com.google.common.base.Converter +import com.google.common.base.Enums +import com.google.common.base.Preconditions +import com.google.gson.* +import com.ibm.common.activitystreams.util.Converters.toLowerConverter +import com.ibm.common.activitystreams.util.Converters.toUpperConverter +import java.lang.reflect.Type + +/** + * @author james + * @version $Revision: 1.0 $ + */ +class EnumAdapter> +@JvmOverloads constructor( + _enumClass: Class?, + c: Converter = Enums.stringConverter(_enumClass) +) : + Adapter() { + private val des: Converter + private val ser: Converter + + /** + * Constructor for EnumAdapter + * + * + * @param _enumClass Class + * @param or E + */ + constructor(_enumClass: Class, or: E) : this(_enumClass, Enums.stringConverter(_enumClass)) + + /** + * Constructor for EnumAdapter. + * @param _enumClass Class + * + * @param c Converter,E> + */ + /** + * Constructor for EnumAdapter. + * @param _enumClass Class + */ + init { + this.des = toUpper.andThen(c) + this.ser = c.reverse().andThen(toLower) + } + + /** + * Method serialize. + * @param src E + * @param typeOfSrc Type + * @param context JsonSerializationContext + * @return JsonElement + */ + override fun serialize( + src: E, + typeOfSrc: Type, + context: JsonSerializationContext + ): JsonElement { + return context.serialize(ser.convert(src)) + } + + /** + * Method deserialize. + * @param json JsonElement + * @param typeOfT Type + * @param context JsonDeserializationContext + * @return E + * @throws JsonParseException + * @see com.google.gson.JsonDeserializer.deserialize + */ + @Throws(JsonParseException::class) + override fun deserialize( + json: JsonElement, + typeOfT: Type, + context: JsonDeserializationContext + ): E { + Preconditions.checkArgument(json.isJsonPrimitive) + val jp: JsonPrimitive = json.asJsonPrimitive + Preconditions.checkArgument(jp.isString) + return des.convert(jp.asString)!! + } + + /** + * Method convert. + * @param s String + * @return E + */ + protected fun convert(s: String?): E? { + return des.convert(s) + } + + companion object { + protected val toLower: Converter = toLowerConverter() + protected val toUpper: Converter = toUpperConverter() + } +} \ No newline at end of file diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/i/GsonWrapper.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/i/GsonWrapper.kt new file mode 100644 index 0000000..41db079 --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/i/GsonWrapper.kt @@ -0,0 +1,312 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.i + +import com.google.common.base.Optional +import com.google.common.base.Supplier +import com.google.common.base.Throwables +import com.google.common.collect.ImmutableList +import com.google.common.collect.Multimap +import com.google.common.collect.Range +import com.google.common.collect.Table +import com.google.common.net.MediaType +import com.google.gson.Gson +import com.google.gson.GsonBuilder +import com.google.gson.internal.LazilyParsedNumber +import com.google.gson.internal.bind.TypeAdapters +import com.ibm.common.activitystreams.* +import com.ibm.common.activitystreams.Collection +import org.joda.time.DateTime +import org.joda.time.ReadableDuration +import org.joda.time.ReadableInterval +import org.joda.time.ReadablePeriod +import java.io.* +import java.util.* +import kotlin.collections.Iterable + +/** + * @author james + * @version $Revision: 1.0 $ + */ +class GsonWrapper protected constructor(builder: Builder) { + /** + * @author james + * @version $Revision: 1.0 $ + */ + class Builder + + : Supplier { + var charset: String = "UTF-8" + var pretty: Boolean = false + var schema: Schema? = null // default + val adapters: ImmutableList.Builder> = ImmutableList.builder() + + /** + * Method charset. + * @param charset String + * + * @return Builder + */ + fun charset(charset: String): Builder { + this.charset = charset + return this + } + + /** + * Method schema. + * @param schema Schema + * + * @return Builder + */ + fun schema(schema: Schema?): Builder { + this.schema = schema + return this + } + + /** + * Method adapter. + * @param type Class + * @param adapter Adapter + * + * @return Builder + */ + fun adapter( + type: Class?, + adapter: Adapter? + ): Builder { + return adapter(type, adapter, false) + } + + /** + * Method adapter. + * @param type Class + * @param adapter Adapter + * @param hier boolean + * + * @return Builder + */ + fun adapter( + type: Class?, + adapter: Adapter?, + hier: Boolean + ): Builder { + adapters.add(AdapterEntry(type, adapter, hier)) + return this + } + + /** + * Method prettyPrint. + * @param on boolean + * + * @return Builder + */ + /** + * Method prettyPrint. + * + * @return Builder + */ + @JvmOverloads + fun prettyPrint(on: Boolean = true): Builder { + this.pretty = on + return this + } + + /** + * Method get. + * + * + * @return GsonWrapper * @see com.google.common.base.Supplier#get() + */ + override fun get(): GsonWrapper { + return GsonWrapper(this) + } + } + + /** + * @author james + * @version $Revision: 1.0 $ + */ + class AdapterEntry + /** + * Constructor for AdapterEntry. + * @param type Class + * @param adapter Adapter + * @param hier boolean + */( + val type: Class?, + val adapter: Adapter?, + val hier: Boolean + ) + + private val gson: Gson + private val charset: String + + /** + * Constructor for GsonWrapper. + * @param builder Builder + */ + init { + val schema: Schema = + if (builder.schema != null) builder.schema!! else Schema.Companion.make().get() + val base: ASObjectAdapter = + ASObjectAdapter(schema) + val b: GsonBuilder = initGsonBuilder( + builder, + schema, + base, + builder.adapters.build() + ) + if (builder.pretty) b.setPrettyPrinting() + this.gson = b.create() + this.charset = builder.charset + } + + /** + * Method write. + * @param w Writable + * @param out OutputStream + */ + fun write(w: Writable?, out: OutputStream) { + try { + val wout: OutputStreamWriter = + OutputStreamWriter(out, charset) + gson.toJson(w, wout) + wout.flush() + } catch (t: Throwable) { + throw Throwables.propagate(t) + } + } + + /** + * Method write. + * @param w Writable + * @param out Writer + */ + fun write(w: Writable?, out: Writer?) { + gson.toJson(w, out) + } + + /** + * Method write. + * @param w Writable + * + * @return String + */ + fun write(w: Writable?): String { + val sw: StringWriter = + StringWriter() + write(w, sw) + return sw.toString() + } + + /** + * Method readAs. + * @param in InputStream + * @param type Class + * + * @return A + */ + fun
readAs(`in`: InputStream, type: Class?): A { + try { + return readAs(InputStreamReader(`in`, charset), type) + } catch (t: Throwable) { + throw Throwables.propagate(t) + } + } + + /** + * Method readAs. + * @param in Reader + * @param type Class + * + * @return A + */ + fun readAs(`in`: Reader, type: Class?): A { + return gson.fromJson(`in`, type) as A + } + + companion object { + /** + * Method make. + * + * @return Builder + */ + fun make(): Builder { + return Builder() + } + + /** + * Method initGsonBuilder. + * @param builder Builder + * + * @return GsonBuilder + */ + private fun initGsonBuilder( + builder: Builder, + schema: Schema, + base: ASObjectAdapter, + adapters: Iterable> + ): GsonBuilder { + val gson: GsonBuilder = GsonBuilder() + .registerTypeHierarchyAdapter(TypeValue::class.java, TypeValueAdapter(schema)) + .registerTypeHierarchyAdapter(LinkValue::class.java, LinkValueAdapter(schema)) + .registerTypeHierarchyAdapter(Iterable::class.java, Adapters.ITERABLE) + .registerTypeHierarchyAdapter(ASObject::class.java, base) + .registerTypeHierarchyAdapter(Collection::class.java, base) + .registerTypeHierarchyAdapter(Activity::class.java, base) + .registerTypeHierarchyAdapter(NLV::class.java, Adapters.NLV) + .registerTypeHierarchyAdapter(ActionsValue::class.java, Adapters.ACTIONS) + .registerTypeHierarchyAdapter(Optional::class.java, Adapters.OPTIONAL) + .registerTypeHierarchyAdapter(Range::class.java, Adapters.RANGE) + .registerTypeHierarchyAdapter(Table::class.java, Adapters.TABLE) + .registerTypeHierarchyAdapter(LazilyParsedNumber::class.java, TypeAdapters.NUMBER) + .registerTypeHierarchyAdapter(LazilyParsedNumberComparable::class.java, TypeAdapters.NUMBER) + .registerTypeHierarchyAdapter(ReadableDuration::class.java, Adapters.DURATION) + .registerTypeHierarchyAdapter(ReadablePeriod::class.java, Adapters.PERIOD) + .registerTypeHierarchyAdapter(ReadableInterval::class.java, Adapters.INTERVAL) + .registerTypeAdapter( + Activity.Status::class.java, + Adapters.forEnum( + Activity.Status::class.java, + Activity.Status.OTHER + ) + ) + .registerTypeAdapter(Date::class.java, Adapters.DATE) + .registerTypeAdapter(DateTime::class.java, Adapters.DATETIME) + .registerTypeAdapter(MediaType::class.java, Adapters.MIMETYPE) + .registerTypeHierarchyAdapter(Multimap::class.java, Adapters.MULTIMAP) + + for (entry: AdapterEntry<*> in adapters) { + if (entry.hier) gson.registerTypeHierarchyAdapter( + entry.type, + if (entry.adapter != null) entry.adapter else base + ) + else gson.registerTypeAdapter( + entry.type, + if (entry.adapter != null) entry.adapter else base + ) + } + + return gson + } + } +} diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/i/LazilyParsedNumberComparable.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/i/LazilyParsedNumberComparable.kt new file mode 100644 index 0000000..75007a8 --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/i/LazilyParsedNumberComparable.kt @@ -0,0 +1,131 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.i + +import com.google.common.primitives.Longs +import com.google.gson.internal.LazilyParsedNumber +import java.io.ObjectStreamException + +/** + */ +internal class LazilyParsedNumberComparable + +/** + * Constructor for LazilyParsedNumberComparable. + * @param inner LazilyParsedNumber + */(private val inner: LazilyParsedNumber) : Number(), Comparable { + /** + * Method compareTo. + * @param o Number + * @return int + */ + override fun compareTo(o: Number): Int { + return Longs.compare(inner.toLong(), o.toLong()) + } + + /** + * Method doubleValue. + * @return double + */ + override fun toDouble(): Double { + return inner.toDouble() + } + + /** + * Method floatValue. + * @return float + */ + override fun toFloat(): Float { + return inner.toFloat() + } + + /** + * Method intValue. + * @return int + */ + override fun toInt(): Int { + return inner.toInt() + } + + /** + * Method longValue. + * @return long + */ + override fun toLong(): Long { + return inner.toLong() + } + + /** + * Method byteValue. + * @return byte + */ + override fun toByte(): Byte { + return inner.toByte() + } + + /** + * Method shortValue. + * @return short + */ + override fun toShort(): Short { + return inner.toShort() + } + + /** + * Method equals. + * @param obj Object + * @return boolean + */ + override fun equals(obj: Any?): Boolean { + return inner == obj + } + + /** + * Method hashCode. + * @return int + */ + override fun hashCode(): Int { + return inner.hashCode() + } + + /** + * Method toString. + * @return String + */ + override fun toString(): String { + return inner.toString() + } + + /** + * Method writeReplace. + * @return Object + * @throws ObjectStreamException + */ + @Throws(ObjectStreamException::class) + private fun writeReplace(): Any { + return inner + } + + companion object { + private const val serialVersionUID: Long = 761729254455440231L + } +} \ No newline at end of file diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/i/LinkValueAdapter.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/i/LinkValueAdapter.kt new file mode 100644 index 0000000..69c23f1 --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/i/LinkValueAdapter.kt @@ -0,0 +1,125 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.i + +import com.google.common.base.Preconditions +import com.google.gson.* +import com.ibm.common.activitystreams.* +import com.ibm.common.activitystreams.LinkValue.SimpleLinkValue +import com.ibm.common.activitystreams.Makers.linkValue +import com.ibm.common.activitystreams.Makers.linkValues +import java.lang.reflect.Type + +/** + * @author james + * @version $Revision: 1.0 $ + */ +internal class LinkValueAdapter + +/** + * Constructor for LinkValueAdapter. + * @param schema Schema + */(private val schema: Schema) : Adapter() { + /** + * Method serialize. + * @param value LinkValue + * @param type Type + * @param context JsonSerializationContext + * + * @return JsonElement + */ + override fun serialize( + value: LinkValue, + type: Type, + context: JsonSerializationContext + ): JsonElement { + when (value.valueType()) { + ValueType.SIMPLE -> { + val simple: SimpleLinkValue = value as SimpleLinkValue + return context.serialize(simple.url(), String::class.java) + } + + ValueType.ARRAY -> return context.serialize(value, Iterable::class.java) + ValueType.OBJECT -> return context.serialize(value, ASObject::class.java) + else -> throw IllegalArgumentException() + } + } + + /** + * Method deserialize. + * @param el JsonElement + * @param type Type + * @param context JsonDeserializationContext + * + * + * + * @return LinkValue * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) + */ + @Throws(JsonParseException::class) + override fun deserialize( + el: JsonElement, + type: Type, + context: JsonDeserializationContext + ): LinkValue { + Preconditions.checkArgument( + el.isJsonArray() || + el.isJsonObject() || + el.isJsonPrimitive() + ) + if (el.isJsonArray()) { + val builder: LinkValue.ArrayLinkValue.Builder = + linkValues() + for (aryel: JsonElement? in el.getAsJsonArray()) builder.add( + context.deserialize( + aryel, + LinkValue::class.java + ) + ) + return builder.get() + } else if (el.isJsonObject()) { + val obj: JsonObject = el.getAsJsonObject() + if (obj.has("objectType")) { + val tv: TypeValue = + context.deserialize( + obj.get("objectType"), + TypeValue::class.java + ) + val pMap: Model? = + schema.forObjectType(tv.id()) + return context.deserialize( + el, + if (pMap != null && pMap.type() != null) pMap.type() else ASObject::class.java + ) + } else { + return context.deserialize( + el, + ASObject::class.java + ) + } + } else { + val prim: JsonPrimitive = + el.getAsJsonPrimitive() + Preconditions.checkArgument(prim.isString()) + return linkValue(prim.getAsString()) + } + } +} diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/i/Model.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/i/Model.kt new file mode 100644 index 0000000..d6b3618 --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/i/Model.kt @@ -0,0 +1,521 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.i + +import com.google.common.base.Objects +import com.google.common.base.Supplier +import com.google.common.collect.ImmutableMap +import com.google.common.collect.Maps +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.LinkValue +import com.ibm.common.activitystreams.NLV +import com.ibm.common.activitystreams.TypeValue +import org.joda.time.DateTime +import org.joda.time.ReadableDuration +import org.joda.time.ReadableInterval +import org.joda.time.ReadablePeriod +import java.lang.reflect.Type + +/** + * @author james + * @version $Revision: 1.0 $ + */ +class Model internal constructor(builder: Builder) { + val parent: String? + val properties: ImmutableMap + val _default: Type? + val _type: Type? + val _builder: Type? + + @Transient + private var schema: Schema? = null + + /** + * Method schema. + * @param schema Schema + */ + fun schema(schema: Schema?) { + this.schema = schema + } + + /** + * @author james + * @version $Revision: 1.0 $ + */ + class Builder + + : Supplier { + var _type: Type? = null + var _builder: Type? = null + var _default: Type? = null + var parent: String? = null + + val properties: MutableMap = Maps.newHashMap() + + internal constructor() + + /** + * Constructor for Builder. + * @param template PropertyMap + */ + internal constructor(template: Model) { + this.parent = template.parent + this._default = template._default + this._type = template._type + this._builder = template._builder + properties.putAll(template.properties) + } + + /** + * Method withDefault. + * @param _default Class + * @return Builder + */ + fun withDefault(_default: Class<*>?): Builder { + this._default = _default + return this + } + + /** + * Method type. + * @param _type Class + * @param _builder Class + * @return Builder + */ + fun type( + _type: Class<*>?, _builder: Class<*>? + ): Builder { + this._type = _type as Class? + this._builder = _builder as Class?>? + return this + } + + + /** + * Method parent. + * @param parent String + * @return Builder + */ + fun parent(parent: String?): Builder { + this.parent = parent + return this + } + + /** + * Method naturalLanguageValue. + * @param name String + * @return Builder + */ + fun naturalLanguageValue(name: String): Builder { + return `as`(name, NLV::class.java) + } + + /** + * Method naturalLanguageValue. + * @param names String[] + * @return Builder + */ + fun naturalLanguageValue(vararg names: String): Builder { + for (name: String in names) naturalLanguageValue(name) + return this + } + + /** + * Method object. + * @param name String + * @return Builder + */ + fun `object`(name: String): Builder { + return `as`(name, ASObject::class.java) + } + + /** + * Method object. + * @param names String[] + * @return Builder + */ + fun `object`(vararg names: String): Builder { + for (name: String in names) `object`(name) + return this + } + + /** + * Method integer. + * @param name String + * @return Builder + */ + fun integer(name: String): Builder { + return `as`(name, Int::class.java) + } + + /** + * Method integer. + * @param names String[] + * @return Builder + */ + fun integer(vararg names: String): Builder { + for (name: String in names) integer(name) + return this + } + + /** + * Method doub. + * @param name String + * @return Builder + */ + fun doub(name: String): Builder { + return `as`(name, Double::class.java) + } + + /** + * Method doub. + * @param names String[] + * @return Builder + */ + fun doub(vararg names: String): Builder { + for (name: String in names) doub(name) + return this + } + + /** + * Method doub. + * @param name String + * @return Builder + */ + fun floatValue(name: String): Builder { + return `as`(name, Float::class.java) + } + + /** + * Method doub. + * @param names String[] + * @return Builder + */ + fun floatValue(vararg names: String): Builder { + for (name: String in names) floatValue(name) + return this + } + + /** + * Method string. + * @param name String + * @return Builder + */ + fun string(name: String): Builder { + return `as`(name, String::class.java) + } + + /** + * Method string. + * @param names String[] + * @return Builder + */ + fun string(vararg names: String): Builder { + for (name: String in names) string(name) + return this + } + + /** + * Method linkValue. + * @param name String + * @return Builder + */ + fun linkValue(name: String): Builder { + return `as`(name, LinkValue::class.java) + } + + /** + * Method linkValue. + * @param names String[] + * @return Builder + */ + fun linkValue(vararg names: String): Builder { + for (name: String in names) linkValue(name) + return this + } + + /** + * Method dateTime. + * @param name String + * @return Builder + */ + fun dateTime(name: String): Builder { + return `as`(name, DateTime::class.java) + } + + /** + * Method dateTime. + * @param names String[] + * @return Builder + */ + fun dateTime(vararg names: String): Builder { + for (name: String in names) dateTime(name) + return this + } + + /** + * Method duration. + * @param name String + * @return Builder + */ + fun duration(name: String): Builder { + return `as`(name, ReadableDuration::class.java) + } + + /** + * Method duration. + * @param names String[] + * @return Builder + */ + fun duration(vararg names: String): Builder { + for (name: String in names) duration(name) + return this + } + + /** + * Method period. + * @param name String + * @return Builder + */ + fun period(name: String): Builder { + return `as`(name, ReadablePeriod::class.java) + } + + /** + * Method period. + * @param names String[] + * @return Builder + */ + fun period(vararg names: String): Builder { + for (name: String in names) period(name) + return this + } + + /** + * Method interval. + * @param name String + * @return Builder + */ + fun interval(name: String): Builder { + return `as`(name, ReadableInterval::class.java) + } + + /** + * Method interval. + * @param names String[] + * @return Builder + */ + fun interval(vararg names: String): Builder { + for (name: String in names) interval(name) + return this + } + + /** + * Method typeValue. + * @param name String + * + * @return Builder + */ + fun typeValue(name: String): Builder { + return `as`(name, TypeValue::class.java) + } + + /** + * Method typeValue. + * @param names String[] + * + * @return Builder + */ + fun typeValue(vararg names: String): Builder { + for (name: String in names) typeValue(name) + return this + } + + /** + * Method as. + * @param name String + * @param _class Class + * + * @return Builder + */ + fun `as`(name: String, _class: Class<*>): Builder { + properties.put(name, _class) + return this + } + + /** + * Method get. + * + * + * @return PropertyMap * @see com.google.common.base.Supplier#get() + */ + override fun get(): Model { + return Model(this) + } + } + + /** + * Constructor for PropertyMap. + * @param builder Builder + */ + init { + this.parent = builder.parent + this.properties = ImmutableMap.copyOf(builder.properties) + this._default = builder._default + this._type = builder._type + this._builder = builder._builder + } + + /** + * Method parentPropertyMap. + * + * @return PropertyMap + */ + protected fun parentPropertyMap(): Model? { + if (schema == null) return null + if (parent == null) return null + return schema!!.forObjectClassOrType( + ASObject.Builder::class.java, + if (parent == "object") null else parent + ) + } + + /** + * Method get. + * @param name String + * + * @return Class + */ + fun get(name: String?): T? { + val parent: Model? = parentPropertyMap() + return (if (properties.containsKey(name)) properties.get(name) else if (parent != null && _default == null) parent.get( + name + ) else _default) as T? + } + + /** + * Method containsKey. + * @param name String + * + * @return boolean + */ + fun has(name: String?): Boolean { + val parent: Model? = parentPropertyMap() + return if (properties.containsKey(name)) true else if (parent != null) parent.has(name) else false + } + + /** + * Method type. + * + * @return Class + */ + fun type(): Class? { + return _type as Class? + } + + /** + * Method builder. + * + * @return Class> + */ + fun builder(): Class?>? { + return _builder as Class?>? + } + + /** + * Method toString. + * + * @return String + */ + override fun toString(): String { + return Objects.toStringHelper(Model::class.java) + .omitNullValues() + .add("Parent", parent) + .add("Properties", properties) + .toString() + } + + /** + * Method template. + * + * @return Builder + */ + fun template(): Builder { + return Builder(this) + } + + /** + * Method template. + * @param _type Class + * @param _builder Class + * + * @return PropertyMap + */ + fun ?> template( + _type: Class?, _builder: Class? + ): Model { + return template().type(_type, _builder).get() + } + + /** + * Method set. + * @param name String + * @param type Class + * + * @return PropertyMap + */ + fun set(name: String, type: Class<*>): Model { + return template() + .`as`(name, type) + .get() + } + + /** + * Method set. + * @param map Map,Class> + * + * @return PropertyMap + */ + fun set(map: Map>): Model { + val builder: Builder = template() + for (entry: Map.Entry> in map.entries) builder.`as`(entry.key, entry.value) + return builder.get() + } + + companion object { + /** + * Method make. + * @param parent String + * + * @return Builder + */ + /** + * Method make. + * + * @return Builder + */ + @JvmOverloads + fun make(parent: String? = null): Builder { + return Builder().parent(parent) + } + } +} diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/i/MultimapAdapter.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/i/MultimapAdapter.kt new file mode 100644 index 0000000..eba61c0 --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/i/MultimapAdapter.kt @@ -0,0 +1,140 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.i + +import com.google.common.collect.ImmutableList +import com.google.common.collect.ImmutableMultimap +import com.google.common.collect.Iterables +import com.google.common.collect.Multimap +import com.google.gson.* +import com.ibm.common.activitystreams.ASObject +import java.lang.reflect.Type + +/** + * @author james + * @version $Revision: 1.0 $ + */ +internal class MultimapAdapter + + : Adapter>() { + val adaptedClass: Class> + /** + * Method getAdaptedClass. + * + * @return Class + */ + get() { + return Multimap::class.java + } + + /** + * Method serialize. + * @param src Multimap + * @param typeOfSrc Type + * @param context JsonSerializationContext + * + * @return JsonElement + */ + override fun serialize( + src: Multimap<*, *>, + typeOfSrc: Type, + context: JsonSerializationContext + ): JsonElement { + val obj: JsonObject = JsonObject() + for (key: Any in src.keySet()) { + val vals: Iterable = (src as Multimap).get(key) + if (Iterables.size(vals) == 1) { + val f: Any? = Iterables.getFirst(vals, null) + if (f != null) obj.add(key.toString(), context.serialize(f, f.javaClass)) + } else { + obj.add(key.toString(), context.serialize(vals, Iterable::class.java)) + } + } + return obj + } + + /** + * Method deserialize. + * @param json JsonElement + * @param typeOfT Type + * @param context JsonDeserializationContext + * + * + * + * @return Multimap * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) + */ + @Throws(JsonParseException::class) + override fun deserialize( + json: JsonElement, + typeOfT: Type, + context: JsonDeserializationContext + ): Multimap<*, *> { + val mm = + ImmutableMultimap.builder() + val obj: JsonObject = json.asJsonObject + for (entry: Map.Entry in obj.entrySet()) { + val key: String = entry.key + val `val`: JsonElement = entry.value + if (`val`.isJsonArray) { + for (el: JsonElement in `val`.asJsonArray) { + if (el.isJsonArray) mm.put(key, arraydes(el.asJsonArray, context)) + else if (el.isJsonObject) mm.put(key, context.deserialize(el, ASObject::class.java)) + else if (el.isJsonPrimitive) mm.put( + key, + ASObjectAdapter.Companion.primConverter.convert(el.asJsonPrimitive) + ) + } + } else if (`val`.isJsonObject) { + mm.put(key, context.deserialize(`val`, ASObject::class.java)) + } else if (`val`.isJsonPrimitive) { + mm.put(key, ASObjectAdapter.Companion.primConverter.convert(`val`.asJsonPrimitive)) + } + } + return mm.build() + } + + companion object { + /** + * Method arraydes. + * @param array JsonArray + * @param context JsonDeserializationContext + * + * @return ImmutableList + */ + fun arraydes( + array: JsonArray, + context: JsonDeserializationContext + ): ImmutableList { + val builder: ImmutableList.Builder = + ImmutableList.builder() + for (child: JsonElement in array) if (child.isJsonArray) builder.add( + arraydes( + child.asJsonArray, + context + ) + ) + else if (child.isJsonObject) builder.add(*context.deserialize(child, ASObject::class.java)) + else if (child.isJsonPrimitive) builder.add(ASObjectAdapter.Companion.primConverter.convert(child.asJsonPrimitive)) + return builder.build() + } + } +} diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/i/NaturalLanguageValueAdapter.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/i/NaturalLanguageValueAdapter.kt new file mode 100644 index 0000000..1d4bb05 --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/i/NaturalLanguageValueAdapter.kt @@ -0,0 +1,114 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.i + +import com.google.common.base.Preconditions +import com.google.gson.* +import com.ibm.common.activitystreams.* +import com.ibm.common.activitystreams.NLV.MapNLV +import com.ibm.common.activitystreams.NLV.SimpleNLV +import com.ibm.common.activitystreams.NLV.SimpleNLV.Companion.make +import java.lang.reflect.Type + +/** + * @author james + * @version $Revision: 1.0 $ + */ +internal class NaturalLanguageValueAdapter + + : Adapter() { + /** + * Method serialize. + * @param nlv NLV + * @param type Type + * @param context JsonSerializationContext + * + * @return JsonElement + */ + override fun serialize( + nlv: NLV, + type: Type, + context: JsonSerializationContext + ): JsonElement? { + var el: JsonElement? = null + when (nlv.valueType()) { + ValueType.SIMPLE -> el = context.serialize((nlv as SimpleNLV).value()) + ValueType.OBJECT -> { + val map: MapNLV = + nlv as MapNLV + val obj: JsonObject = JsonObject() + for (lang: String in map) obj.addProperty( + lang.toString(), + map.value(lang) + ) + el = obj + } + + else -> {} + } + return el + } + + /** + * Method deserialize. + * @param element JsonElement + * @param type1 Type + * @param context JsonDeserializationContext + * + * + * + * @return NLV * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) + */ + @Throws(JsonParseException::class) + override fun deserialize( + element: JsonElement, + type1: Type, + context: JsonDeserializationContext + ): NLV { + Preconditions.checkArgument( + element.isJsonPrimitive() || + element.isJsonObject() + ) + if (element.isJsonPrimitive()) { + val prim: JsonPrimitive = + element.getAsJsonPrimitive() + Preconditions.checkArgument(prim.isString()) + return make( + prim.getAsString() + ) + } else { + try { + val obj: JsonObject = + element.getAsJsonObject() + val builder: MapNLV.Builder = + MapNLV.make() + for (entry: Map.Entry in obj.entrySet()) builder.set( + entry.key, + entry.value.getAsString() + ) + return builder.get() + } catch (t: Throwable) { + throw IllegalArgumentException() + } + } + } +} diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/i/Schema.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/i/Schema.kt new file mode 100644 index 0000000..577f44e --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/i/Schema.kt @@ -0,0 +1,447 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.i + +import com.google.common.base.Converter +import com.google.common.base.Objects +import com.google.common.base.Preconditions +import com.google.common.base.Supplier +import com.google.common.collect.* +import com.google.common.net.MediaType +import com.ibm.common.activitystreams.* +import com.ibm.common.activitystreams.Collection +import org.joda.time.Duration +import kotlin.collections.Iterable +import kotlin.collections.MutableMap +import kotlin.collections.MutableSet +import kotlin.collections.get + +/** + * @TODO: The Schema mechanism needs to be revisited and reworked + * to be much more efficient. + * @author james + * @version $Revision: 1.0 $ + */ +class Schema internal constructor(builder: Builder) { + /** + * @author james + * @version $Revision: 1.0 $ + */ + class Builder + + : Supplier { + val objectTypeMap: MutableMap = Maps.newHashMap() + val builderMap: MutableMap?>> = Maps.newHashMap() + val objectClassMap: MutableMap?>, Model> = Maps.newHashMap() + val classMap: BiMap, Class?>> = HashBiMap.create(100) + val adapters: MutableSet> = Sets.newHashSet() + + internal constructor() + + /** + * Constructor for Builder. + * @param template Schema + */ + internal constructor(template: Schema) { + objectTypeMap.putAll(template.objectTypeMap) + builderMap.putAll(template.builderMap) + objectClassMap.putAll(template.objectClassMap) + classMap.putAll(template.classMap) + adapters.addAll(template.adapters) + } + + /** + * Method adapter. + * @param _enumClass Class + * + * @return Builder + */ + fun > adapter( + _enumClass: Class + ): Builder { + return adapter(EnumAdapter(_enumClass)) + } + + /** + * Method adapter. + * @param _enumClass Class + * + * + * @param c Converter,E> + * @return Builder + */ + fun > adapter( + _enumClass: Class, + c: Converter + ): Builder { + return adapter(EnumAdapter(_enumClass, c)) + } + + /** + * Method adapter + * @param _enumClass Class + * @param or E + * @return Builder + */ + fun > adapter( + _enumClass: Class, or: E + ): Builder { + return adapter(EnumAdapter(_enumClass, or)) + } + + /** + * Method adapter. + * @param adapter Adapter + * + * @return Builder + */ + fun adapter(adapter: Adapter<*>): Builder { + adapters.add(adapter) + return this + } + + /** + * Method adapter. + * @param adapters Adapter[] + * + * @return Builder + */ + fun adapter(vararg adapters: Adapter<*>): Builder { + if (adapters == null) return this + for (a: Adapter<*> in adapters) adapter(a) + return this + } + + /** + * Method adapter. + * @param adapters Iterable> + * + * @return Builder + */ + fun adapter(adapters: Iterable>?): Builder { + if (adapters == null) return this + Iterables.addAll(this.adapters, adapters) + return this + } + + /** + * Method map. + * @param objectType String + * @param propertyMap Supplier + * + * @return Builder + */ + fun map(objectType: String?, propertyMap: Supplier): Builder { + return map(objectType, propertyMap.get()) + } + + /** + * Method map. + * @param propertyMap Supplier + * + * @return Builder + */ + fun map(propertyMap: Supplier): Builder { + return map(null, propertyMap) + } + + /** + * Method map. + * @param propertyMap PropertyMap + * + * @return Builder + */ + fun map(propertyMap: Model): Builder { + return map(null, propertyMap) + } + + /** + * Method map. + * @param objectType String + * @param propertyMap PropertyMap + * + * @return Builder + */ + fun map(objectType: String?, propertyMap: Model): Builder { + Preconditions.checkNotNull(propertyMap) + val _builder: Class?>? = propertyMap.builder() + val _type: Class? = propertyMap.type() + if (objectType != null) objectTypeMap.put(objectType, propertyMap) + if (objectType != null && _builder != null) builderMap.put(objectType, _builder) + if (_builder != null) objectClassMap.put(_builder, propertyMap) + if (_builder != null && _type != null) classMap.put(_type, _builder) + return this + } + + fun model(objectType: String): Model? { + return objectTypeMap.get(objectType) + } + + fun model(): Model? { + return objectClassMap.get(ASObject.Builder::class.java) + } + + /** + * Method get. + * @return Schema * @see com.google.common.base.Supplier#get() + */ + override fun get(): Schema { + return Schema(this) + } + } + + val objectTypeMap: ImmutableMap + val objectClassMap: ImmutableMap?>, Model> + val builderMap: ImmutableMap?>> + val classMap: ImmutableBiMap, Class?>> + val adapters: ImmutableSet> + + /** + * Method adapters. + * + * @return Iterable> + */ + fun adapters(): Iterable> { + return adapters + } + + /** + * Method builderForObjectTypeOrClass. + * @param ots String + * @param _class Class + * + * @return Class + */ + fun builderForObjectTypeOrClass(ots: String?, _class: Class<*>?): Class?>? { + val _builder: Class?>? = builderFor(ots) + return if (_builder != null) _builder else builderFor(_builder as Class<*>) + } + + /** + * Method builderFor. + * @param _class Class + * + * @return Class + */ + fun builderFor(_class: Class<*>?): Class?>? { + if (_class == null) return null + return classMap.get(_class) + } + + /** + * Method classFor. + * @param _builder Class + * + * @return Class + */ + fun classFor(_builder: Class?>?): Class? { + if (_builder == null) return null + return classMap.inverse().get(_builder) + } + + /** + * Method builderFor. + * @param ots String + * + * @return Class + */ + fun builderFor(ots: String?): Class?>? { + if (ots == null) return null + return builderMap.get(ots) + } + + /** + * Method forObjectType. + * @param objectType String + * + * @return PropertyMap + */ + fun forObjectType(objectType: String?): Model? { + return objectTypeMap.get(objectType) + } + + /** + * Method forObjectClass. + * @param _class Class + * + * @return PropertyMap + */ + fun forObjectClass(_class: Class?>): Model? { + return objectClassMap.get(_class) + } + + /** + * Method forObjectClassOrType. + * @param _class Class + * @param objectType String + * + * @return PropertyMap + */ + fun forObjectClassOrType(_class: Class?>, objectType: String?): Model { + val pm: Model? = forObjectClass(_class) + return if (pm != null) pm else forObjectType(objectType)!! + } + + /** + * Method template. + * + * @return Builder + */ + fun template(): Builder { + return Builder(this) + } + + /** + * Method toString. + * + * @return String + */ + override fun toString(): String { + return Objects.toStringHelper(Schema::class.java) + .add("Object Types", objectTypeMap) + .add("Object Classes", objectClassMap) + .toString() + } + + /** + * Constructor for Schema. + * @param builder Builder + */ + init { + this.objectClassMap = ImmutableMap.copyOf(builder.objectClassMap) + this.objectTypeMap = ImmutableMap.copyOf(builder.objectTypeMap) + this.builderMap = ImmutableMap.copyOf(builder.builderMap) + this.adapters = ImmutableSet.copyOf(builder.adapters) + this.classMap = ImmutableBiMap.copyOf(builder.classMap) + + for (pmap: Model in objectTypeMap.values) pmap.schema(this) + for (pmap: Model in objectClassMap.values) pmap.schema(this) + } + + companion object { + @JvmField + val `object`: Model = Model.make() + .type( + ASObject::class.java, + ASObject.Builder::class.java + ) + .typeValue( + "objectType" + ) + .linkValue( + "attachments", + "author", + "duplicates", + "icon", + "image", + "location", + "inReplyTo", + "tags", + "url", + "generator", + "provider", + "scope" + ) + .dateTime( + "published", + "updated", + "startTime", + "endTime" + ) + .naturalLanguageValue( + "summary", + "title", + "content", + "displayName" + ) + .`as`("language", String::class.java) + .`as`("actions", ActionsValue::class.java) + .string("id", "rel", "alias") + .doub("rating") + .integer("height", "width") + .`as`("mediaType", MediaType::class.java) + .`as`("duration", Duration::class.java) + .get() + + val activity: Model = Model.Companion.make("object") + .type( + Activity::class.java, + Activity.Builder::class.java + ) + .typeValue("verb") + .linkValue( + "actor", + "participant", + "instrument", + "object", + "target", + "result", + "to", + "bto", + "cc", + "bcc" + ) + .doub("priority") + .`as`("status", Activity.Status::class.java) + .get() + + val collection: Model = Model.Companion.make("object") + .type( + Collection::class.java, + Collection.Builder::class.java + ) + .dateTime( + "itemsBefore", + "itemsAfter" + ) + .linkValue( + "first", + "last", + "prev", + "next", + "current", + "self" + ) + .`object`("items") + .integer( + "startIndex", + "itemsPerPage", + "totalItems" + ) + .get() + + /** + * Method make. + * + * @return Schema.Builder + */ + @JvmStatic + fun make(): Builder { + return Builder() + .map(null, `object`) + .map("activity", activity) + .map("collection", collection) + } + + val DEFAULT_SCHEMA: Schema = make().get() + } +} diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/i/SimpleAdapter.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/i/SimpleAdapter.kt new file mode 100644 index 0000000..8b164ad --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/i/SimpleAdapter.kt @@ -0,0 +1,92 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.i + +import com.google.common.base.Function +import com.google.gson.JsonDeserializationContext +import com.google.gson.JsonElement +import com.google.gson.JsonParseException +import com.google.gson.JsonSerializationContext +import java.lang.reflect.Type + +/** + * @author james + * @version $Revision: 1.0 $ + */ +abstract class SimpleAdapter + : Adapter(), Function { + /** + * Method serialize. + * @param t T + * @param type Type + * @param context JsonSerializationContext + * + * + * @return JsonElement * @see com.google.gson.JsonSerializer#serialize(T, Type, JsonSerializationContext) + */ + override fun serialize( + t: T, + type: Type, + context: JsonSerializationContext + ): JsonElement { + return context.serialize(serialize(t)) + } + + /** + * Method serialize. + * @param t T + * + * @return String + */ + protected open fun serialize(t: T?): String? { + return t?.toString() + } + + /** + * Method deserialize. + * @param v String + * + * @return T + */ + protected fun deserialize(v: String?): T? { + return apply(v) + } + + /** + * Method deserialize. + * @param json JsonElement + * @param type Type + * @param context JsonDeserializationContext + * + * + * + * @return T * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) + */ + @Throws(JsonParseException::class) + override fun deserialize( + json: JsonElement, + type: Type, + context: JsonDeserializationContext + ): T { + return deserialize(json.asJsonPrimitive.asString)!! + } +} \ No newline at end of file diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/i/TypeValueAdapter.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/i/TypeValueAdapter.kt new file mode 100644 index 0000000..85e1b43 --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/i/TypeValueAdapter.kt @@ -0,0 +1,107 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.i + +import com.google.common.base.Preconditions +import com.google.gson.* +import com.ibm.common.activitystreams.* +import com.ibm.common.activitystreams.Makers.type +import java.lang.reflect.Type + +/** + * @author james + * @version $Revision: 1.0 $ + */ +internal class TypeValueAdapter + +/** + * Constructor for TypeValueAdapter. + * @param schema Schema + */(private val schema: Schema) : Adapter() { + /** + * Method serialize. + * @param value TypeValue + * @param type Type + * @param context JsonSerializationContext + * + * @return JsonElement + */ + override fun serialize( + value: TypeValue, + type: Type, + context: JsonSerializationContext + ): JsonElement { + val simple: Boolean = value.valueType() == ValueType.SIMPLE + return context.serialize( + if (simple) value.id() else value, + if (simple) String::class.java else ASObject::class.java + ) + } + + /** + * Method deserialize. + * @param el JsonElement + * @param type Type + * @param context JsonDeserializationContext + * + * + * + * @return TypeValue * @throws JsonParseException * @see com.google.gson.JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext) + */ + @Throws(JsonParseException::class) + override fun deserialize( + el: JsonElement, + type: Type, + context: JsonDeserializationContext + ): TypeValue { + Preconditions.checkArgument( + el.isJsonPrimitive() || + el.isJsonObject() + ) + if (el.isJsonPrimitive()) { + val prim: JsonPrimitive = + el.getAsJsonPrimitive() + Preconditions.checkArgument(prim.isString()) + return type(prim.getAsString()) + } else { + val obj: JsonObject = el.getAsJsonObject() + if (obj.has("objectType")) { + val tv: TypeValue = + context.deserialize( + obj.get("objectType"), + TypeValue::class.java + ) + val pMap: Model? = + schema.forObjectType(tv.id()) + return context.deserialize( + el, + if (pMap!!.type() != null) pMap.type() else ASObject::class.java + ) + } else { + return context.deserialize( + el, + ASObject::class.java + ) + } + } + } +} diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/util/AbstractDictionaryObject.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/util/AbstractDictionaryObject.kt new file mode 100644 index 0000000..bb2585d --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/util/AbstractDictionaryObject.kt @@ -0,0 +1,276 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.util + +import com.google.common.base.Function +import com.google.common.base.Predicate +import com.google.common.base.Supplier +import com.google.common.collect.ImmutableList +import com.google.common.collect.ImmutableMap +import com.google.common.collect.Iterables +import com.google.common.collect.Maps +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.LinkValue +import com.ibm.common.activitystreams.LinkValue.ArrayLinkValue +import com.ibm.common.activitystreams.LinkValue.ArrayLinkValue.Companion.make +import com.ibm.common.activitystreams.Makers.linkValue +import com.ibm.common.activitystreams.Makers.linkValues +import com.ibm.common.activitystreams.ValueType +import java.beans.Transient + +/** + * Utility abstract base used for objects that are JSON + * dictionaries as opposed to full Activity Stream objects. + * @author james + * @version $Revision: 1.0 $ + */ +abstract class AbstractDictionaryObject +protected constructor(builder: AbstractBuilder) : + AbstractWritable(builder), Iterable { + abstract class AbstractBuilder + , B : AbstractBuilder> + : AbstractWritableBuilder() { + val map: MutableMap = Maps.newHashMap() + private var isempty = true + + /** + * Returns true if items have been added + * @return boolean + */ + fun notEmpty(): Boolean { + return !isempty + } + + /** + * Sets an item in this dictionary object + * @param key String + * @param x X + * @return B + */ + open operator fun set(key: String, x: X?): B { + if (x != null) { + map[key] = x + isempty = false + } + return this as B + } + + /** + * Sets an item in this dictionary object + * @param key String + * @param x Supplier + * @return B + */ + open fun set( + key: String, + x: Supplier + ): B { + return set(key, x.get()) + } + + /** + * Add a link + * @param name String + * @param url String + * @return B + */ + protected fun link(name: String, url: String?): B { + return link(name, linkValue(url)) + } + + /** + * Add a link + * @param name String + * @param link LinkValue + * @return B + */ + protected fun link(name: String, link: LinkValue?): B { + var link = link + ?: return this as B + isempty = false + val obj: Any? = map[name] + if (link.valueType() != ValueType.ARRAY) { + if (obj is LinkValue) link = + if (obj.valueType() == ValueType.ARRAY) linkValues() + .add(obj as Iterable) + .add(link) + .get() else linkValues() + .add(obj, link) + .get() + map[name] = link as X + } else map[name] = link as X + return this as B + } + + /** + * Add a link + * @param name String + * @param link Supplier + * @return B + */ + fun link(name: String, link: Supplier): B { + return link(name, link.get()) + } + + /** + * Add a link + * @param name String + * @param links Object[] + * @return B + */ + protected fun link(name: String, vararg links: Any?): B { + if (links == null) return this as B + val b = + make() + for (obj in links) _add(b, obj) + return link(name, b.get()) + } + + /** + * Method _add. + * @param builder ArrayLinkValue.Builder + * @param obj Object + */ + private fun _add(builder: ArrayLinkValue.Builder, obj: Any?) { + if (obj == null) return + else if (obj is String) builder.add(obj) + else if (obj is ASObject) builder.add(obj) + else if (obj is Supplier<*>) _add(builder, obj.get()) + else throw IllegalArgumentException() + } + } + + private val map: ImmutableMap = + ImmutableMap.copyOf(builder.map) + + @get:Transient + private var hash = 1 + + /** + * Method getSingle. + * @param key String + * @return X + */ + fun getSingle(key: String?): X? { + return map[key] + } + + /** + * Method getSingle. + * @param key String + * @param defaultValue X + * @return X + */ + protected fun getSingle(key: String?, defaultValue: X): X { + val ret = getSingle(key) + return ret ?: defaultValue + } + + /** + * Method getIterable. + * @param key String + * @return Iterable + */ + protected fun getIterable(key: String?): Iterable { + val x = map[key] + return if (x is Iterable<*>) x as Iterable else x?.let { ImmutableList.of(it) }.orEmpty() + } + + /** + * Method getIterable. + * @param key String + * @param filter Predicate + * @return Iterable + */ + protected fun getIterable( + key: String?, + filter: Predicate + ): Iterable { + return Iterables.filter(getIterable(key), filter) + } + + /** + * Method getIterable. + * @param key String + * @param transform Function,Y> + * @return Iterable + */ + protected fun getIterable( + key: String?, + transform: Function + ): Iterable { + return Iterables.transform(getIterable(key), transform) + } + + /** + * Method getIterable. + * @param key String + * @param filter Predicate + * @param transform Function,Y> + * @return Iterable + */ + protected fun getIterable( + key: String?, + filter: Predicate, + transform: Function + ): Iterable { + return Iterables.transform(Iterables.filter(getIterable(key), filter), transform) + } + + override fun iterator(): MutableIterator { + return map.keys.iterator() + } + + /** + * Returns true if the verb appears in the ActionsValue object + * @param key String + * @return boolean + */ + fun has(key: String?): Boolean { + return map.containsKey(key) + } + + /** + * Returns true if the verb appears in the ActionsValue object + * and there is at least one handler in the value. + * @param key String + * @return boolean + */ + protected open fun hasAtLeastOne(key: String?): Boolean { + return has(key) && Iterables.size(getIterable(key)) > 0 + } + + override fun hashCode(): Int { + if (hash == 1) hash = map.hashCode() + return hash + } + + + override fun equals(obj: Any?): Boolean { + if (this === obj) return true + if (obj == null) return false + if (javaClass != obj.javaClass) return false + val other = + obj as AbstractDictionaryObject<*> + return map.toSortedMap() == other.map.toSortedMap() + } +} diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/util/AbstractDictionaryObjectAdapter.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/util/AbstractDictionaryObjectAdapter.kt new file mode 100644 index 0000000..6de245e --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/util/AbstractDictionaryObjectAdapter.kt @@ -0,0 +1,81 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.util + +import com.google.common.base.Preconditions +import com.google.gson.* +import com.ibm.common.activitystreams.i.Adapter +import java.lang.reflect.Type + +/** + * Abstract base GSON Serializer for AbstractDictionaryObject + * instances. + * @author james + * @version $Revision: 1.0 $ + */ +abstract class AbstractDictionaryObjectAdapter +, B : AbstractDictionaryObject.AbstractBuilder> +/** + * Constructor for AbstractDictionaryObjectAdapter. + * @param klass Class + */ protected constructor(private val klass: Class) : Adapter() { + override fun serialize( + x: X, + type: Type, + context: JsonSerializationContext + ): JsonElement { + val obj = JsonObject() + for (key in x!!) obj.add( + key, + context.serialize( + x.getSingle(key), + klass + ) + ) + return obj + } + + @Throws(JsonParseException::class) + override fun deserialize( + element: JsonElement, + type1: Type, + context: JsonDeserializationContext + ): X { + Preconditions.checkArgument(element.isJsonObject) + try { + val obj = + element.asJsonObject + val builder = builder() + for ((key, value) in obj.entrySet()) builder!![key!!] = + context.deserialize( + value, + klass + ) + return builder!!.get() + } catch (t: Throwable) { + t.printStackTrace() + throw IllegalArgumentException() + } + } + + protected abstract fun builder(): B +} diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/util/AbstractWritable.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/util/AbstractWritable.kt new file mode 100644 index 0000000..1c1f253 --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/util/AbstractWritable.kt @@ -0,0 +1,146 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.util + +import com.google.common.base.Supplier +import com.ibm.common.activitystreams.IO +import com.ibm.common.activitystreams.IO.Companion.makeDefault +import com.ibm.common.activitystreams.Writable +import java.io.OutputStream +import java.io.StringWriter +import java.io.Writer +import java.util.concurrent.ExecutorService +import java.util.concurrent.Future + +/** + * Utility base class for Writable instances. + * @author james + * @version $Revision: 1.0 $ + */ +abstract class AbstractWritable +protected constructor(b: AbstractWritableBuilder<*, *>) : Writable { + abstract class AbstractWritableBuilder + ?> + : Supplier { + var io: IO? = null + + /** + * Set the IO instance that should be used + * by default for writing instances of this + * object. + */ + fun writeUsing(io: IO?): B { + this.io = io + return this as B + } + + fun writeTo(out: OutputStream) { + get()!!.writeTo(out) + } + + fun writeTo(out: OutputStream, executor: ExecutorService): Future<*> { + return get()!!.writeTo(out, executor) + } + + fun writeTo(out: Writer) { + get()!!.writeTo(out) + } + + fun writeTo(out: Writer, executor: ExecutorService): Future<*> { + return get()!!.writeTo(out, executor) + } + + + fun writeTo(out: OutputStream, io: IO) { + get()!!.writeTo(out, io) + } + + fun writeTo(out: OutputStream, io: IO, executor: ExecutorService): Future<*> { + return get()!!.writeTo(out, io, executor) + } + + fun writeTo(out: Writer, io: IO) { + get()!!.writeTo(out, io) + } + + fun writeTo(out: Writer, io: IO, executor: ExecutorService): Future<*> { + return get()!!.writeTo(out, io, executor) + } + } + + private val io: IO + + init { + this.io = if (b.io != null) b.io!! else makeDefault() + } + + override fun writeTo(out: OutputStream) { + writeTo(out, io) + } + + override fun writeTo(out: OutputStream, executor: ExecutorService): Future<*> { + return writeTo(out, io, executor) + } + + override fun writeTo(out: OutputStream, io: IO) { + io.write(this, out) + } + + override fun writeTo(out: OutputStream, io: IO, executor: ExecutorService): Future<*> { + return io.write(this, out, executor) + } + + override fun writeTo(out: Writer) { + writeTo(out, io) + } + + override fun writeTo(out: Writer, executor: ExecutorService): Future<*> { + return writeTo(out, io, executor) + } + + override fun writeTo(out: Writer, io: IO) { + io.write(this, out) + } + + override fun writeTo(out: Writer, io: IO, executor: ExecutorService): Future<*> { + return io.write(this, out, executor) + } + + open fun toString(io: IO): String { + val sw = + StringWriter() + io.write(this, sw) + return sw.toString() + } + + fun toString(executor: ExecutorService): Future { + return io.write(this, executor) + } + + fun toString(io: IO, executor: ExecutorService): Future { + return io.write(this, executor) + } + + override fun toString(): String { + return toString(io) + } +} diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/util/Converters.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/util/Converters.kt new file mode 100644 index 0000000..f13f707 --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/util/Converters.kt @@ -0,0 +1,310 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.util + +import com.google.common.base.* +import com.google.common.base.Function +import com.google.common.base.Optional +import com.google.common.primitives.Doubles +import com.google.common.primitives.Floats +import com.google.common.primitives.Ints +import com.google.common.primitives.Longs +import org.joda.time.DateTime +import org.joda.time.Duration +import org.joda.time.Interval +import org.joda.time.Period +import java.util.* +import java.util.concurrent.TimeUnit + +object Converters { + /** + * Method toDuration. + * @param v long + * @param unit TimeUnit + * @return Duration + */ + fun toDuration(v: Long, unit: TimeUnit): Duration { + return when (unit) { + TimeUnit.NANOSECONDS -> Duration.millis(v / 1000 / 1000) + TimeUnit.MICROSECONDS -> Duration.millis(v / 1000) + TimeUnit.MILLISECONDS -> Duration.millis(v) + TimeUnit.SECONDS -> Duration.standardSeconds(v) + TimeUnit.MINUTES -> Duration.standardMinutes(v) + TimeUnit.HOURS -> Duration.standardHours(v) + TimeUnit.DAYS -> Duration.standardDays(v) + else -> throw IllegalArgumentException() + } + } + + /** + * Method tryParseShort. + * @param input String + * @return Short + */ + private fun tryParseShort(input: String): Short? { + return try { + input.toShort() + } catch (t: Throwable) { + null + } + } + + /** + * Method tryParseBoolean. + * @param input String + * @return Boolean + */ + private fun tryParseBoolean(input: String): Boolean? { + return try { + input.toBoolean() + } catch (t: Throwable) { + null + } + } + + /** + * Method tryParseDateTime. + * @param input String + * @return DateTime + */ + private fun tryParseDateTime(input: String): DateTime? { + return try { + DateTime.parse(input) + } catch (t: Throwable) { + null + } + } + + /** + * Method tryParseDuration. + * @param input String + * @return Duration + */ + private fun tryParseDuration(input: String): Duration? { + return try { + Period.parse(input).toDurationFrom(DateTime.now()) + } catch (t: Throwable) { + null + } + } + + /** + * Method tryParsePeriod. + * @param input String + * @return Period + */ + private fun tryParsePeriod(input: String): Period? { + return try { + Period.parse(input) + } catch (t: Throwable) { + null + } + } + + /** + * Method tryParseInterval. + * @param input String + * @return Interval + */ + private fun tryParseInterval(input: String): Interval? { + return try { + Interval.parse(input) + } catch (t: Throwable) { + null + } + } + + val toInterval: Function> = + Function> { input -> + var ret = Optional.absent() + if (input != null) ret = + if (input is Interval) Optional.of(input) else Optional.fromNullable( + tryParseInterval(input.toString()) + ) + ret + } + + val toDuration: Function> = + Function> { input -> + var ret = Optional.absent() + if (input != null) ret = + if (input is Duration) Optional.of(input) else if (input is Number) Optional.of( + Duration.standardSeconds(input.toLong()) + ) else Optional.fromNullable( + tryParseDuration( + input.toString() + ) + ) + ret + } + + val toPeriod: Function> = + Function> { input -> + var ret = Optional.absent() + if (input != null) ret = + if (input is Period) Optional.of(input) else Optional.fromNullable( + tryParsePeriod(input.toString()) + ) + ret + } + + val toDateTime: Function> = + Function> { input -> + var ret = Optional.absent() + if (input != null) ret = + if (input is DateTime) Optional.of(input) else if (input is Date) Optional.of( + DateTime(input) + ) else if (input is Number) Optional.of( + DateTime( + input.toLong() + ) + ) else Optional.fromNullable( + tryParseDateTime( + input.toString() + ) + ) + ret + } + + val toBoolean: Function> = + Function> { input -> + var ret = Optional.absent() + if (input != null) ret = + if (input is Boolean) Optional.of(input) else if (input is Number) Optional.of( + input.toInt() != 0 + ) else Optional.fromNullable(tryParseBoolean(input.toString())) + ret + } + + val toShort: Function> = + Function> { input -> + var ret = Optional.absent() + if (input != null) ret = + if (input is Number) Optional.of(input.toShort()) else Optional.fromNullable( + tryParseShort(input.toString()) + ) + ret + } + + val toInt: Function> = + Function> { input -> + var ret = Optional.absent() + if (input != null) ret = + if (input is Number) Optional.of(input.toInt()) else Optional.fromNullable( + Ints.tryParse(input.toString()) + ) + ret + } + + val toLong: Function> = + Function> { input -> + var ret = Optional.absent() + if (input != null) ret = + if (input is Number) Optional.of(input.toLong()) else Optional.fromNullable( + Longs.tryParse(input.toString()) + ) + ret + } + + val toDouble: Function> = + Function> { input -> + var ret = Optional.absent() + if (input != null) ret = + if (input is Number) Optional.of(input.toDouble()) else Optional.fromNullable( + Doubles.tryParse(input.toString()) + ) + ret + } + + val toFloat: Function> = + Function> { input -> + var ret = Optional.absent() + if (input != null) ret = + if (input is Number) Optional.of(input.toFloat()) else Optional.fromNullable( + Floats.tryParse(input.toString()) + ) + ret + } + + /** + * Method stringConverter. + * @param enumClass Class + * @param or E + * @return Converter,E> + */ + fun > stringConverter( + enumClass: Class, + or: E + ): Converter { + return object : Converter() { + override fun doBackward(e: E): String { + return Preconditions.checkNotNull(e)!!.name + } + + override fun doForward(s: String): E { + return Enums.getIfPresent(enumClass, s).or(or) + } + } + } + + /** + * Method toUpperConverter. + * @return Converter,String> + */ + @JvmStatic + fun toUpperConverter(): Converter { + return toLowerConverter().reverse() + } + + /** + * Method toUpperConverter. + * @param locale Locale + * @return Converter,String> + */ + @JvmStatic + fun toUpperConverter(locale: Locale): Converter { + return toLowerConverter(locale).reverse() + } + + /** + * Method toLowerConverter. + * @param locale Locale + * @return Converter,String> + */ + /** + * Method toLowerConverter. + * @return Converter,String> + */ + @JvmStatic + @JvmOverloads + fun toLowerConverter(locale: Locale = Locale.getDefault()): Converter { + return object : Converter() { + override fun doForward(a: String): String { + return a.lowercase(locale) + } + + override fun doBackward(b: String): String { + return b.uppercase(locale) + } + } + } +} diff --git a/core/src/main/java/com/ibm/common/activitystreams/util/Module.java b/core/src/main/kotlin/com/ibm/common/activitystreams/util/Module.kt similarity index 75% rename from core/src/main/java/com/ibm/common/activitystreams/util/Module.java rename to core/src/main/kotlin/com/ibm/common/activitystreams/util/Module.kt index 4d7a627..6ab7351 100644 --- a/core/src/main/java/com/ibm/common/activitystreams/util/Module.java +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/util/Module.kt @@ -19,15 +19,13 @@ * * @author James M Snell (jasnell@us.ibm.com) */ -package com.ibm.common.activitystreams.util; +package com.ibm.common.activitystreams.util -import com.ibm.common.activitystreams.IO; -import com.ibm.common.activitystreams.internal.Schema; +import com.ibm.common.activitystreams.IO +import com.ibm.common.activitystreams.i.Schema -public interface Module { +interface Module { + fun apply(builder: Schema.Builder) - void apply(Schema.Builder builder); - - void apply(IO.Builder builder, Schema schema); - + fun apply(builder: IO.Builder, schema: Schema) } diff --git a/core/src/main/kotlin/com/ibm/common/activitystreams/util/Util.kt b/core/src/main/kotlin/com/ibm/common/activitystreams/util/Util.kt new file mode 100644 index 0000000..db720af --- /dev/null +++ b/core/src/main/kotlin/com/ibm/common/activitystreams/util/Util.kt @@ -0,0 +1,18 @@ +package com.ibm.common.activitystreams.util + +import com.google.common.base.Preconditions +import java.util.* + +object Util { + /** + * Method convLocale. + * @param locale Locale + * @return String + */ + fun convLocale(locale: Locale): String { + return Preconditions.checkNotNull(locale).toString().replace("_".toRegex(), "-") + } + + @JvmField + val DEFAULT_LOCALE: String = convLocale(Locale.getDefault()) +} diff --git a/core/src/test/java/com/ibm/common/activitystreams/test/TestIO.java b/core/src/test/java/com/ibm/common/activitystreams/test/TestIO.java index 561ecc1..ff97359 100644 --- a/core/src/test/java/com/ibm/common/activitystreams/test/TestIO.java +++ b/core/src/test/java/com/ibm/common/activitystreams/test/TestIO.java @@ -21,17 +21,16 @@ */ package com.ibm.common.activitystreams.test; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -import org.joda.time.DateTime; -import org.junit.Test; - import com.ibm.common.activitystreams.ASObject; import com.ibm.common.activitystreams.Activity; import com.ibm.common.activitystreams.Collection; import com.ibm.common.activitystreams.IO; -import com.ibm.common.activitystreams.internal.Schema; +import com.ibm.common.activitystreams.i.Schema; +import org.joda.time.DateTime; +import org.junit.Test; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; public final class TestIO { diff --git a/geo/build.gradle.kts b/geo/build.gradle.kts new file mode 100644 index 0000000..c2a0486 --- /dev/null +++ b/geo/build.gradle.kts @@ -0,0 +1,24 @@ +/* + * This file was generated by the Gradle 'init' task. + */ + +plugins { + kotlin("jvm") + java +} + +dependencies { + api(project(":core")) + implementation(kotlin("stdlib-jdk8")) +} + +description = "Activity Streams 2.0 - GeoJSON" +repositories { + mavenCentral() +} +kotlin { + jvmToolchain(11) +} +tasks.test { + useJUnit() +} \ No newline at end of file diff --git a/geo/pom.xml b/geo/pom.xml deleted file mode 100755 index 7ad5ef9..0000000 --- a/geo/pom.xml +++ /dev/null @@ -1,141 +0,0 @@ - - 4.0.0 - - com.ibm.common - activitystreams - 0.0.1-SNAPSHOT - - activitystreams-geo - Activity Streams 2.0 - GeoJSON - - A GeoJSON Implementation that can be used standalone or with the IBM Activity Streams 2.0 Reference Implementation - - - - Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - UTF-8 - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9.1 - - UTF-8 - UTF-8 - UTF-8 - -XDignore.symbol.file - public - - http://www.joda.org/joda-time/apidocs - http://docs.guava-libraries.googlecode.com/git-history/v16.0.1/javadoc/ - - - - - - maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - - - - - maven-jar-plugin - 2.3.1 - - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - - - - - org.apache.felix - maven-bundle-plugin - 2.3.7 - true - - - bundle-manifest - process-classes - - manifest - - - - - - com.ibm.common.geojson.* - - com.ibm.common.activitystreams.*, - com.google.gson.*, - com.google.common.*, - org.joda.time.* - - - - - - - org.apache.maven.plugins - maven-assembly-plugin - 2.2.2 - - - assembly.xml - - - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - org.apache.felix - maven-bundle-plugin - [2.3.7,) - - manifest - - - - - - - - - - - - - - - - - com.ibm.common - activitystreams-core - 0.0.1-SNAPSHOT - - - - \ No newline at end of file diff --git a/geo/src/main/java/com/ibm/common/geojson/AS1Position.java b/geo/src/main/java/com/ibm/common/geojson/AS1Position.java deleted file mode 100644 index 4b2ab37..0000000 --- a/geo/src/main/java/com/ibm/common/geojson/AS1Position.java +++ /dev/null @@ -1,133 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.geojson; - -import static com.google.common.primitives.Floats.max; -import static com.google.common.primitives.Floats.min; - -import java.io.ObjectStreamException; - -import com.ibm.common.activitystreams.ASObject; - -/** - * Represents an Activity Streams 1.0 style position object - * see (https://github.com/activitystreams/activity-schema/blob/master/activity-schema.md) - * - * Use of the AS1Position object is deprecated. Use the GeoJSON mechanisms - * instead - * - * @author james - * @deprecated Use Position - */ -public final class AS1Position - extends ASObject { - - public static final class Builder - extends ASObject.AbstractBuilder { - - Builder() { - objectType("position"); - } - - /** - * Set the latitude - * @param latitude float - * @return Builder - */ - public Builder latitude(float latitude) { - return set("latitude", max(0f,min(90.0f,latitude))); - } - - /** - * Set the longitude - * @param longitude float - * @return Builder - */ - public Builder longitude(float longitude) { - return set("longitude", max(-180.0f,min(180.0f,longitude))); - } - - /** - * Set the altitude - * @param altitude float - * @return Builder - */ - public Builder altitude(float altitude) { - return set("altitude", altitude); - } - - @Override - public AS1Position get() { - return new AS1Position(this); - } - - } - - private AS1Position(Builder builder) { - super(builder); - } - - /** - * Get the latitude - * @return float - */ - public float latitude() { - return max(0f,min(90.0f,getFloat("latitude"))); - } - - /** - * Get the longitude - * @return float - */ - public float longitude() { - return max(-180.0f,min(180.0f,getFloat("longitude"))); - } - - /** - * Get the altitude. If the altitude property is not set, this - * will return Float.MIN_VALUE; - * @return float - */ - public float altitude() { - return getFloat("altitude", Float.MIN_VALUE); - } - - // Java Serialization Support - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936285L; - protected SerializedForm(AS1Position obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return super.doReadResolve(); - } - protected AS1Position.Builder builder() { - return GeoMakers.as1Position(); - } - } -} diff --git a/geo/src/main/java/com/ibm/common/geojson/Address.java b/geo/src/main/java/com/ibm/common/geojson/Address.java deleted file mode 100644 index 4148a4f..0000000 --- a/geo/src/main/java/com/ibm/common/geojson/Address.java +++ /dev/null @@ -1,185 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.geojson; - -import java.io.ObjectStreamException; - -import com.ibm.common.activitystreams.ASObject; - -/** - * A simple non-GeoJSON Address object modelled after the - * legacy Activity Streams 1.0 Address object - * (see https://github.com/activitystreams/activity-schema/blob/master/activity-schema.md) - * - * @author james - * - */ -public final class Address - extends ASObject { - - public static final class Builder - extends ASObject.AbstractBuilder { - - Builder() { - objectType("address"); - } - - /** - * The full mailing address formatted for display or use - * with a printed mailing label. - * @param formatted String - * @return Builder - */ - public Builder formatted(String formatted) { - return set("formatted", formatted); - } - - /** - * The street address including house number, street name, P.O. Box, - * apartment or unit number and extended multi-line address information. - * @param streetAddress String - * @return Builder - */ - public Builder streetAddress(String streetAddress) { - return set("streetAddress", streetAddress); - } - - /** - * The city or locality - * @param locality String - * @return Builder - */ - public Builder locality(String locality) { - return set("locality", locality); - } - - /** - * The state or region - * @param region String - * @return Builder - */ - public Builder region(String region) { - return set("region", region); - } - - /** - * The zip or postal code - * @param postalCode String - * @return Builder - */ - public Builder postalCode(String postalCode) { - return set("postalCode", postalCode); - } - - /** - * The country name component - * @param country String - * @return Builder - */ - public Builder country(String country) { - return set("country", country); - } - - /** - * Get the completed Address object - */ - @Override - public Address get() { - return new Address(this); - } - - } - - private Address(Builder builder) { - super(builder); - } - - /** - * The full mailing address formatted for display or use - * with a printed mailing label. - * @return String - */ - public String formatted() { - return getString("formatted"); - } - - /** - * The street address including house number, street name, P.O. Box, - * apartment or unit number and extended multi-line address information. - * @return String - */ - public String streetAddress() { - return getString("streetAddress"); - } - - /** - * The city or locality - * @return String - */ - public String locality() { - return getString("locality"); - } - - /** - * The state or region - * @return String - */ - public String region() { - return getString("region"); - } - - /** - * The zip or postal code - * @return String - */ - public String postalCode() { - return getString("postalCode"); - } - - /** - * The country name component - * @return String - */ - public String country() { - return getString("country"); - } - - // Java Serialization Support - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm
{ - private static final long serialVersionUID = -2060301713159936285L; - protected SerializedForm(Address obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return super.doReadResolve(); - } - protected Address.Builder builder() { - return GeoMakers.address(); - } - } -} diff --git a/geo/src/main/java/com/ibm/common/geojson/BoundingBox.java b/geo/src/main/java/com/ibm/common/geojson/BoundingBox.java deleted file mode 100644 index 57f39a6..0000000 --- a/geo/src/main/java/com/ibm/common/geojson/BoundingBox.java +++ /dev/null @@ -1,284 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.geojson; - -import java.io.ObjectStreamException; -import java.io.Serializable; -import java.util.Iterator; - -import com.google.common.base.Objects; -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableSortedSet; -import com.google.common.collect.Iterables; - -/** - * A GeoJSON Bounding Box (see http://geojson.org/geojson-spec.html#bounding-boxes) - * @author james - */ -public final class BoundingBox - implements Iterable, Serializable { - - public static final class Builder - implements Supplier { - - private final ImmutableList.Builder bounds = - ImmutableList.builder(); - - public Builder add(float value) { - this.bounds.add(value); - return this; - } - - public Builder add(float... values) { - if (values != null) - for (float v : values) - this.bounds.add(v); - return this; - } - - @Override - public BoundingBox get() { - return new BoundingBox(this); - } - - } - - private final ImmutableList bounds; - - BoundingBox(Builder builder) { - this.bounds = builder.bounds.build(); - } - - @Override - public Iterator iterator() { - return bounds.iterator(); - } - - public String toString() { - return Objects.toStringHelper(BoundingBox.class) - .addValue(bounds) - .toString(); - } - - private static BoundingBox buildBoundingBox( - ImmutableSortedSet xs, - ImmutableSortedSet ys, - ImmutableSortedSet zs) { - BoundingBox.Builder bbox = - new BoundingBox.Builder() - .add(xs.first()) - .add(ys.first()); - if (!zs.isEmpty()) - bbox.add(zs.first()); - bbox.add(xs.last()); - bbox.add(ys.last()); - if (!zs.isEmpty()) - bbox.add(zs.last()); - return bbox.get(); - } - - protected static BoundingBox calculateBoundingBoxLineStrings(Iterable lineStrings) { - ImmutableSortedSet.Builder xset = - ImmutableSortedSet.naturalOrder(); - ImmutableSortedSet.Builder yset = - ImmutableSortedSet.naturalOrder(); - ImmutableSortedSet.Builder zset = - ImmutableSortedSet.naturalOrder(); - for (LineString ls : lineStrings) { - for (Position p : ls) { - xset.add(p.northing()); - yset.add(p.easting()); - if (p.hasAltitude()) - zset.add(p.altitude()); - } - } - return buildBoundingBox( - xset.build(), - yset.build(), - zset.build()); - } - - /** - * Calculate the Bounding Box for a collection of Polygon objects - * @param polygons Iterable<Polygon> - * @return BoundingBox - */ - public static BoundingBox calculateBoundingBoxPolygons(Iterable polygons) { - ImmutableSortedSet.Builder xset = - ImmutableSortedSet.naturalOrder(); - ImmutableSortedSet.Builder yset = - ImmutableSortedSet.naturalOrder(); - ImmutableSortedSet.Builder zset = - ImmutableSortedSet.naturalOrder(); - for (Polygon polygon : polygons) { - for (LineString line : polygon) { - for (Position pos : line) { - xset.add(pos.northing()); - yset.add(pos.easting()); - if (pos.hasAltitude()) - zset.add(pos.altitude()); - } - } - } - return buildBoundingBox( - xset.build(), - yset.build(), - zset.build()); - } - - protected static BoundingBox calculateBoundingBoxPositions(Iterable positions) { - ImmutableSortedSet.Builder xset = - ImmutableSortedSet.naturalOrder(); - ImmutableSortedSet.Builder yset = - ImmutableSortedSet.naturalOrder(); - ImmutableSortedSet.Builder zset = - ImmutableSortedSet.naturalOrder(); - for (Position pos : positions) { - xset.add(pos.northing()); - yset.add(pos.easting()); - if (pos.hasAltitude()) - zset.add(pos.altitude()); - } - return buildBoundingBox( - xset.build(), - yset.build(), - zset.build()); - } - - protected static BoundingBox calculateBoundingBox(Position position) { - BoundingBox.Builder bbox = - new BoundingBox.Builder(); - bbox.add(position.northing()); - bbox.add(position.easting()); - if (position.hasAltitude()) - bbox.add(position.altitude()); - return bbox.get(); - } - - private static void addValues( - ImmutableSortedSet.Builder xset, - ImmutableSortedSet.Builder yset, - ImmutableSortedSet.Builder zset, - Iterable positions) { - for (Position position : positions) { - xset.add(position.northing()); - yset.add(position.easting()); - if (position.hasAltitude()) - zset.add(position.altitude()); - } - } - - private static void addValuesLineString( - ImmutableSortedSet.Builder xset, - ImmutableSortedSet.Builder yset, - ImmutableSortedSet.Builder zset, - Iterable lines) { - for (LineString ls : lines) { - addValues(xset,yset,zset,ls); - } - } - - private static void addValuesPolygon( - ImmutableSortedSet.Builder xset, - ImmutableSortedSet.Builder yset, - ImmutableSortedSet.Builder zset, - Iterable polygons) { - for (Polygon poly : polygons) { - addValuesLineString(xset,yset,zset,poly); - } - } - - protected static BoundingBox calculateBoundingBox(Geometry geometry) { - return calculateBoundingBoxGeometries( - ImmutableList.>of(geometry)); - } - - @SuppressWarnings("unchecked") - protected static BoundingBox calculateBoundingBoxGeometries( - Iterable> geometries) { - ImmutableSortedSet.Builder xset = - ImmutableSortedSet.naturalOrder(); - ImmutableSortedSet.Builder yset = - ImmutableSortedSet.naturalOrder(); - ImmutableSortedSet.Builder zset = - ImmutableSortedSet.naturalOrder(); - for (Geometry geo : geometries) { - switch(geo.type()) { - case POINT: - Point point = (Point) geo; - Position position = Iterables.getFirst(point.coordinates(),null); - xset.add(position.northing()); - yset.add(position.easting()); - if (position.hasAltitude()) - zset.add(position.altitude()); - break; - case LINESTRING: - case MULTIPOINT: - addValues(xset,yset,zset,(Iterable)geo); - break; - case MULTILINESTRING: - case POLYGON: - addValuesLineString(xset,yset,zset,(Iterable)geo); - break; - case MULTIPOLYGON: - addValuesPolygon(xset,yset,zset,(Iterable)geo); - break; - default: - break; - } - } - return buildBoundingBox( - xset.build(), - yset.build(), - zset.build()); - } - - protected static BoundingBox calculateBoundingBoxFeatures(Iterable features) { - ImmutableList.Builder> list = - ImmutableList.builder(); - for (Feature feature : features) { - Geometry geometry = feature.geometry(); - if (geometry != null) - list.add(geometry); - } - return calculateBoundingBoxGeometries(list.build()); - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm implements Serializable { - private static final long serialVersionUID = -2060301713159936285L; - private ImmutableList bounds; - protected SerializedForm(BoundingBox obj) { - this.bounds = obj.bounds; - } - Object readResolve() throws ObjectStreamException { - BoundingBox.Builder builder = - new BoundingBox.Builder(); - builder.bounds.addAll(bounds); - return builder.get(); - } - } -} diff --git a/geo/src/main/java/com/ibm/common/geojson/CRS.java b/geo/src/main/java/com/ibm/common/geojson/CRS.java deleted file mode 100644 index c71d9a4..0000000 --- a/geo/src/main/java/com/ibm/common/geojson/CRS.java +++ /dev/null @@ -1,148 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.geojson; - -import java.io.ObjectStreamException; -import java.io.Serializable; -import java.util.Iterator; -import java.util.Map; - -import com.google.common.base.Objects; -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableMap; - -/** - * A GeoJSON Coordinate Reference System description - * see http://geojson.org/geojson-spec.html#coordinate-reference-system-objects - * @author james - */ -public final class CRS - implements Iterable, Serializable { - - public static final class Builder implements Supplier { - - private String type; - private ImmutableMap.Builder properties = - ImmutableMap.builder(); - - public Builder type(String type) { - this.type = type; - return this; - } - - public Builder set(String name, Object value) { - this.properties.put(name,value); - return this; - } - - public Builder set(Map properties) { - this.properties.putAll(properties); - return this; - } - - public CRS get() { - return new CRS(this); - } - - } - - private final String type; - private final Map properties; - - CRS(Builder builder) { - this.type = builder.type; - this.properties = builder.properties.build(); - } - - public String toString() { - return Objects.toStringHelper(CRS.class) - .addValue(type) - .addValue(properties) - .toString(); - } - - public int size() { - return properties.size(); - } - - public String type() { - return type; - } - - public Map properties() { - return properties; - } - - @SuppressWarnings("unchecked") - public T get(String name) { - return (T)properties.get(name); - } - - public T get(String name, T defaultValue) { - T t = this.get(name); - return t != null ? t : defaultValue; - } - - public boolean has(String name) { - return properties.containsKey(name); - } - - @Override - public Iterator iterator() { - return properties.keySet().iterator(); - } - - public static final CRS named(String name) { - return new CRS.Builder() - .type("name") - .set("name",name) - .get(); - } - - public static final CRS linked(String href, String type) { - return new CRS.Builder() - .type("link") - .set("href", href) - .set("type", type) - .get(); - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm implements Serializable { - private static final long serialVersionUID = -2060301713159936285L; - private String type; - private Map properties; - protected SerializedForm(CRS obj) { - this.type = obj.type; - this.properties = obj.properties; - } - Object readResolve() throws ObjectStreamException { - CRS.Builder builder = new CRS.Builder(); - builder.type(type); - builder.properties.putAll(properties); - return builder.get(); - } - } -} diff --git a/geo/src/main/java/com/ibm/common/geojson/Feature.java b/geo/src/main/java/com/ibm/common/geojson/Feature.java deleted file mode 100644 index bbef2c9..0000000 --- a/geo/src/main/java/com/ibm/common/geojson/Feature.java +++ /dev/null @@ -1,159 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.geojson; - -import static com.ibm.common.geojson.BoundingBox.calculateBoundingBox; - -import java.io.ObjectStreamException; -import java.util.Iterator; -import java.util.Map; - -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableMap; - -/** - * A GeoJSON Feature Object - * see http://geojson.org/geojson-spec.html#feature-objects - * @author james - */ -public final class Feature - extends GeoObject - implements Iterable { - - public static final class Builder - extends GeoObject.Builder { - - private final ImmutableMap.Builder properties = - ImmutableMap.builder(); - - public Builder() { - type(GeoObject.Type.FEATURE); - } - - public Builder geometry(Geometry geometry) { - return set("geometry", geometry); - } - - public Builder geometry(Supplier> geometry) { - return geometry(geometry.get()); - } - - public Builder property(String name, Object value) { - this.properties.put(name, value); - return this; - } - - protected Builder properties(Map properties) { - properties.putAll(properties); - return this; - } - - public Builder id(String id) { - return set("id", id); - } - - @Override - public Feature doGet() { - set("properties", properties.build()); - return new Feature(this); - } - - } - - Feature(Builder builder) { - super(builder); - } - - public >G geometry() { - return this.get("geometry"); - } - - public Map properties() { - return this.>get( - "properties", - ImmutableMap.of()); - } - - public String id() { - return this.get("id"); - } - - @SuppressWarnings("unchecked") - public T getProperty(String name) { - return (T) properties().get(name); - } - - public T getProperty(String name, T defaultValue) { - T t = this.getProperty(name); - return t != null ? t : defaultValue; - } - - public boolean has(String name) { - return properties().containsKey(name); - } - - @Override - public Iterator iterator() { - return properties().keySet().iterator(); - } - - @Override - protected Feature makeWithBoundingBox() { - return new Feature.Builder() - .from(this) - .properties(this.properties()) - .boundingBox( - calculateBoundingBox(geometry())).get(); - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936281L; - protected SerializedForm(Feature obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return doReadResolve(); - } - @SuppressWarnings("unchecked") - @Override - protected boolean handle( - Builder builder, - String key, - Object val) { - if ("properties".equals(key)) { - Map props = (Map) val; - builder.properties.putAll(props); - return true; - } - return false; - } - @Override - protected Builder builder() { - return new Feature.Builder(); - } - } -} diff --git a/geo/src/main/java/com/ibm/common/geojson/FeatureCollection.java b/geo/src/main/java/com/ibm/common/geojson/FeatureCollection.java deleted file mode 100644 index 6a28b15..0000000 --- a/geo/src/main/java/com/ibm/common/geojson/FeatureCollection.java +++ /dev/null @@ -1,130 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.geojson; - -import static com.ibm.common.geojson.BoundingBox.calculateBoundingBoxFeatures; - -import java.io.ObjectStreamException; -import java.util.Iterator; - -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; - -/** - * A GeoJSON FeatureCollection object - * see http://geojson.org/geojson-spec.html#feature-collection-objects - * @author james - * - */ -public final class FeatureCollection - extends GeoObject - implements Iterable { - - public static final class Builder - extends GeoObject.Builder { - - private final ImmutableList.Builder list = - ImmutableList.builder(); - - public Builder() { - type(GeoObject.Type.FEATURECOLLECTION); - } - - public Builder add(Iterable features) { - list.addAll(features); - return this; - } - - public Builder add(Feature feature, Feature... features) { - list.add(feature); - if (features != null) - list.add(features); - return this; - } - - public Builder add(Supplier feature) { - return add(feature.get()); - } - - @Override - public void preGet() { - set("features", list.build()); - } - - @Override - public FeatureCollection doGet() { - return new FeatureCollection(this); - } - - } - - FeatureCollection(Builder builder) { - super(builder); - } - - public Iterable features() { - return this.>get( - "features", - ImmutableList.of()); - } - - public int size() { - return Iterables.size(features()); - } - - public Feature get(int idx) { - return Iterables.get(features(),idx); - } - - public Iterator iterator() { - return features().iterator(); - } - - @Override - protected FeatureCollection makeWithBoundingBox() { - return new FeatureCollection.Builder() - .from(this) - .add(this) - .boundingBox(calculateBoundingBoxFeatures(this)) - .get(); - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936281L; - protected SerializedForm(FeatureCollection obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return doReadResolve(); - } - @Override - protected FeatureCollection.Builder builder() { - return GeoMakers.featureCollection(); - } - } -} diff --git a/geo/src/main/java/com/ibm/common/geojson/GeoMakers.java b/geo/src/main/java/com/ibm/common/geojson/GeoMakers.java deleted file mode 100644 index efd7683..0000000 --- a/geo/src/main/java/com/ibm/common/geojson/GeoMakers.java +++ /dev/null @@ -1,135 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.geojson; - -/** - * Makers for the various GeoJSON object types - * @author james - * - */ -@SuppressWarnings("deprecation") -public final class GeoMakers { - - private GeoMakers() {} - - public static Place.Builder place() { - return new Place.Builder(); - } - - /** @deprecated **/ - public static AS1Position.Builder as1Position() { - return new AS1Position.Builder(); - } - - /** @deprecated **/ - public static AS1Position as1Position( - float latitude, - float longitude, - float altitude) { - return as1Position() - .longitude(longitude) - .latitude(latitude) - .altitude(altitude) - .get(); - } - - /** @deprecated **/ - public static AS1Position as1Position( - Position position) { - return as1Position( - position.northing(), - position.easting(), - position.altitude()); - } - - public static Position position( - AS1Position position) { - return position( - position.latitude(), - position.longitude(), - position.altitude()); - } - - public static Address.Builder address() { - return new Address.Builder(); - } - - public static Position position(float x, float y) { - return GeoObject.position(x,y); - } - - public static Position position(float x, float y, float z) { - return GeoObject.position(x, y, z); - } - - public static Point point(float x, float y) { - return point().position(x,y).get(); - } - - public static Point point(float x, float y, float z) { - return point().position(x, y, z).get(); - } - - public static Point point(Position position) { - return point().position(position).get(); - } - - public static Point.Builder point() { - return new Point.Builder(); - } - - public static MultiPoint.Builder multipoint() { - return new MultiPoint.Builder(); - } - - public static LineString.Builder linestring() { - return new LineString.Builder(); - } - - public static LineString.Builder linearRing() { - return linestring().linearRing(); - } - - public static Feature.Builder feature() { - return new Feature.Builder(); - } - - public static FeatureCollection.Builder featureCollection() { - return new FeatureCollection.Builder(); - } - - public static GeometryCollection.Builder geometryCollection() { - return new GeometryCollection.Builder(); - } - - public static MultiLineString.Builder multiLineString() { - return new MultiLineString.Builder(); - } - - public static MultiPolygon.Builder multiPolygon() { - return new MultiPolygon.Builder(); - } - - public static Polygon.Builder polygon() { - return new Polygon.Builder(); - } -} diff --git a/geo/src/main/java/com/ibm/common/geojson/GeoObject.java b/geo/src/main/java/com/ibm/common/geojson/GeoObject.java deleted file mode 100644 index 65fc410..0000000 --- a/geo/src/main/java/com/ibm/common/geojson/GeoObject.java +++ /dev/null @@ -1,250 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.geojson; - -import java.io.Serializable; -import java.util.Map; - -import com.google.common.base.Objects; -import com.google.common.base.Supplier; - -import static com.google.common.collect.ImmutableMap.copyOf; -import static com.google.common.collect.Maps.newLinkedHashMap; - -/** - * The base class for all GeoJSON objects. The type of object is identified - * by the type() property. - * @author james - * - * @param - */ -@SuppressWarnings("unchecked") -public abstract class GeoObject> - implements Serializable { - - private static final long serialVersionUID = 8852811044366213922L; - - public static enum Type { - POINT, - MULTIPOINT, - LINESTRING, - MULTILINESTRING, - POLYGON, - MULTIPOLYGON, - GEOMETRYCOLLECTION, - FEATURE, - FEATURECOLLECTION - } - - public static abstract class Builder - , B extends Builder> - implements Supplier { - - protected boolean withBoundingBox = false; - protected Type type; - protected Map data = - newLinkedHashMap(); - - /** - * Auto-calculate the bounding box when the object is created - * @return Builder - */ - public B calculateBoundingBox() { - this.withBoundingBox = true; - return (B)this; - } - - /** - * Use the given object as a template when creating this one - * @param geo GeObject<?> - * @return Builder - */ - protected B from(GeoObject geo) { - data.putAll(geo.data); - return (B)this; - } - - /** - * Set the object type - * @param type Type - * @return Builder - */ - public B type(Type type) { - this.type = type; - return (B)this; - } - - /** - * Set the CRS - * @param crs CRS - * @return Builder - */ - public B crs(CRS crs) { - return set("crs", crs); - } - - /** - * Set the bounding box explicitly - * @param bbox BoundingBox - * @return Builder - * @see GeoObject.Builder.calculateBoundingBox() - */ - public B boundingBox(BoundingBox bbox) { - return set("bbox", bbox); - } - - /** - * Set an additional property on this object - * @param name String - * @param val Object - * @return Builder - */ - public B set(String name, Object val) { - if (val != null) - this.data.put(name,val); - else if (this.data.containsKey(name)) - this.data.remove(name); - return (B)this; - } - - /** - * Get the built object - */ - public final G get() { - preGet(); - G g = doGet(); - return withBoundingBox ? g.withBoundingBox() : g; - } - - protected void preGet() {} - - protected abstract G doGet(); - } - - final Type type; - final Map data; - - protected GeoObject(Builder builder) { - this.type = builder.type; - this.data = copyOf(builder.data); - } - - /** - * Return the type of object - * @return Type - */ - public Type type() { - return type; - } - - public T get(String name) { - return (T)data.get(name); - } - - public T get(String name, T defaultValue) { - T val = get(name); - return val != null ? val : defaultValue; - } - - public boolean has(String name) { - return data.containsKey(name); - } - - /** - * Return the CRS for this object - * @return CRS - */ - public CRS crs() { - return this.get("crs", null); - } - - /** - * Return the bounding box for this object - * @return BoundingBox - */ - public BoundingBox boundingBox() { - return this.get("bbox", null); - } - - /** - * Return a copy of this object with a calculated bounding box - * @return G (a copy of this object) - */ - public final G withBoundingBox() { - return has("bbox") ? - (G)this : makeWithBoundingBox(); - } - - protected abstract G makeWithBoundingBox(); - - public static final Position position(float x, float y) { - return new Position.Builder() - .northing(x) - .easting(y) - .get(); - } - - public static final Position position(float x, float y, float z) { - return new Position.Builder() - .northing(x) - .easting(y) - .altitude(z) - .get(); - } - - public String toString() { - return Objects.toStringHelper(GeoObject.class) - .add("type", type) - .add("data", data) - .toString(); - } - - protected static abstract class AbstractSerializedForm - , B extends GeoObject.Builder> - implements Serializable { - private static final long serialVersionUID = -1950126276150975248L; - private Type type; - private Map data; - AbstractSerializedForm(G obj) { - this.type = obj.type(); - this.data = obj.data; - } - protected Object doReadResolve() { - B builder = builder(); - builder.type(type); - for (Map.Entry entry : data.entrySet()) { - String key = entry.getKey(); - Object val = entry.getValue(); - if (!handle(builder, key,val)) - builder.data.put(key,val); - } - return builder.get(); - } - protected boolean handle( - B builder, - String key, - Object val) { - return false; - } - protected abstract B builder(); - } -} diff --git a/geo/src/main/java/com/ibm/common/geojson/Geometry.java b/geo/src/main/java/com/ibm/common/geojson/Geometry.java deleted file mode 100644 index 8daa700..0000000 --- a/geo/src/main/java/com/ibm/common/geojson/Geometry.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.geojson; - -import com.google.common.collect.ImmutableList; - -public abstract class Geometry, M> - extends GeoObject - implements Iterable { - - private static final long serialVersionUID = -6184360762496309625L; - - protected Geometry(Builder builder) { - super(builder); - } - - public static abstract class CoordinateGeometry, M,P> - extends Geometry { - - private static final long serialVersionUID = -6502745908455054826L; - - protected static abstract class Builder - , B extends Builder> - extends GeoObject.Builder { - - protected abstract P coordinates(); - - public void preGet() { - set("coordinates", coordinates()); - } - - protected abstract C doGet(); - } - - protected CoordinateGeometry(Builder builder) { - super(builder); - } - - @SuppressWarnings("unchecked") - public Iterable coordinates() { - Object o = get("coordinates"); - if (o instanceof Iterable) - return (Iterable)o; - else - return ImmutableList.of((M)o); - } - - } - -} diff --git a/geo/src/main/java/com/ibm/common/geojson/GeometryCollection.java b/geo/src/main/java/com/ibm/common/geojson/GeometryCollection.java deleted file mode 100644 index 57e11d8..0000000 --- a/geo/src/main/java/com/ibm/common/geojson/GeometryCollection.java +++ /dev/null @@ -1,134 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.geojson; - -import static com.ibm.common.geojson.BoundingBox.calculateBoundingBoxGeometries; - -import java.io.ObjectStreamException; -import java.util.Iterator; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Iterables; - -/** - * A GeoJSON GeometryCollection object - * see http://geojson.org/geojson-spec.html#geometry-collection - * @author james - * - */ -public final class GeometryCollection - extends Geometry> { - - public static final class Builder - extends GeoObject.Builder { - - private final ImmutableList.Builder> list = - ImmutableList.builder(); - - public Builder() { - type(GeoObject.Type.GEOMETRYCOLLECTION); - } - - public Builder add(Geometry geometry, Geometry... geometries) { - list.add(geometry); - if (geometries != null) - list.add(geometries); - return this; - } - - public Builder add(Iterable> geometries) { - list.addAll(geometries); - return this; - } - - @Override - public void preGet() { - set("geometries", list.build()); - } - - @Override - public GeometryCollection doGet() { - return new GeometryCollection(this); - } - } - - GeometryCollection(Builder builder) { - super(builder); - } - - public Iterable> geometries() { - return this.>>get( - "geometries", - ImmutableList.>of()); - } - - public int size() { - return Iterables.size(geometries()); - } - - @SuppressWarnings("unchecked") - public >G get(int idx) { - return (G)Iterables.get(geometries(),idx); - } - - public Iterator> iterator() { - return geometries().iterator(); - } - - @Override - public GeometryCollection makeWithBoundingBox() { - return new GeometryCollection.Builder() - .from(this) - .add(this) - .boundingBox(calculateBoundingBoxGeometries(this)) - .get(); - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936281L; - protected SerializedForm(GeometryCollection obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return doReadResolve(); - } - @SuppressWarnings("unchecked") - @Override - protected boolean handle(Builder builder, String key, Object val) { - if ("geometries".equals(key)) { - Iterable> list = (Iterable>) val; - builder.list.addAll(list); - return true; - } - return false; - } - @Override - protected GeometryCollection.Builder builder() { - return GeoMakers.geometryCollection(); - } - } -} diff --git a/geo/src/main/java/com/ibm/common/geojson/LineString.java b/geo/src/main/java/com/ibm/common/geojson/LineString.java deleted file mode 100644 index 8f4c79f..0000000 --- a/geo/src/main/java/com/ibm/common/geojson/LineString.java +++ /dev/null @@ -1,252 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.geojson; - -import static com.ibm.common.geojson.BoundingBox.calculateBoundingBoxPositions; -import static com.google.common.base.Preconditions.checkArgument; -import static com.google.common.collect.Iterables.concat; -import static com.google.common.collect.Iterables.getFirst; -import static com.google.common.collect.Iterables.size; -import static java.lang.String.format; - -import java.io.ObjectStreamException; -import java.util.Iterator; - -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableList; -import com.ibm.common.geojson.Geometry.CoordinateGeometry; - -/** - * A GeoJSON LineString object - * See http://geojson.org/geojson-spec.html#linestring. - * - * The LineString can optionally be a Linear Ring if there are at least four - * positions and the first and last position are equivalent. - * - *
- *   LineString regularLineString = 
- *     GeoMakers.linestring()
- *       .add(1,2)
- *       .add(2,3)
- *       .get();
- *   // includes points (1,2) and (2,3)
- *       
- *   LineString linearRing = 
- *     GeoMakers.linestring()
- *       .linearRing()
- *       .add(1,2)
- *       .add(2,3)
- *       .add(3,4)
- *       .get()
- *   // includes points (1,2), (2,3), (3,4) and (1,2)
- * 
- * - * @author james - * - */ -public final class LineString - extends CoordinateGeometry> { - - public static final class Builder - extends CoordinateGeometry.Builder,LineString, Builder> { - - private final ImmutableList.Builder positions = - ImmutableList.builder(); - private boolean ring; - private final boolean nocheck; - - public Builder() { - nocheck = false; - type(Type.LINESTRING); - } - - private Builder(boolean nocheck) { - this.nocheck = nocheck; - type(Type.LINESTRING); - } - - /** - * Specify that this LineString is a linearring - * @return Builder - */ - public Builder linearRing() { - return linearRing(true); - } - - public Builder linearRing(boolean on) { - this.ring = on; - return this; - } - - /** - * Add one or more positions to this linestring - * @param position Position - * @param positions Position[] optional vararg - * @return Builder - */ - public Builder add(Position position, Position... positions) { - this.positions.add(position); - if (positions != null) - for (Position pos : positions) - add(pos); - return this; - } - - /** - * Add a single position to this linestring - * @param x float - * @param y float - * @return Builder - */ - public Builder add(float x, float y) { - return add(GeoObject.position(x, y)); - } - - /** - * Add a single position to this linestring - * @param position Supplier<Position> - * @return Builder - */ - public Builder add(Supplier position) { - return add(position.get()); - } - - /** - * Add one or more positions to this linestring - * @param positions Iterable<Position> - * @return Builder - */ - public Builder add(Iterable positions) { - this.positions.addAll(positions); - return this; - } - - /** - * Add a single position to this linestring - * @param x float - * @param y float - * @param z float - * @return Builder - */ - public Builder add(float x, float y, float z) { - return add(GeoObject.position(x,y,z)); - } - - public LineString doGet() { - return new LineString(this); - } - - @Override - protected Iterable coordinates() { - return positions.build(); - } - - } - - private final boolean ring; - - protected LineString( - Builder builder) { - super(builder); - this.ring = builder.ring; - int min = ring?3:2; - checkArgument( - builder.nocheck || - size(coordinates()) >= min, - format( - "A LineString that %s a LinearRing MUST consist of at least %d positions", - ring?"is":"is not", - min)); - } - - public boolean linearRing() { - return ring; - } - - @Override - /** - * Get this LineStrings positions - * @return Iterable<Position> - */ - public Iterable coordinates() { - Iterable pos = super.coordinates(); - if (!ring) - return pos; - else { - return size(pos) > 0 ? - concat(pos,ImmutableList.of(getFirst(pos,null))) : - ImmutableList.of(); - } - } - - @Override - public Iterator iterator() { - return coordinates().iterator(); - } - - /** - * Return a copy of this linestring with a calculated bounding box - */ - @Override - public LineString makeWithBoundingBox() { - return new LineString.Builder() - .from(this) - .add(this) - .boundingBox(calculateBoundingBoxPositions(this)) - .get(); - } - - // Java Serialization support - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936281L; - boolean ring; - protected SerializedForm(LineString obj) { - super(obj); - this.ring = obj.ring; - } - Object readResolve() throws ObjectStreamException { - return doReadResolve(); - } - @SuppressWarnings("unchecked") - @Override - protected boolean handle(Builder builder, String key, Object val) { - if ("coordinates".equals(key)) { - Iterable list = (Iterable) val; - builder.positions.addAll(list); - return true; - } - return false; - } - @Override - protected LineString.Builder builder() { - Builder builder = new Builder(true); - builder.ring = ring; - return builder; - } - } -} diff --git a/geo/src/main/java/com/ibm/common/geojson/MultiLineString.java b/geo/src/main/java/com/ibm/common/geojson/MultiLineString.java deleted file mode 100644 index 14df947..0000000 --- a/geo/src/main/java/com/ibm/common/geojson/MultiLineString.java +++ /dev/null @@ -1,150 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.geojson; - -import static com.ibm.common.geojson.BoundingBox.calculateBoundingBoxLineStrings; - -import java.io.ObjectStreamException; -import java.util.Iterator; - -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableList; -import com.ibm.common.geojson.Geometry.CoordinateGeometry; - -/** - * A GeoJSON MultiLineString object - * see http://geojson.org/geojson-spec.html#multilinestring - * @author james - * - */ -public final class MultiLineString - extends CoordinateGeometry> { - - public static final class Builder - extends CoordinateGeometry.Builder, MultiLineString, Builder> { - - private final ImmutableList.Builder strings = - ImmutableList.builder(); - - public Builder() { - type(Type.MULTILINESTRING); - } - - /** - * Add one or more LineStrings - * @param line LineString - * @param lines LineString[] optional vararg - * @return Builder - */ - public Builder add(LineString line, LineString... lines) { - this.strings.add(line); - if (lines != null) - for (LineString l : lines) - add(l); - return this; - } - - /** - * Add a single LineString - * @param line Supplier<LineString> - * @return Builder - */ - public Builder add(Supplier line) { - return add(line.get()); - } - - /** - * Add one or more LineStrings - * @param lines Iterable<LineString> - * @return Builder - */ - public Builder add(Iterable lines) { - this.strings.addAll(lines); - return this; - } - - public MultiLineString doGet() { - return new MultiLineString(this); - } - - /** - * Get this objects collection of LineStrings - * @return Iterable<LineString> - */ - @Override - protected Iterable coordinates() { - return strings.build(); - } - - } - - protected MultiLineString( - Builder builder) { - super(builder); - } - - @Override - public Iterator iterator() { - return coordinates().iterator(); - } - - /** - * Copy this object with a calculated bounding box - * @return MultiLineString - */ - @Override - protected MultiLineString makeWithBoundingBox() { - return new MultiLineString.Builder() - .from(this) - .add(this) - .boundingBox( - calculateBoundingBoxLineStrings(this)).get(); - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936281L; - protected SerializedForm(MultiLineString obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return doReadResolve(); - } - @SuppressWarnings("unchecked") - protected boolean handle(Builder builder, String key, Object val) { - if ("coordinates".equals(key)) { - Iterable list = (Iterable) val; - builder.strings.addAll(list); - return true; - } - return false; - } - @Override - protected MultiLineString.Builder builder() { - return GeoMakers.multiLineString(); - } - } -} diff --git a/geo/src/main/java/com/ibm/common/geojson/MultiPoint.java b/geo/src/main/java/com/ibm/common/geojson/MultiPoint.java deleted file mode 100644 index b90156a..0000000 --- a/geo/src/main/java/com/ibm/common/geojson/MultiPoint.java +++ /dev/null @@ -1,167 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.geojson; - -import java.io.ObjectStreamException; -import java.util.Iterator; - -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableList; -import com.ibm.common.geojson.Geometry.CoordinateGeometry; - -import static com.ibm.common.geojson.BoundingBox.calculateBoundingBoxPositions; - -/** - * A GeoJSON MultiPoint object - * see http://geojson.org/geojson-spec.html#multipoint - * @author james - * - */ -public final class MultiPoint - extends CoordinateGeometry> { - - public static final class Builder - extends CoordinateGeometry.Builder,MultiPoint,Builder> { - - protected ImmutableList.Builder list = - ImmutableList.builder(); - - public Builder() { - type(GeoObject.Type.MULTIPOINT); - } - - /** - * Add one or more positions - * @param position Position - * @param positions Position[] optional vararg - * @return Builder - */ - public Builder add(Position position, Position... positions) { - list.add(position); - if (positions != null) - list.add(positions); - return this; - } - - /** - * Add one or more positions - * @param positions Iterable<Position> - * @return Builder - */ - public Builder add(Iterable positions) { - list.addAll(positions); - return this; - } - - /** - * Add a position - * @param pos Supplier<Position> - * @return Builder - */ - public Builder add(Supplier pos) { - return add(pos.get()); - } - - /** - * Add a position - * @param x float - * @param y float - * @return Builder - */ - public Builder add(float x, float y) { - return add(GeoObject.position(x, y)); - } - - /** - * Add a position - * @param x float - * @param y float - * @param z float - * @return Builder - */ - public Builder add(float x, float y, float z) { - return add(GeoObject.position(x,y,z)); - } - - @Override - protected Iterable coordinates() { - return list.build(); - } - - @Override - public MultiPoint doGet() { - return new MultiPoint(this); - } - - } - - protected MultiPoint( - Builder builder) { - super(builder); - } - - @Override - public Iterator iterator() { - return coordinates().iterator(); - } - - /** - * Return a copy of this object with a calculated bounding box - * @return MultiPoint - */ - @Override - protected MultiPoint makeWithBoundingBox() { - return new MultiPoint.Builder() - .from(this) - .add(this) - .boundingBox(calculateBoundingBoxPositions(this)).get(); - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936281L; - protected SerializedForm(MultiPoint obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return doReadResolve(); - } - @SuppressWarnings("unchecked") - @Override - protected boolean handle(Builder builder, String key, Object val) { - if ("coordinates".equals(key)) { - Iterable list = (Iterable) val; - builder.list.addAll(list); - return true; - } - return false; - } - @Override - protected MultiPoint.Builder builder() { - return GeoMakers.multipoint(); - } - } -} diff --git a/geo/src/main/java/com/ibm/common/geojson/MultiPolygon.java b/geo/src/main/java/com/ibm/common/geojson/MultiPolygon.java deleted file mode 100644 index 0727c93..0000000 --- a/geo/src/main/java/com/ibm/common/geojson/MultiPolygon.java +++ /dev/null @@ -1,148 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.geojson; - -import static com.ibm.common.geojson.BoundingBox.calculateBoundingBoxPolygons; - -import java.io.ObjectStreamException; -import java.util.Iterator; - -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableList; -import com.ibm.common.geojson.Geometry.CoordinateGeometry; - -/** - * A GeoJSON MultiPolygon object. - * see http://geojson.org/geojson-spec.html#multipolygon - * @author james - * - */ -public final class MultiPolygon - extends CoordinateGeometry>{ - - public static final class Builder - extends CoordinateGeometry.Builder, MultiPolygon, Builder> { - - private final ImmutableList.Builder strings = - ImmutableList.builder(); - - public Builder() { - type(Type.MULTIPOLYGON); - } - - /** - * Add one or more Polygons - * @param poly Polygon - * @param polys Polygon[] optional vararg - * @return Builder - */ - public Builder add(Polygon poly, Polygon... polys) { - // TODO: Check hole requirement - this.strings.add(poly); - if (polys != null) - for (Polygon l : polys) - add(l); - return this; - } - - /** - * Add a Polygon - * @param poly Supplier<Polygon> - * @return Builder - */ - public Builder add(Supplier poly) { - return add(poly.get()); - } - - /** - * Add one ore more Polygons - * @param polygons Iterable<Polygon> - * @return Builder - */ - public Builder add(Iterable polygons) { - this.strings.addAll(polygons); - return this; - } - - public MultiPolygon doGet() { - return new MultiPolygon(this); - } - - @Override - protected Iterable coordinates() { - return strings.build(); - } - - } - - protected MultiPolygon( - Builder builder) { - super(builder); - } - - @Override - public Iterator iterator() { - return coordinates().iterator(); - } - - /** - * Return a copy of this object with a calculated bounding box - * @return MultiPolygon - */ - @Override - protected MultiPolygon makeWithBoundingBox() { - return new MultiPolygon.Builder() - .from(this) - .add(this) - .boundingBox(calculateBoundingBoxPolygons(this)) - .get(); - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936281L; - protected SerializedForm(MultiPolygon obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return doReadResolve(); - } - @SuppressWarnings("unchecked") - @Override - protected boolean handle(Builder builder, String key, Object val) { - if ("coordinates".equals(key)) { - Iterable list = (Iterable) val; - builder.strings.addAll(list); - return true; - } - return false; - } - @Override - protected MultiPolygon.Builder builder() { - return GeoMakers.multiPolygon(); - } - } -} diff --git a/geo/src/main/java/com/ibm/common/geojson/Place.java b/geo/src/main/java/com/ibm/common/geojson/Place.java deleted file mode 100644 index e61e461..0000000 --- a/geo/src/main/java/com/ibm/common/geojson/Place.java +++ /dev/null @@ -1,171 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.geojson; - -import java.io.ObjectStreamException; - -import com.google.common.base.Supplier; -import com.ibm.common.activitystreams.ASObject; - -/** - * A legacy Activity Streams 1.0 Place object - * see https://github.com/activitystreams/activity-schema/blob/master/activity-schema.md. - * - * Place objects have additional address, position and geo properties that - * describe the location. - * @author james - * - */ -public final class Place extends ASObject { - - public static final class Builder - extends ASObject.AbstractBuilder { - - Builder() { - objectType("place"); - } - - /** - * Set the address - * @param address Address - * @return Builder - */ - public Builder address(Address address) { - return set("address", address); - } - - /** - * Set the address - * @param address Supplier<Address> - * @return Builder - */ - public Builder address(Supplier
address) { - return address(address.get()); - } - - /** - * Set the position - * @deprecated - * @param position AS1Position - * @return Builder - */ - public Builder position(AS1Position position) { - return set("position", position); - } - - /** - * Set the position - * @deprecated - * @param position Supplier<AS1Position> - * @return Builder - */ - public Builder position(Supplier position) { - return position(position.get()); - } - - /** - * Set the position - * @param latitude float - * @param longitude float - * @param altitude float - * @return Builder - * @deprecated - */ - public Builder position( - float latitude, - float longitude, - float altitude) { - return position(GeoMakers.as1Position(latitude, longitude, altitude)); - } - - /** - * Set the geo property - * @param geo GeoObject<?> Any GeoJSON object can be used - * @return Builder - */ - public Builder geo(GeoObject geo) { - return set("geo", geo); - } - - /** - * Set the geo property - * @param geo Supplier<? extends GeoObject<?>> Any GeoJSON object can be used - * @return Builder - */ - public Builder geo(Supplier> geo) { - return geo(geo.get()); - } - - @Override - public Place get() { - return new Place(this); - } - - } - - private Place(Builder builder) { - super(builder); - } - - /** - * Get the address - * @return Address - */ - public Address address() { - return this.
get("address"); - } - - /** - * Get the position - * @deprecated - * @return AS1Position - */ - public AS1Position position() { - return this.get("position"); - } - - /** - * Get the geo property - * @return <G extends GeoObject<?>>G - */ - public >G geo() { - return this.get("geo"); - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936285L; - protected SerializedForm(Place obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return super.doReadResolve(); - } - protected Place.Builder builder() { - return GeoMakers.place(); - } - } -} diff --git a/geo/src/main/java/com/ibm/common/geojson/Point.java b/geo/src/main/java/com/ibm/common/geojson/Point.java deleted file mode 100644 index 2ff83b0..0000000 --- a/geo/src/main/java/com/ibm/common/geojson/Point.java +++ /dev/null @@ -1,155 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.geojson; - -import java.io.ObjectStreamException; -import java.util.Iterator; - -import com.google.common.base.Supplier; - -import static com.google.common.collect.Iterables.getFirst; -import static com.ibm.common.geojson.BoundingBox.calculateBoundingBox; - -import com.ibm.common.geojson.Geometry.CoordinateGeometry; - -/** - * A GeoJSON Point object - * see http://geojson.org/geojson-spec.html#point. - * - * A Point object represents a single Position - * - * @author james - * - */ -public final class Point - extends CoordinateGeometry { - - public static final class Builder - extends CoordinateGeometry.Builder { - - protected Position position; - - public Builder() { - type(GeoObject.Type.POINT); - } - - /** - * Set the position - * @param northing float - * @param easting float - * @param altitude float - * @return Builder - */ - public Builder position(float northing, float easting, float altitude) { - this.position = GeoObject.position(northing, easting, altitude); - return this; - } - - /** - * Set the position - * @param northing float - * @param easting float - * @return Builder - */ - public Builder position(float northing, float easting) { - this.position = GeoObject.position(northing,easting); - return this; - } - - /** - * Set the position - * @param position Position - * @return Builder - */ - public Builder position(Position position) { - this.position = position; - return this; - } - - /** - * Set the position - * @param position Supplier<Position> - * @return Builder - */ - public Builder position(Supplier position) { - return position(position.get()); - } - - @Override - protected Position coordinates() { - return position; - } - - @Override - public Point doGet() { - return new Point(this); - } - - } - - Point(Builder builder) { - super(builder); - } - - @Override - public Iterator iterator() { - return coordinates().iterator(); - } - - - @Override - protected Point makeWithBoundingBox() { - Position pos = getFirst(coordinates(),null); - return new Point.Builder() - .from(this) - .position(pos) - .boundingBox(calculateBoundingBox(pos)) - .get(); - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936281L; - protected SerializedForm(Point obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return doReadResolve(); - } - @Override - protected boolean handle(Builder builder, String key, Object val) { - if ("coordinates".equals(key)) { - builder.position = (Position) val; - return true; - } - return false; - } - @Override - protected Point.Builder builder() { - return GeoMakers.point(); - } - } -} diff --git a/geo/src/main/java/com/ibm/common/geojson/Polygon.java b/geo/src/main/java/com/ibm/common/geojson/Polygon.java deleted file mode 100644 index e447f2b..0000000 --- a/geo/src/main/java/com/ibm/common/geojson/Polygon.java +++ /dev/null @@ -1,146 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.geojson; - -import static com.google.common.base.Preconditions.checkArgument; -import static com.ibm.common.geojson.BoundingBox.calculateBoundingBoxLineStrings; - -import java.io.ObjectStreamException; -import java.util.Iterator; - -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableList; -import com.ibm.common.geojson.Geometry.CoordinateGeometry; - -/** - * A GeoJSON Polygon object - * see http://geojson.org/geojson-spec.html#polygon - * @author james - * - */ -public final class Polygon - extends CoordinateGeometry> { - - public static final class Builder - extends CoordinateGeometry.Builder, Polygon, Builder> { - - private final ImmutableList.Builder strings = - ImmutableList.builder(); - - public Builder() { - type(Type.POLYGON); - } - - /** - * Add one or more LineStrings - * @param line LineString - * @param lines LineString[] optional vararg - * @return Builder - */ - public Builder add(LineString line, LineString... lines) { - checkArgument(line.linearRing(), "Polygon coordinates MUST be Linear Rings"); - // TODO: Check hole requirement - this.strings.add(line); - if (lines != null) - for (LineString l : lines) - add(l); - return this; - } - - /** - * Add a LineString - * @param line Supplier<LineString> - * @return Builder - */ - public Builder add(Supplier line) { - return add(line.get()); - } - - /** - * Add one or more LineStrings - * @param lines Iterable<LineString> - * @return Builder - */ - public Builder add(Iterable lines) { - this.strings.addAll(lines); - return this; - } - - public Polygon doGet() { - return new Polygon(this); - } - - @Override - protected Iterable coordinates() { - return strings.build(); - } - - } - - protected Polygon( - Builder builder) { - super(builder); - } - - @Override - public Iterator iterator() { - return coordinates().iterator(); - } - - @Override - protected Polygon makeWithBoundingBox() { - return new Polygon.Builder() - .from(this) - .add(this) - .boundingBox( - calculateBoundingBoxLineStrings(this)).get(); - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936281L; - protected SerializedForm(Polygon obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return doReadResolve(); - } - @SuppressWarnings("unchecked") - @Override - protected boolean handle(Builder builder, String key, Object val) { - if ("coordinates".equals(key)) { - Iterable list = (Iterable) val; - builder.strings.addAll(list); - return true; - } - return false; - } - @Override - protected Polygon.Builder builder() { - return GeoMakers.polygon(); - } - } -} diff --git a/geo/src/main/java/com/ibm/common/geojson/Position.java b/geo/src/main/java/com/ibm/common/geojson/Position.java deleted file mode 100755 index 6bc4605..0000000 --- a/geo/src/main/java/com/ibm/common/geojson/Position.java +++ /dev/null @@ -1,161 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.geojson; - -import static com.google.common.primitives.Floats.concat; -import static com.google.common.primitives.Floats.toArray; - -import java.io.ObjectStreamException; -import java.io.Serializable; -import java.util.Arrays; -import java.util.Iterator; - -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableList; -import com.google.common.primitives.Floats; - -/** - * A GeoJSON Position - * see http://geojson.org/geojson-spec.html#positions. - * - * Position objects consist primarily of three distinct values: - * a northing (latitude or x), easting (longitude or y) and altitude (z). - * - * @author james - * - */ -public final class Position - implements Iterable, Serializable { - - public static final class Builder - implements Supplier { - - private float x,y,z; - private boolean hasz = false; - private ImmutableList.Builder rest = - ImmutableList.builder(); - - public Builder northing(float x) { - this.x = x; - return this; - } - - public Builder easting(float y) { - this.y = y; - return this; - } - - public Builder altitude(float z) { - this.hasz = true; - this.z = z; - return this; - } - - public Builder additional(float m) { - this.rest.add(m); - return this; - } - - public Position get() { - return new Position(this); - } - - } - - private final float x,y,z; - private final boolean hasz; - private final float[] rest; - - Position(Builder builder) { - this.x = builder.x; - this.y = builder.y; - this.z = builder.z; - this.hasz = builder.hasz; - this.rest = toArray(builder.rest.build()); - } - - public float northing() { - return x; - } - - public float easting() { - return y; - } - - public float altitude() { - return z; - } - - public boolean hasAltitude() { - return hasz; - } - - public int size() { - return values().length; - } - - private float[] values() { - return hasz? - concat(new float[] {x,y,z}, rest) : - concat(new float[] {x,y}, rest); - } - - public String toString() { - return Arrays.toString(values()); - } - - @Override - public Iterator iterator() { - return Floats.asList(values()).iterator(); - } - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm implements Serializable { - private static final long serialVersionUID = -2060301713159936285L; - private float x,y,z; - private boolean hasz; - private float[] rest; - protected SerializedForm(Position obj) { - this.x = obj.x; - this.y = obj.y; - this.z = obj.z; - this.hasz = obj.hasz; - this.rest = obj.rest; - } - Object readResolve() throws ObjectStreamException { - Position.Builder position = - new Position.Builder() - .northing(x) - .easting(y) - .altitude(z); - position.hasz = this.hasz; - if (rest != null) - for (float f : rest) - position.additional(f); - return position.get(); - } - - } -} diff --git a/geo/src/main/java/com/ibm/common/geojson/as2/GeoAdapter.java b/geo/src/main/java/com/ibm/common/geojson/as2/GeoAdapter.java deleted file mode 100644 index 8dc3283..0000000 --- a/geo/src/main/java/com/ibm/common/geojson/as2/GeoAdapter.java +++ /dev/null @@ -1,352 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.geojson.as2; - -import static com.google.common.base.Preconditions.checkArgument; - -import java.lang.reflect.Type; -import java.util.Arrays; -import java.util.Map; - -import com.google.common.base.Enums; -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonPrimitive; -import com.google.gson.JsonSerializationContext; -import com.ibm.common.activitystreams.internal.Adapter; -import com.ibm.common.geojson.BoundingBox; -import com.ibm.common.geojson.CRS; -import com.ibm.common.geojson.Feature; -import com.ibm.common.geojson.FeatureCollection; -import com.ibm.common.geojson.GeoMakers; -import com.ibm.common.geojson.GeoObject; -import com.ibm.common.geojson.Geometry; -import com.ibm.common.geojson.Geometry.CoordinateGeometry; -import com.ibm.common.geojson.GeometryCollection; -import com.ibm.common.geojson.LineString; -import com.ibm.common.geojson.MultiLineString; -import com.ibm.common.geojson.MultiPoint; -import com.ibm.common.geojson.MultiPolygon; -import com.ibm.common.geojson.Point; -import com.ibm.common.geojson.Polygon; -import com.ibm.common.geojson.Position; - -@SuppressWarnings("rawtypes") -public class GeoAdapter - extends Adapter { - - @Override - public JsonElement serialize( - GeoObject geo, - Type type, - JsonSerializationContext context) { - - JsonObject obj = new JsonObject(); - obj.add("type", context.serialize(geo.type(),GeoObject.Type.class)); - switch(geo.type()) { - case POINT: - case MULTIPOINT: - case LINESTRING: - case MULTILINESTRING: - case MULTIPOLYGON: - case POLYGON: - CoordinateGeometry c = - (CoordinateGeometry) geo; - obj.add( - "coordinates", - context.serialize( - c.coordinates(), - Iterable.class)); - break; - case GEOMETRYCOLLECTION: - GeometryCollection gc = - (GeometryCollection)geo; - obj.add( - "geometries", - context.serialize( - gc.geometries(), - Iterable.class)); - break; - case FEATURE: - Feature feature = - (Feature) geo; - if (feature.id() != null) - obj.addProperty("id", feature.id()); - Geometry geometry = feature.geometry(); - Map properties = feature.properties(); - if (geometry != null) - obj.add( - "geometry", - context.serialize(feature.geometry())); - if (properties != null) - obj.add( - "properties", - context.serialize(properties)); - break; - case FEATURECOLLECTION: - FeatureCollection fc = - (FeatureCollection)geo; - obj.add( - "features", - context.serialize( - fc.features(), - Iterable.class)); - break; - default: - break; - - } - if (geo.boundingBox() != null) { - BoundingBox bb = geo.boundingBox(); - obj.add("bbox", context.serialize(bb, Iterable.class)); - } - if (geo.crs() != null) { - CRS crs = geo.crs(); - JsonObject crsobj = new JsonObject(); - crsobj.addProperty("name", crs.type()); - if (crs.size() > 0) - crsobj.add( - "properties", - context.serialize(crs.properties())); - obj.add("crs", crsobj); - } - return obj; - } - - private Position toPosition(float[] pos) { - Position.Builder b = - new Position.Builder(); - for (int n = 0; n < pos.length; n++) { - if (n == 0) b.northing(pos[n]); - else if (n == 1) b.easting(pos[n]); - else if (n == 2) b.altitude(pos[n]); - else b.additional(pos[n]); - } - return b.get(); - } - - @Override - public GeoObject deserialize( - JsonElement element, - Type type, - JsonDeserializationContext context) - throws JsonParseException { - GeoObject.Builder geo = null; - checkArgument(element.isJsonObject()); - JsonObject obj = element.getAsJsonObject(); - checkArgument(obj.has("type")); - GeoObject.Type et = - Enums.getIfPresent( - GeoObject.Type.class, - obj.get("type").getAsString().toUpperCase()).orNull(); - checkArgument(et != null); - switch(et) { - case FEATURE: - geo = GeoMakers.feature(); - break; - case FEATURECOLLECTION: - geo = GeoMakers.featureCollection(); - type = Feature.class; - break; - case GEOMETRYCOLLECTION: - geo = GeoMakers.geometryCollection(); - type = Geometry.class; - break; - case LINESTRING: - geo = GeoMakers.linestring(); - type = Position.class; - break; - case MULTILINESTRING: - geo = GeoMakers.multiLineString(); - type = LineString.class; - break; - case MULTIPOINT: - geo = GeoMakers.multipoint(); - type = Position.class; - break; - case MULTIPOLYGON: - geo = GeoMakers.multiPolygon(); - type = Polygon.class; - break; - case POINT: - geo = GeoMakers.point(); - type = null; - break; - case POLYGON: - geo = GeoMakers.polygon(); - type = LineString.class; - break; - } - - for (Map.Entry entry : obj.entrySet()) { - JsonElement el = entry.getValue(); - String name = entry.getKey(); - if ("crs".equals(name)) { - CRS.Builder cb = new CRS.Builder(); - JsonObject o = el.getAsJsonObject(); - if (o.has("type")) - cb.type(o.get("type").getAsString()); - if (o.has("properties")) { - JsonObject p = o.get("properties").getAsJsonObject(); - for (Map.Entry e : p.entrySet()) { - cb.set(e.getKey(), context.deserialize(e.getValue(), Object.class)); - } - } - geo.crs(cb.get()); - } else if ("properties".equals(name)) { - geo.set( - "properties", - context.deserialize( - el, - Map.class)); - } else if ("bbox".equals(name)) { - BoundingBox.Builder bb = - new BoundingBox.Builder(); - float[] points = context.deserialize(el, float[].class); - bb.add(points); - geo.boundingBox(bb.get()); - } else if ("features".equals(name)) { - Feature[] features = context.deserialize(el, Feature[].class); - FeatureCollection.Builder fcb = (FeatureCollection.Builder)geo; - for (Feature f : features) - fcb.add(f); - } else if ("coordinates".equals(name)) { - switch(et) { - case LINESTRING: { - LineString.Builder lsb = (LineString.Builder) geo; - float[][] positions = context.deserialize(el, float[][].class); - boolean ring = ring(positions); - if (ring) - lsb.linearRing(); - for (int n = 0; n < positions.length; n++) { - if (!ring || (ring && n < positions.length - 1)) - lsb.add(toPosition(positions[n])); - } - break; - } - case MULTIPOINT: { - MultiPoint.Builder lsb = (MultiPoint.Builder) geo; - float[][] positions = context.deserialize(el, float[][].class); - for (float[] pos : positions) - lsb.add(toPosition(pos)); - break; - } - case MULTILINESTRING: { - MultiLineString.Builder mlb = (MultiLineString.Builder) geo; - float[][][] positions = context.deserialize(el, float[][][].class); - for (float[][] lines : positions) { - LineString.Builder lsb = - GeoMakers.linestring(); - boolean ring = ring(lines); - if (ring) - lsb.linearRing(); - for (int n = 0; n < lines.length; n++) { - if (!ring || (ring && n < lines.length - 1)) - lsb.add(toPosition(lines[n])); - } - for (float[] pos : lines) - lsb.add(toPosition(pos)); - mlb.add(lsb); - } - break; - } - case POLYGON: { - Polygon.Builder mlb = (Polygon.Builder) geo; - float[][][] positions = context.deserialize(el, float[][][].class); - for (float[][] lines : positions) { - LineString.Builder lsb = - GeoMakers.linestring(); - for (float[] pos : lines) - lsb.add(toPosition(pos)); - mlb.add(lsb); - } - break; - } - case MULTIPOLYGON: { - MultiPolygon.Builder mpb = (MultiPolygon.Builder) geo; - float[][][][] positions = context.deserialize(el, float[][][][].class); - for (float[][][] polygons : positions) { - Polygon.Builder pb = GeoMakers.polygon(); - for (float[][] lines : polygons) { - LineString.Builder lsb = - GeoMakers.linestring(); - for (float[] pos : lines) - lsb.add(toPosition(pos)); - pb.add(lsb); - } - mpb.add(pb); - } - break; - } - case POINT: - Point.Builder pb = (Point.Builder)geo; - float[] position = context.deserialize(el, float[].class); - pb.position(toPosition(position)); - break; - default: - break; - } - } else if ("geometries".equals(name)) { - Geometry[] geos = context.deserialize(el, Geometry[].class); - GeometryCollection.Builder fcb = (GeometryCollection.Builder)geo; - for (Geometry g : geos) - fcb.add(g); - } else { - if (el.isJsonArray()) { - geo.set(name, context.deserialize(el, Object.class)); - } else if (el.isJsonObject()) { - geo.set(name, context.deserialize(el, GeoObject.class)); - } else if (el.isJsonPrimitive()) { - JsonPrimitive p = el.getAsJsonPrimitive(); - if (p.isBoolean()) - geo.set(name, p.getAsBoolean()); - else if (p.isNumber()) - geo.set(name, p.getAsNumber()); - else if (p.isString()) - geo.set(name, p.getAsString()); - } - } - } - - return geo.get(); - } - - private static boolean ring(float[][] line) { - return ring(first(line),last(line)); - } - - private static boolean ring(float[] p1, float[] p2) { - return Arrays.equals(p1,p2); - } - - private static float[] first(float[][] line) { - if (line.length == 0) return null; - return line[0]; - } - - private static float[] last(float[][] line) { - if (line.length == 0) return null; - return line[line.length - 1]; - } -} diff --git a/geo/src/main/java/com/ibm/common/geojson/as2/GeoModule.java b/geo/src/main/java/com/ibm/common/geojson/as2/GeoModule.java deleted file mode 100644 index d58ce31..0000000 --- a/geo/src/main/java/com/ibm/common/geojson/as2/GeoModule.java +++ /dev/null @@ -1,111 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.geojson.as2; - -import com.ibm.common.activitystreams.IO; -import com.ibm.common.activitystreams.internal.EnumAdapter; -import com.ibm.common.activitystreams.internal.Model; -import com.ibm.common.activitystreams.internal.Schema; -import com.ibm.common.activitystreams.internal.Schema.Builder; -import com.ibm.common.activitystreams.util.Module; -import com.ibm.common.geojson.AS1Position; -import com.ibm.common.geojson.Address; -import com.ibm.common.geojson.GeoObject; -import com.ibm.common.geojson.Place; - -/** - * Enables the use of the GeoJSON extensions with Activity Streams 2.0 - * - *
- *   import com.ibm.common.geojson.as2.GeoModule;
- *   import com.ibm.common.activitystreams.IO;
- *   
- *   //...
- *   
- *   IO io = IO.makeDefault(GeoModule.instance);
- *   
- * 
- * @author james - * - */ -@SuppressWarnings("deprecation") -public final class GeoModule - implements Module { - - public static final Module instance = - new GeoModule(); - - public static final Model place = - Schema.object.template() - .type(Place.class, Place.Builder.class) - .as("geo", GeoObject.class) - .as("address", Address.class) - .as("position", AS1Position.class) - .get(); - - public static final Model address = - Schema.object.template() - .type(Address.class, Address.Builder.class) - .string( - "country", - "formatted", - "locality", - "postalCode", - "region", - "streetAddress") - .get(); - - public static final Model as1Position = - Schema.object.template() - .type(AS1Position.class, AS1Position.Builder.class) - .floatValue( - "latitude", - "longitude", - "altitude") - .get(); - - @Override - public void apply( - Builder builder) { - builder.map("place", place) - .map("address", address) - .map("position", as1Position); - } - - @Override - public void apply( - IO.Builder builder, - Schema schema) { - final GeoObjectAdapter base = - new GeoObjectAdapter(schema); - final GeoAdapter geo = - new GeoAdapter(); - builder.hierarchicalAdapter(Place.class, base) - .hierarchicalAdapter(Address.class, base) - .hierarchicalAdapter(AS1Position.class, base) - .hierarchicalAdapter(GeoObject.class, geo) - .hierarchicalAdapter( - GeoObject.Type.class, - new EnumAdapter(GeoObject.Type.class)); - } - -} diff --git a/geo/src/main/java/com/ibm/common/geojson/as2/GeoObjectAdapter.java b/geo/src/main/java/com/ibm/common/geojson/as2/GeoObjectAdapter.java deleted file mode 100644 index 78a0094..0000000 --- a/geo/src/main/java/com/ibm/common/geojson/as2/GeoObjectAdapter.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.geojson.as2; - -import java.lang.reflect.Type; - -import com.google.common.collect.ImmutableSet; -import com.ibm.common.activitystreams.ASObject.AbstractBuilder; -import com.ibm.common.activitystreams.internal.ASObjectAdapter; -import com.ibm.common.activitystreams.internal.Model; -import com.ibm.common.activitystreams.internal.Schema; -import com.ibm.common.geojson.AS1Position; -import com.ibm.common.geojson.Address; -import com.ibm.common.geojson.GeoMakers; -import com.ibm.common.geojson.Place; - -@SuppressWarnings("deprecation") -public class GeoObjectAdapter - extends ASObjectAdapter { - - protected GeoObjectAdapter(Schema schema) { - super(schema); - } - - private static final ImmutableSet knownTypes = - ImmutableSet.of(Address.class,AS1Position.class,Place.class); - - @Override - protected boolean knowsType(Type type) { - if (super.knowsType(type)) - return true; - return knownTypes.contains(type); - } - - @Override - protected AbstractBuilder builderFor(Type type) { - if (super.knowsType(type)) - return super.builderFor(type); - if (type == Address.class) { - return GeoMakers.address(); - } else if (type == AS1Position.class) { - return GeoMakers.as1Position(); - } else if (type == Place.class) { - return GeoMakers.place(); - } else return null; - } - - @Override - protected Model modelFor(Type type) { - if (super.knowsType(type)) - return super.modelFor(type); - if (type == Address.class) { - return schema().forObjectClassOrType( - Address.Builder.class, - "address"); - } else if (type == AS1Position.class) { - return schema().forObjectClassOrType( - AS1Position.Builder.class, - "position"); - } else if (type == Place.class) { - return schema().forObjectClassOrType( - Place.Builder.class, - "place"); - } else return null; - } -} diff --git a/geo/src/main/kotlin/com/ibm/common/geojson/AS1Position.kt b/geo/src/main/kotlin/com/ibm/common/geojson/AS1Position.kt new file mode 100644 index 0000000..7c07a6d --- /dev/null +++ b/geo/src/main/kotlin/com/ibm/common/geojson/AS1Position.kt @@ -0,0 +1,123 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.geojson + +import com.google.common.primitives.Floats +import com.ibm.common.activitystreams.ASObject +import java.io.ObjectStreamException + +/** + * Represents an Activity Streams 1.0 style position object + * see (https://github.com/activitystreams/activity-schema/blob/master/activity-schema.md) + * + * Use of the AS1Position object is deprecated. Use the GeoJSON mechanisms + * instead + * + * @author james + */ +class AS1Position +private constructor(builder: Builder) : ASObject(builder) { + class Builder + internal constructor() : AbstractBuilder() { + init { + objectType("position") + } + + /** + * Set the latitude + * @param latitude float + * @return Builder + */ + fun latitude(latitude: Float): Builder? { + return set("latitude", Floats.max(0f, Floats.min(90.0f, latitude))) + } + + /** + * Set the longitude + * @param longitude float + * @return Builder + */ + fun longitude(longitude: Float): Builder? { + return set("longitude", Floats.max(-180.0f, Floats.min(180.0f, longitude))) + } + + /** + * Set the altitude + * @param altitude float + * @return Builder + */ + fun altitude(altitude: Float): Builder? { + return set("altitude", altitude) + } + + override fun get(): AS1Position { + return AS1Position(this) + } + } + + /** + * Get the latitude + * @return float + */ + fun latitude(): Float { + return Floats.max(0f, Floats.min(90.0f, getFloat("latitude"))) + } + + /** + * Get the longitude + * @return float + */ + fun longitude(): Float { + return Floats.max(-180.0f, Floats.min(180.0f, getFloat("longitude"))) + } + + /** + * Get the altitude. If the altitude property is not set, this + * will return Float.MIN_VALUE; + * @return float + */ + fun altitude(): Float { + return getFloat("altitude", Float.MIN_VALUE) + } + + // Java Serialization Support + @Throws(ObjectStreamException::class) + override fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: AS1Position?) : AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + override fun builder(): Builder { + return GeoMakers.as1Position() + } + + companion object { + private const val serialVersionUID = -2060301713159936285L + } + } +} diff --git a/geo/src/main/kotlin/com/ibm/common/geojson/Address.kt b/geo/src/main/kotlin/com/ibm/common/geojson/Address.kt new file mode 100644 index 0000000..736d29e --- /dev/null +++ b/geo/src/main/kotlin/com/ibm/common/geojson/Address.kt @@ -0,0 +1,178 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.geojson + +import com.ibm.common.activitystreams.ASObject +import java.io.ObjectStreamException + +/** + * A simple non-GeoJSON Address object modelled after the + * legacy Activity Streams 1.0 Address object + * (see https://github.com/activitystreams/activity-schema/blob/master/activity-schema.md) + * + * @author james + */ +class Address +private constructor(builder: Builder) : ASObject(builder) { + class Builder + internal constructor() : + AbstractBuilder() { + init { + objectType("address") + } + + /** + * The full mailing address formatted for display or use + * with a printed mailing label. + * @param formatted String + * @return Builder + */ + fun formatted(formatted: String?): Builder? { + return set("formatted", formatted) + } + + /** + * The street address including house number, street name, P.O. Box, + * apartment or unit number and extended multi-line address information. + * @param streetAddress String + * @return Builder + */ + fun streetAddress(streetAddress: String?): Builder? { + return set("streetAddress", streetAddress) + } + + /** + * The city or locality + * @param locality String + * @return Builder + */ + fun locality(locality: String?): Builder? { + return set("locality", locality) + } + + /** + * The state or region + * @param region String + * @return Builder + */ + fun region(region: String?): Builder? { + return set("region", region) + } + + /** + * The zip or postal code + * @param postalCode String + * @return Builder + */ + fun postalCode(postalCode: String?): Builder? { + return set("postalCode", postalCode) + } + + /** + * The country name component + * @param country String + * @return Builder + */ + fun country(country: String?): Builder? { + return set("country", country) + } + + /** + * Get the completed Address object + */ + override fun get(): Address { + return Address(this) + } + } + + /** + * The full mailing address formatted for display or use + * with a printed mailing label. + * @return String + */ + fun formatted(): String? { + return getString("formatted") + } + + /** + * The street address including house number, street name, P.O. Box, + * apartment or unit number and extended multi-line address information. + * @return String + */ + fun streetAddress(): String? { + return getString("streetAddress") + } + + /** + * The city or locality + * @return String + */ + fun locality(): String? { + return getString("locality") + } + + /** + * The state or region + * @return String + */ + fun region(): String? { + return getString("region") + } + + /** + * The zip or postal code + * @return String + */ + fun postalCode(): String? { + return getString("postalCode") + } + + /** + * The country name component + * @return String + */ + fun country(): String? { + return getString("country") + } + + // Java Serialization Support + @Throws(ObjectStreamException::class) + override fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: Address?) : AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + override fun builder(): Builder { + return GeoMakers.address() + } + + companion object { + private const val serialVersionUID = -2060301713159936285L + } + } +} diff --git a/geo/src/main/kotlin/com/ibm/common/geojson/BoundingBox.kt b/geo/src/main/kotlin/com/ibm/common/geojson/BoundingBox.kt new file mode 100644 index 0000000..6de4b69 --- /dev/null +++ b/geo/src/main/kotlin/com/ibm/common/geojson/BoundingBox.kt @@ -0,0 +1,289 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.geojson + +import com.google.common.base.Objects +import com.google.common.base.Supplier +import com.google.common.collect.ImmutableList +import com.google.common.collect.ImmutableSortedSet +import com.google.common.collect.Iterables +import java.io.ObjectStreamException +import java.io.Serializable + +/** + * A GeoJSON Bounding Box (see http://geojson.org/geojson-spec.html#bounding-boxes) + * @author james + */ +class BoundingBox +internal constructor(builder: Builder) : Iterable, + Serializable { + class Builder + + : Supplier { + val bounds: ImmutableList.Builder = ImmutableList.builder() + + fun add(value: Float): Builder { + bounds.add(value) + return this + } + + fun add(vararg values: Float): Builder { + if (values != null) for (v: Float in values) bounds.add(v) + return this + } + + override fun get(): BoundingBox { + return BoundingBox(this) + } + } + + private val bounds: ImmutableList + + init { + this.bounds = builder.bounds.build() + } + + override fun iterator(): MutableIterator { + return bounds.iterator() + } + + override fun toString(): String { + return Objects.toStringHelper(BoundingBox::class.java) + .addValue(bounds) + .toString() + } + + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm(obj: BoundingBox) : Serializable { + private val bounds: ImmutableList + + init { + this.bounds = obj.bounds + } + + @Throws(ObjectStreamException::class) + fun readResolve(): Any { + val builder: Builder = + Builder() + builder.bounds.addAll(bounds) + return builder.get() + } + + companion object { + private val serialVersionUID: Long = -2060301713159936285L + } + } + + companion object { + private fun buildBoundingBox( + xs: ImmutableSortedSet, + ys: ImmutableSortedSet, + zs: ImmutableSortedSet + ): BoundingBox { + val bbox: Builder = + Builder() + .add(xs.first()) + .add(ys.first()) + if (!zs.isEmpty()) bbox.add(zs.first()) + bbox.add(xs.last()) + bbox.add(ys.last()) + if (!zs.isEmpty()) bbox.add(zs.last()) + return bbox.get() + } + + fun calculateBoundingBoxLineStrings(lineStrings: Iterable): BoundingBox { + val xset: ImmutableSortedSet.Builder = + ImmutableSortedSet.naturalOrder() + val yset: ImmutableSortedSet.Builder = + ImmutableSortedSet.naturalOrder() + val zset: ImmutableSortedSet.Builder = + ImmutableSortedSet.naturalOrder() + for (ls: LineString in lineStrings) { + for (p: Position in ls) { + xset.add(p.northing()) + yset.add(p.easting()) + if (p.hasAltitude()) zset.add(p.altitude()) + } + } + return buildBoundingBox( + xset.build(), + yset.build(), + zset.build() + ) + } + + /** + * Calculate the Bounding Box for a collection of Polygon objects + * @param polygons Iterable<Polygon> + * @return BoundingBox + */ + fun calculateBoundingBoxPolygons(polygons: Iterable): BoundingBox { + val xset: ImmutableSortedSet.Builder = + ImmutableSortedSet.naturalOrder() + val yset: ImmutableSortedSet.Builder = + ImmutableSortedSet.naturalOrder() + val zset: ImmutableSortedSet.Builder = + ImmutableSortedSet.naturalOrder() + for (polygon: Polygon in polygons) { + for (line: LineString in polygon) { + for (pos: Position in line) { + xset.add(pos.northing()) + yset.add(pos.easting()) + if (pos.hasAltitude()) zset.add(pos.altitude()) + } + } + } + return buildBoundingBox( + xset.build(), + yset.build(), + zset.build() + ) + } + + fun calculateBoundingBoxPositions(positions: Iterable): BoundingBox { + val xset: ImmutableSortedSet.Builder = + ImmutableSortedSet.naturalOrder() + val yset: ImmutableSortedSet.Builder = + ImmutableSortedSet.naturalOrder() + val zset: ImmutableSortedSet.Builder = + ImmutableSortedSet.naturalOrder() + for (pos: Position in positions) { + xset.add(pos.northing()) + yset.add(pos.easting()) + if (pos.hasAltitude()) zset.add(pos.altitude()) + } + return buildBoundingBox( + xset.build(), + yset.build(), + zset.build() + ) + } + + fun calculateBoundingBox(position: Position): BoundingBox { + val bbox: Builder = + Builder() + bbox.add(position.northing()) + bbox.add(position.easting()) + if (position.hasAltitude()) bbox.add(position.altitude()) + return bbox.get() + } + + private fun addValues( + xset: ImmutableSortedSet.Builder, + yset: ImmutableSortedSet.Builder, + zset: ImmutableSortedSet.Builder, + positions: Iterable + ) { + for (position: Position in positions) { + xset.add(position.northing()) + yset.add(position.easting()) + if (position.hasAltitude()) zset.add(position.altitude()) + } + } + + private fun addValuesLineString( + xset: ImmutableSortedSet.Builder, + yset: ImmutableSortedSet.Builder, + zset: ImmutableSortedSet.Builder, + lines: Iterable + ) { + for (ls: LineString in lines) { + addValues(xset, yset, zset, ls) + } + } + + private fun addValuesPolygon( + xset: ImmutableSortedSet.Builder, + yset: ImmutableSortedSet.Builder, + zset: ImmutableSortedSet.Builder, + polygons: Iterable + ) { + for (poly: Polygon in polygons) { + addValuesLineString(xset, yset, zset, poly) + } + } + + fun calculateBoundingBox(geometry: Geometry<*, *>): BoundingBox { + return calculateBoundingBoxGeometries( + ImmutableList.of(geometry) + ) + } + + fun calculateBoundingBoxGeometries( + geometries: Iterable> + ): BoundingBox { + val xset: ImmutableSortedSet.Builder = + ImmutableSortedSet.naturalOrder() + val yset: ImmutableSortedSet.Builder = + ImmutableSortedSet.naturalOrder() + val zset: ImmutableSortedSet.Builder = + ImmutableSortedSet.naturalOrder() + for (geo: Geometry<*, *> in geometries) { + when (geo.type()) { + GeoObject.Type.POINT -> { + val point: Point = geo as Point + val position: Position? = Iterables.getFirst(point.coordinates(), null) + xset.add(position!!.northing()) + yset.add(position.easting()) + if (position.hasAltitude()) zset.add(position.altitude()) + } + + GeoObject.Type.LINESTRING, GeoObject.Type.MULTIPOINT -> addValues( + xset, + yset, + zset, + geo as Iterable + ) + + GeoObject.Type.MULTILINESTRING, GeoObject.Type.POLYGON -> addValuesLineString( + xset, + yset, + zset, + geo as Iterable + ) + + GeoObject.Type.MULTIPOLYGON -> addValuesPolygon(xset, yset, zset, geo as Iterable) + else -> {} + } + } + return buildBoundingBox( + xset.build(), + yset.build(), + zset.build() + ) + } + + fun calculateBoundingBoxFeatures(features: Iterable): BoundingBox { + val list: ImmutableList.Builder> = + ImmutableList.builder() + for (feature: Feature in features) { + val geometry: Geometry<*, *>? = feature.geometry() + if (geometry != null) list.add(geometry) + } + return calculateBoundingBoxGeometries(list.build()) + } + } +} diff --git a/geo/src/main/kotlin/com/ibm/common/geojson/CRS.kt b/geo/src/main/kotlin/com/ibm/common/geojson/CRS.kt new file mode 100644 index 0000000..23e4244 --- /dev/null +++ b/geo/src/main/kotlin/com/ibm/common/geojson/CRS.kt @@ -0,0 +1,143 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.geojson + +import com.google.common.base.Objects +import com.google.common.base.Supplier +import com.google.common.collect.ImmutableMap +import java.io.ObjectStreamException +import java.io.Serializable + +/** + * A GeoJSON Coordinate Reference System description + * see http://geojson.org/geojson-spec.html#coordinate-reference-system-objects + * @author james + */ +class CRS +internal constructor(builder: Builder) : Iterable, Serializable { + class Builder : Supplier { + var type: String? = null + val properties: ImmutableMap.Builder = ImmutableMap.builder() + + fun type(type: String?): Builder { + this.type = type + return this + } + + operator fun set(name: String, value: Any): Builder { + properties.put(name, value) + return this + } + + fun set(properties: Map?): Builder { + this.properties.putAll(properties) + return this + } + + override fun get(): CRS { + return CRS(this) + } + } + + private val type: String? + private val properties: Map + + init { + this.type = builder.type + this.properties = builder.properties.build() + } + + override fun toString(): String { + return Objects.toStringHelper(CRS::class.java) + .addValue(type) + .addValue(properties) + .toString() + } + + fun size(): Int { + return properties.size + } + + fun type(): String? { + return type + } + + fun properties(): Map { + return properties + } + + fun get(name: String): T? { + return properties[name] as T? + } + + fun get(name: String, defaultValue: T): T { + val t = this.get(name) + return t ?: defaultValue + } + + fun has(name: String): Boolean { + return properties.containsKey(name) + } + + override fun iterator(): MutableIterator { + return properties.keys.toMutableList().iterator() + } + + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm(obj: CRS) : Serializable { + private val type = obj.type + private val properties = obj.properties + + @Throws(ObjectStreamException::class) + fun readResolve(): Any { + val builder = Builder() + builder.type(type) + builder.properties.putAll(properties) + return builder.get() + } + + companion object { + private const val serialVersionUID = -2060301713159936285L + } + } + + companion object { + fun named(name: String): CRS { + return Builder() + .type("name") + .set("name", name) + .get() + } + + fun linked(href: String, type: String): CRS { + return Builder() + .type("link") + .set("href", href) + .set("type", type) + .get() + } + } +} diff --git a/geo/src/main/kotlin/com/ibm/common/geojson/Feature.kt b/geo/src/main/kotlin/com/ibm/common/geojson/Feature.kt new file mode 100644 index 0000000..1cbc988 --- /dev/null +++ b/geo/src/main/kotlin/com/ibm/common/geojson/Feature.kt @@ -0,0 +1,140 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.geojson + +import com.google.common.base.Supplier +import com.google.common.collect.ImmutableMap +import java.io.ObjectStreamException + +/** + * A GeoJSON Feature Object + * see http://geojson.org/geojson-spec.html#feature-objects + * @author james + */ +class Feature +internal constructor(builder: Builder) : GeoObject(builder), Iterable { + class Builder + + : GeoObject.Builder() { + val properties: ImmutableMap.Builder = ImmutableMap.builder() + + init { + type(Type.FEATURE) + } + + fun geometry(geometry: Geometry<*, *>?): Builder? { + return set("geometry", geometry) + } + + fun geometry(geometry: Supplier?>): Builder? { + return geometry(geometry.get()) + } + + fun property(name: String, value: Any): Builder { + properties.put(name, value) + return this + } + + fun properties(properties: MutableMap): Builder { + properties.putAll(properties) + return this + } + + fun id(id: String?): Builder? { + return set("id", id) + } + + public override fun doGet(): Feature { + set("properties", properties.build()) + return Feature(this) + } + } + + fun ?> geometry(): G? { + return this.get("geometry") + } + + fun properties(): MutableMap { + return this.get>( + "properties", ImmutableMap.of() + ) + } + + fun id(): String? { + return this.get("id") + } + + fun getProperty(name: String): T? { + return properties()[name] as T? + } + + fun getProperty(name: String, defaultValue: T): T { + val t = this.getProperty(name) + return t ?: defaultValue + } + + override fun has(name: String): Boolean { + return properties().containsKey(name) + } + + override fun iterator(): MutableIterator { + return properties().keys.iterator() + } + + override fun makeWithBoundingBox(): Feature { + return Builder().from(this).properties(this.properties()).boundingBox( + BoundingBox.Companion.calculateBoundingBox(geometry>()!!) + ).get() + } + + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: Feature) : AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return doReadResolve() + } + + override fun handle( + builder: Builder, key: String, `val`: Any? + ): Boolean { + if ("properties" == key) { + val props = `val` as Map? + builder.properties.putAll(props) + return true + } + return false + } + + override fun builder(): Builder { + return Builder() + } + + companion object { + private const val serialVersionUID = -2060301713159936281L + } + } +} diff --git a/geo/src/main/kotlin/com/ibm/common/geojson/FeatureCollection.kt b/geo/src/main/kotlin/com/ibm/common/geojson/FeatureCollection.kt new file mode 100644 index 0000000..2f19d35 --- /dev/null +++ b/geo/src/main/kotlin/com/ibm/common/geojson/FeatureCollection.kt @@ -0,0 +1,117 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.geojson + +import com.google.common.base.Supplier +import com.google.common.collect.ImmutableList +import com.google.common.collect.Iterables +import java.io.ObjectStreamException + +/** + * A GeoJSON FeatureCollection object + * see http://geojson.org/geojson-spec.html#feature-collection-objects + * @author james + */ +class FeatureCollection +internal constructor(builder: Builder) : GeoObject(builder), + Iterable { + class Builder + + : GeoObject.Builder() { + private val list: ImmutableList.Builder = ImmutableList.builder() + + init { + type(Type.FEATURECOLLECTION) + } + + fun add(features: Iterable): Builder { + list.addAll(features) + return this + } + + fun add(feature: Feature, vararg features: Feature?): Builder { + list.add(feature) + if (features != null) list.add(*features) + return this + } + + fun add(feature: Supplier): Builder { + return add(feature.get()) + } + + public override fun preGet() { + set("features", list.build()) + } + + public override fun doGet(): FeatureCollection { + return FeatureCollection(this) + } + } + + fun features(): Iterable { + return this.get>( + "features", + ImmutableList.of() + ) + } + + fun size(): Int { + return Iterables.size(features()) + } + + fun get(idx: Int): Feature { + return Iterables.get(features(), idx) + } + + override fun iterator(): MutableIterator { + return features().toMutableList().iterator() + } + + override fun makeWithBoundingBox(): FeatureCollection { + return Builder() + .from(this) + .add(this) + .boundingBox(BoundingBox.Companion.calculateBoundingBoxFeatures(this)) + .get() + } + + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: FeatureCollection) : AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any { + return doReadResolve() + } + + override fun builder(): Builder { + return GeoMakers.featureCollection() + } + + companion object { + private const val serialVersionUID = -2060301713159936281L + } + } +} diff --git a/geo/src/main/kotlin/com/ibm/common/geojson/GeoMakers.kt b/geo/src/main/kotlin/com/ibm/common/geojson/GeoMakers.kt new file mode 100644 index 0000000..eddb593 --- /dev/null +++ b/geo/src/main/kotlin/com/ibm/common/geojson/GeoMakers.kt @@ -0,0 +1,136 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.geojson + +/** + * Makers for the various GeoJSON object types + * @author james + */ +@Suppress("deprecation") +object GeoMakers { + fun place(): Place.Builder { + return Place.Builder() + } + + + fun as1Position(): AS1Position.Builder { + return AS1Position.Builder() + } + + + fun as1Position( + latitude: Float, + longitude: Float, + altitude: Float + ): AS1Position? { + return as1Position() + .longitude(longitude) + ?.latitude(latitude) + ?.altitude(altitude) + ?.get() + } + + + fun as1Position( + position: Position + ): AS1Position? { + return as1Position( + position.northing(), + position.easting(), + position.altitude() + ) + } + + fun position( + position: AS1Position + ): Position { + return position( + position.latitude(), + position.longitude(), + position.altitude() + ) + } + + fun address(): Address.Builder { + return Address.Builder() + } + + fun position(x: Float, y: Float): Position { + return GeoObject.Companion.position(x, y) + } + + fun position(x: Float, y: Float, z: Float): Position { + return GeoObject.Companion.position(x, y, z) + } + + fun point(x: Float, y: Float): Point? { + return point().position(x, y).get() + } + + fun point(x: Float, y: Float, z: Float): Point? { + return point().position(x, y, z).get() + } + + fun point(position: Position?): Point? { + return point().position(position).get() + } + + fun point(): Point.Builder { + return Point.Builder() + } + + fun multipoint(): MultiPoint.Builder { + return MultiPoint.Builder() + } + + fun linestring(): LineString.Builder { + return LineString.Builder() + } + + fun linearRing(): LineString.Builder { + return linestring().linearRing() + } + + fun feature(): Feature.Builder { + return Feature.Builder() + } + + fun featureCollection(): FeatureCollection.Builder { + return FeatureCollection.Builder() + } + + fun geometryCollection(): GeometryCollection.Builder { + return GeometryCollection.Builder() + } + + fun multiLineString(): MultiLineString.Builder { + return MultiLineString.Builder() + } + + fun multiPolygon(): MultiPolygon.Builder { + return MultiPolygon.Builder() + } + + fun polygon(): Polygon.Builder { + return Polygon.Builder() + } +} diff --git a/geo/src/main/kotlin/com/ibm/common/geojson/GeoObject.kt b/geo/src/main/kotlin/com/ibm/common/geojson/GeoObject.kt new file mode 100644 index 0000000..c35833c --- /dev/null +++ b/geo/src/main/kotlin/com/ibm/common/geojson/GeoObject.kt @@ -0,0 +1,247 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.geojson + +import com.google.common.base.Objects +import com.google.common.base.Supplier +import com.google.common.collect.ImmutableMap +import com.google.common.collect.Maps +import java.io.Serializable + +/** + * The base class for all GeoJSON objects. The type of object is identified + * by the type() property. + * @author james + * + * @param + */ +abstract class GeoObject> +protected constructor(builder: Builder<*, *>) : Serializable { + enum class Type { + POINT, + MULTIPOINT, + LINESTRING, + MULTILINESTRING, + POLYGON, + MULTIPOLYGON, + GEOMETRYCOLLECTION, + FEATURE, + FEATURECOLLECTION + } + + abstract class Builder + , B : Builder> + : Supplier { + protected var withBoundingBox: Boolean = false + var type: Type? = null + var data: MutableMap = Maps.newLinkedHashMap() + + /** + * Auto-calculate the bounding box when the object is created + * @return Builder + */ + fun calculateBoundingBox(): B { + this.withBoundingBox = true + return this as B + } + + /** + * Use the given object as a template when creating this one + * @param geo GeObject<?> + * @return Builder + */ + fun from(geo: GeoObject<*>): B { + data.putAll(geo.data) + return this as B + } + + /** + * Set the object type + * @param type Type + * @return Builder + */ + fun type(type: Type?): B { + this.type = type + return this as B + } + + /** + * Set the CRS + * @param crs CRS + * @return Builder + */ + fun crs(crs: CRS?): B { + return set("crs", crs) + } + + /** + * Set the bounding box explicitly + * @param bbox BoundingBox + * @return Builder + * @see GeoObject.Builder.calculateBoundingBox + */ + fun boundingBox(bbox: BoundingBox?): B { + return set("bbox", bbox) + } + + /** + * Set an additional property on this object + * @param name String + * @param val Object + * @return Builder + */ + operator fun set(name: String, `val`: Any?): B { + if (`val` != null) data[name] = `val` + else if (data.containsKey(name)) data.remove(name) + return this as B + } + + /** + * Get the built object + */ + override fun get(): G { + preGet() + val g = doGet() + return if (withBoundingBox) g!!.withBoundingBox() else g + } + + protected open fun preGet() {} + + protected abstract fun doGet(): G + } + + val type: Type? + val data: Map + + init { + this.type = builder.type + this.data = ImmutableMap.copyOf(builder.data) + } + + /** + * Return the type of object + * @return Type + */ + fun type(): Type? { + return type + } + + fun get(name: String): T? { + return data[name] as T? + } + + fun get(name: String, defaultValue: T): T { + val `val` = get(name) + return `val` ?: defaultValue + } + + open fun has(name: String): Boolean { + return data.containsKey(name) + } + + /** + * Return the CRS for this object + * @return CRS + */ + fun crs(): CRS? { + return this.get("crs", null) + } + + /** + * Return the bounding box for this object + * @return BoundingBox + */ + fun boundingBox(): BoundingBox? { + return this.get("bbox", null) + } + + /** + * Return a copy of this object with a calculated bounding box + * @return G (a copy of this object) + */ + fun withBoundingBox(): G { + return if (has("bbox")) this as G else makeWithBoundingBox() + } + + protected abstract fun makeWithBoundingBox(): G + + override fun toString(): String { + return Objects.toStringHelper(GeoObject::class.java) + .add("type", type) + .add("data", data) + .toString() + } + + protected abstract class AbstractSerializedForm + , B : Builder> + internal constructor(obj: G) : Serializable { + private val type: Type? + private val data: Map + + init { + this.type = obj!!.type() + this.data = obj.data + } + + protected fun doReadResolve(): Any { + val builder = builder() + builder!!.type(type) + for (entry: Map.Entry in data.entries) { + if (!handle(builder, entry.key, entry.value)) builder.data[entry.key] = entry.value + } + return builder.get() + } + + protected open fun handle( + builder: B, + key: String, + `val`: Any? + ): Boolean { + return false + } + + protected abstract fun builder(): B + + companion object { + private val serialVersionUID = -1950126276150975248L + } + } + + companion object { + private const val serialVersionUID = 8852811044366213922L + + fun position(x: Float, y: Float): Position { + return Position.Builder() + .northing(x) + .easting(y) + .get() + } + + fun position(x: Float, y: Float, z: Float): Position { + return Position.Builder() + .northing(x) + .easting(y) + .altitude(z) + .get() + } + } +} diff --git a/geo/src/main/kotlin/com/ibm/common/geojson/Geometry.kt b/geo/src/main/kotlin/com/ibm/common/geojson/Geometry.kt new file mode 100644 index 0000000..f3637d5 --- /dev/null +++ b/geo/src/main/kotlin/com/ibm/common/geojson/Geometry.kt @@ -0,0 +1,58 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.geojson + +import com.google.common.collect.ImmutableList + +abstract class Geometry, M> +protected constructor(builder: Builder<*, *>) : GeoObject(builder), + Iterable { + abstract class CoordinateGeometry, M, P> + protected constructor(builder: Builder) : + Geometry(builder) { + abstract class Builder + , B : Builder> + : GeoObject.Builder() { + protected abstract fun coordinates(): P? + + public override fun preGet() { + set("coordinates", coordinates()) + } + + abstract override fun doGet(): C + } + + open fun coordinates(): Iterable { + val o: Any? = get("coordinates") + if (o is Iterable<*>) return o as Iterable + else return ImmutableList.of(o as M) + } + + companion object { + private val serialVersionUID: Long = -6502745908455054826L + } + } + + companion object { + private val serialVersionUID: Long = -6184360762496309625L + } +} diff --git a/geo/src/main/kotlin/com/ibm/common/geojson/GeometryCollection.kt b/geo/src/main/kotlin/com/ibm/common/geojson/GeometryCollection.kt new file mode 100644 index 0000000..f4a1c61 --- /dev/null +++ b/geo/src/main/kotlin/com/ibm/common/geojson/GeometryCollection.kt @@ -0,0 +1,121 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.geojson + +import com.google.common.collect.ImmutableList +import com.google.common.collect.Iterables +import java.io.ObjectStreamException + +/** + * A GeoJSON GeometryCollection object + * see http://geojson.org/geojson-spec.html#geometry-collection + * @author james + */ +class GeometryCollection +internal constructor(builder: Builder) : + Geometry>(builder) { + class Builder + + : GeoObject.Builder() { + val list: ImmutableList.Builder> = ImmutableList.builder() + + init { + type(Type.GEOMETRYCOLLECTION) + } + + fun add(geometry: Geometry<*, *>, vararg geometries: Geometry<*, *>?): Builder { + list.add(geometry) + if (geometries != null) list.add(*geometries) + return this + } + + fun add(geometries: Iterable>): Builder { + list.addAll(geometries) + return this + } + + public override fun preGet() { + set("geometries", list.build()) + } + + public override fun doGet(): GeometryCollection { + return GeometryCollection(this) + } + } + + fun geometries(): Iterable> { + return this.get>>( + "geometries", + ImmutableList.of() + ) + } + + fun size(): Int { + return Iterables.size(geometries()) + } + + fun ?> get(idx: Int): G { + return Iterables.get(geometries(), idx) as G + } + + override fun iterator(): MutableIterator> { + return geometries().toMutableList().iterator() + } + + public override fun makeWithBoundingBox(): GeometryCollection { + return Builder() + .from(this) + .add(this as Iterable>) + .boundingBox(BoundingBox.Companion.calculateBoundingBoxGeometries(this)) + .get() + } + + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: GeometryCollection) : AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any { + return doReadResolve() + } + + override fun handle(builder: Builder, key: String, `val`: Any?): Boolean { + if ("geometries" == key) { + val list = `val` as Iterable>? + builder.list.addAll(list) + return true + } + return false + } + + override fun builder(): Builder { + return GeoMakers.geometryCollection() + } + + companion object { + private const val serialVersionUID = -2060301713159936281L + } + } +} diff --git a/geo/src/main/kotlin/com/ibm/common/geojson/LineString.kt b/geo/src/main/kotlin/com/ibm/common/geojson/LineString.kt new file mode 100644 index 0000000..4c28edb --- /dev/null +++ b/geo/src/main/kotlin/com/ibm/common/geojson/LineString.kt @@ -0,0 +1,243 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.geojson + +import com.google.common.base.Preconditions +import com.google.common.base.Supplier +import com.google.common.collect.ImmutableList +import com.google.common.collect.Iterables +import com.ibm.common.geojson.Geometry.CoordinateGeometry +import java.io.ObjectStreamException + +/** + * A GeoJSON LineString object + * See http://geojson.org/geojson-spec.html#linestring. + * + * The LineString can optionally be a Linear Ring if there are at least four + * positions and the first and last position are equivalent. + * + *
+ * LineString regularLineString =
+ * GeoMakers.linestring()
+ * .add(1,2)
+ * .add(2,3)
+ * .get();
+ * // includes points (1,2) and (2,3)
+ *
+ * LineString linearRing =
+ * GeoMakers.linestring()
+ * .linearRing()
+ * .add(1,2)
+ * .add(2,3)
+ * .add(3,4)
+ * .get()
+ * // includes points (1,2), (2,3), (3,4) and (1,2)
+
* + * + * @author james + */ +class LineString +protected constructor(builder: Builder) : + CoordinateGeometry>(builder) { + class Builder + + : CoordinateGeometry.Builder, LineString, Builder> { + val positions: ImmutableList.Builder = ImmutableList.builder() + var ring: Boolean = false + val nocheck: Boolean + + constructor() { + nocheck = false + type(Type.LINESTRING) + } + + constructor(nocheck: Boolean) { + this.nocheck = nocheck + type(Type.LINESTRING) + } + + /** + * Specify that this LineString is a linearring + * @return Builder + */ + @JvmOverloads + fun linearRing(on: Boolean = true): Builder { + this.ring = on + return this + } + + /** + * Add one or more positions to this linestring + * @param position Position + * @param positions Position[] optional vararg + * @return Builder + */ + fun add(position: Position, vararg positions: Position): Builder { + this.positions.add(position) + if (positions != null) for (pos in positions) add(pos) + return this + } + + /** + * Add a single position to this linestring + * @param x float + * @param y float + * @return Builder + */ + fun add(x: Float, y: Float): Builder { + return add(GeoObject.Companion.position(x, y)) + } + + /** + * Add a single position to this linestring + * @param position Supplier<Position> + * @return Builder + */ + fun add(position: Supplier): Builder { + return add(position.get()) + } + + /** + * Add one or more positions to this linestring + * @param positions Iterable<Position> + * @return Builder + */ + fun add(positions: Iterable): Builder { + this.positions.addAll(positions) + return this + } + + /** + * Add a single position to this linestring + * @param x float + * @param y float + * @param z float + * @return Builder + */ + fun add(x: Float, y: Float, z: Float): Builder { + return add(GeoObject.Companion.position(x, y, z)) + } + + public override fun doGet(): LineString { + return LineString(this) + } + + override fun coordinates(): Iterable { + return positions.build() + } + } + + private val ring: Boolean + + init { + this.ring = builder.ring + val min = if (ring) 3 else 2 + Preconditions.checkArgument( + builder.nocheck || + Iterables.size(coordinates()) >= min, + String.format( + "A LineString that %s a LinearRing MUST consist of at least %d positions", + if (ring) "is" else "is not", + min + ) + ) + } + + fun linearRing(): Boolean { + return ring + } + + /** + * Get this LineStrings positions + * @return Iterable<Position> + */ + override fun coordinates(): Iterable { + val pos = super.coordinates() + return if (!ring) { + pos + } else ({ + if (Iterables.size(pos) > 0) Iterables.concat( + pos, + ImmutableList.of( + Iterables.getFirst( + pos, + null + )!! + ) + ) else ImmutableList.of() + }) as Iterable + } + + override fun iterator(): MutableIterator { + return coordinates().toMutableList().iterator() + } + + /** + * Return a copy of this linestring with a calculated bounding box + */ + public override fun makeWithBoundingBox(): LineString { + return Builder() + .from(this) + .add(this) + .boundingBox(BoundingBox.Companion.calculateBoundingBoxPositions(this)) + .get() + } + + // Java Serialization support + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: LineString) : AbstractSerializedForm(obj) { + var ring: Boolean + + init { + this.ring = obj.ring + } + + @Throws(ObjectStreamException::class) + fun readResolve(): Any { + return doReadResolve() + } + + override fun handle(builder: Builder, key: String, `val`: Any?): Boolean { + if ("coordinates" == key) { + val list = `val` as Iterable? + builder.positions.addAll(list) + return true + } + return false + } + + override fun builder(): Builder { + val builder = Builder(true) + builder.ring = ring + return builder + } + + companion object { + private const val serialVersionUID = -2060301713159936281L + } + } +} diff --git a/geo/src/main/kotlin/com/ibm/common/geojson/MultiLineString.kt b/geo/src/main/kotlin/com/ibm/common/geojson/MultiLineString.kt new file mode 100644 index 0000000..67ff45d --- /dev/null +++ b/geo/src/main/kotlin/com/ibm/common/geojson/MultiLineString.kt @@ -0,0 +1,136 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.geojson + +import com.google.common.base.Supplier +import com.google.common.collect.ImmutableList +import com.ibm.common.geojson.Geometry.CoordinateGeometry +import java.io.ObjectStreamException + +/** + * A GeoJSON MultiLineString object + * see http://geojson.org/geojson-spec.html#multilinestring + * @author james + */ +class MultiLineString +protected constructor(builder: Builder) : + CoordinateGeometry>(builder) { + class Builder + + : CoordinateGeometry.Builder, MultiLineString, Builder>() { + val strings: ImmutableList.Builder = ImmutableList.builder() + + init { + type(Type.MULTILINESTRING) + } + + /** + * Add one or more LineStrings + * @param line LineString + * @param lines LineString[] optional vararg + * @return Builder + */ + fun add(line: LineString, vararg lines: LineString): Builder { + strings.add(line) + if (lines != null) for (l in lines) add(l) + return this + } + + /** + * Add a single LineString + * @param line Supplier<LineString> + * @return Builder + */ + fun add(line: Supplier): Builder { + return add(line.get()) + } + + /** + * Add one or more LineStrings + * @param lines Iterable<LineString> + * @return Builder + */ + fun add(lines: Iterable): Builder { + strings.addAll(lines) + return this + } + + public override fun doGet(): MultiLineString { + return MultiLineString(this) + } + + /** + * Get this objects collection of LineStrings + * @return Iterable<LineString> + */ + override fun coordinates(): Iterable { + return strings.build() + } + } + + override fun iterator(): MutableIterator { + return coordinates().toMutableList().iterator() + } + + /** + * Copy this object with a calculated bounding box + * @return MultiLineString + */ + override fun makeWithBoundingBox(): MultiLineString { + return Builder() + .from(this) + .add(this) + .boundingBox( + BoundingBox.Companion.calculateBoundingBoxLineStrings(this) + ).get() + } + + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: MultiLineString) : AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any { + return doReadResolve() + } + + override fun handle(builder: Builder, key: String, `val`: Any?): Boolean { + if ("coordinates" == key) { + val list = `val` as Iterable? + builder.strings.addAll(list) + return true + } + return false + } + + override fun builder(): Builder { + return GeoMakers.multiLineString() + } + + companion object { + private const val serialVersionUID = -2060301713159936281L + } + } +} diff --git a/geo/src/main/kotlin/com/ibm/common/geojson/MultiPoint.kt b/geo/src/main/kotlin/com/ibm/common/geojson/MultiPoint.kt new file mode 100644 index 0000000..9acac47 --- /dev/null +++ b/geo/src/main/kotlin/com/ibm/common/geojson/MultiPoint.kt @@ -0,0 +1,151 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.geojson + +import com.google.common.base.Supplier +import com.google.common.collect.ImmutableList +import com.ibm.common.geojson.Geometry.CoordinateGeometry +import java.io.ObjectStreamException + +/** + * A GeoJSON MultiPoint object + * see http://geojson.org/geojson-spec.html#multipoint + * @author james + */ +class MultiPoint +protected constructor(builder: Builder) : + CoordinateGeometry>(builder) { + class Builder + + : CoordinateGeometry.Builder, MultiPoint, Builder>() { + var list: ImmutableList.Builder = ImmutableList.builder() + + init { + type(Type.MULTIPOINT) + } + + /** + * Add one or more positions + * @param position Position + * @param positions Position[] optional vararg + * @return Builder + */ + fun add(position: Position, vararg positions: Position?): Builder { + list.add(position) + if (positions != null) list.add(*positions) + return this + } + + /** + * Add one or more positions + * @param positions Iterable<Position> + * @return Builder + */ + fun add(positions: Iterable): Builder { + list.addAll(positions) + return this + } + + /** + * Add a position + * @param pos Supplier<Position> + * @return Builder + */ + fun add(pos: Supplier): Builder { + return add(pos.get()) + } + + /** + * Add a position + * @param x float + * @param y float + * @return Builder + */ + fun add(x: Float, y: Float): Builder { + return add(GeoObject.Companion.position(x, y)) + } + + /** + * Add a position + * @param x float + * @param y float + * @param z float + * @return Builder + */ + fun add(x: Float, y: Float, z: Float): Builder { + return add(GeoObject.Companion.position(x, y, z)) + } + + override fun coordinates(): Iterable { + return list.build() + } + + public override fun doGet(): MultiPoint { + return MultiPoint(this) + } + } + + override fun iterator(): MutableIterator { + return coordinates().toMutableList().iterator() + } + + /** + * Return a copy of this object with a calculated bounding box + * @return MultiPoint + */ + override fun makeWithBoundingBox(): MultiPoint { + return Builder() + .from(this) + .add(this) + .boundingBox(BoundingBox.Companion.calculateBoundingBoxPositions(this)).get() + } + + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: MultiPoint) : AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return doReadResolve() + } + + override fun handle(builder: Builder, key: String, `val`: Any?): Boolean { + if ("coordinates" == key) { + val list = `val` as Iterable? + builder.list.addAll(list) + return true + } + return false + } + + override fun builder(): Builder { + return GeoMakers.multipoint() + } + + companion object { + private const val serialVersionUID = -2060301713159936281L + } + } +} diff --git a/geo/src/main/kotlin/com/ibm/common/geojson/MultiPolygon.kt b/geo/src/main/kotlin/com/ibm/common/geojson/MultiPolygon.kt new file mode 100644 index 0000000..9e76fed --- /dev/null +++ b/geo/src/main/kotlin/com/ibm/common/geojson/MultiPolygon.kt @@ -0,0 +1,132 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.geojson + +import com.google.common.base.Supplier +import com.google.common.collect.ImmutableList +import com.ibm.common.geojson.Geometry.CoordinateGeometry +import java.io.ObjectStreamException + +/** + * A GeoJSON MultiPolygon object. + * see http://geojson.org/geojson-spec.html#multipolygon + * @author james + */ +class MultiPolygon +protected constructor(builder: Builder) : + CoordinateGeometry>(builder) { + class Builder + + : CoordinateGeometry.Builder, MultiPolygon, Builder>() { + val strings: ImmutableList.Builder = ImmutableList.builder() + + init { + type(Type.MULTIPOLYGON) + } + + /** + * Add one or more Polygons + * @param poly Polygon + * @param polys Polygon[] optional vararg + * @return Builder + */ + fun add(poly: Polygon, vararg polys: Polygon): Builder { + // TODO: Check hole requirement + strings.add(poly) + if (polys != null) for (l in polys) add(l) + return this + } + + /** + * Add a Polygon + * @param poly Supplier<Polygon> + * @return Builder + */ + fun add(poly: Supplier): Builder { + return add(poly.get()) + } + + /** + * Add one ore more Polygons + * @param polygons Iterable<Polygon> + * @return Builder + */ + fun add(polygons: Iterable): Builder { + strings.addAll(polygons) + return this + } + + public override fun doGet(): MultiPolygon { + return MultiPolygon(this) + } + + override fun coordinates(): Iterable { + return strings.build() + } + } + + override fun iterator(): MutableIterator { + return coordinates().toMutableList().iterator() + } + + /** + * Return a copy of this object with a calculated bounding box + * @return MultiPolygon + */ + override fun makeWithBoundingBox(): MultiPolygon { + return Builder() + .from(this) + .add(this) + .boundingBox(BoundingBox.Companion.calculateBoundingBoxPolygons(this)) + .get() + } + + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: MultiPolygon) : AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any { + return doReadResolve() + } + + override fun handle(builder: Builder, key: String, `val`: Any?): Boolean { + if ("coordinates" == key) { + val list = `val` as Iterable? + builder.strings.addAll(list) + return true + } + return false + } + + override fun builder(): Builder { + return GeoMakers.multiPolygon() + } + + companion object { + private const val serialVersionUID = -2060301713159936281L + } + } +} diff --git a/geo/src/main/kotlin/com/ibm/common/geojson/Place.kt b/geo/src/main/kotlin/com/ibm/common/geojson/Place.kt new file mode 100644 index 0000000..0482541 --- /dev/null +++ b/geo/src/main/kotlin/com/ibm/common/geojson/Place.kt @@ -0,0 +1,164 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.geojson + +import com.google.common.base.Supplier +import com.ibm.common.activitystreams.ASObject +import java.io.ObjectStreamException + +/** + * A legacy Activity Streams 1.0 Place object + * see https://github.com/activitystreams/activity-schema/blob/master/activity-schema.md. + * + * Place objects have additional address, position and geo properties that + * describe the location. + * @author james + */ +class Place private constructor(builder: Builder) : ASObject(builder) { + class Builder + internal constructor() : AbstractBuilder() { + init { + objectType("place") + } + + /** + * Set the address + * @param address Address + * @return Builder + */ + fun address(address: Address?): Builder? { + return set("address", address) + } + + /** + * Set the address + * @param address Supplier<Address> + * @return Builder + */ + fun address(address: Supplier): Builder? { + return address(address.get()) + } + + /** + * Set the position + * + * @param position AS1Position + * @return Builder + */ + fun position(position: AS1Position?): Builder? { + return set("position", position) + } + + /** + * Set the position + * + * @param position Supplier<AS1Position> + * @return Builder + */ + fun position(position: Supplier): Builder? { + return position(position.get()) + } + + /** + * Set the position + * @param latitude float + * @param longitude float + * @param altitude float + * @return Builder + */ + fun position( + latitude: Float, + longitude: Float, + altitude: Float + ): Builder? { + return position(GeoMakers.as1Position(latitude, longitude, altitude)) + } + + /** + * Set the geo property + * @param geo GeoObject<?> Any GeoJSON object can be used + * @return Builder + */ + fun geo(geo: GeoObject<*>?): Builder? { + return set("geo", geo) + } + + /** + * Set the geo property + * @param geo Supplier<? extends GeoObject<?>> Any GeoJSON object can be used + * @return Builder + */ + fun geo(geo: Supplier?>): Builder? { + return geo(geo.get()) + } + + override fun get(): Place { + return Place(this) + } + } + + /** + * Get the address + * @return Address + */ + fun address(): Address? { + return this.get
("address") + } + + /** + * Get the position + * + * @return AS1Position + */ + fun position(): AS1Position? { + return this.get("position") + } + + /** + * Get the geo property + * @return <G extends GeoObject<?>>G + */ + fun ?> geo(): G? { + return this.get("geo") + } + + @Throws(ObjectStreamException::class) + override fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: Place?) : AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + override fun builder(): Builder { + return GeoMakers.place() + } + + companion object { + private const val serialVersionUID = -2060301713159936285L + } + } +} diff --git a/geo/src/main/kotlin/com/ibm/common/geojson/Point.kt b/geo/src/main/kotlin/com/ibm/common/geojson/Point.kt new file mode 100644 index 0000000..e37add3 --- /dev/null +++ b/geo/src/main/kotlin/com/ibm/common/geojson/Point.kt @@ -0,0 +1,143 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.geojson + +import com.google.common.base.Supplier +import com.google.common.collect.Iterables +import com.ibm.common.geojson.Geometry.CoordinateGeometry +import java.io.ObjectStreamException + +/** + * A GeoJSON Point object + * see http://geojson.org/geojson-spec.html#point. + * + * A Point object represents a single Position + * + * @author james + */ +class Point +internal constructor(builder: Builder) : + CoordinateGeometry(builder) { + class Builder + + : CoordinateGeometry.Builder() { + var position: Position? = null + + init { + type(Type.POINT) + } + + /** + * Set the position + * @param northing float + * @param easting float + * @param altitude float + * @return Builder + */ + fun position(northing: Float, easting: Float, altitude: Float): Builder { + this.position = GeoObject.Companion.position(northing, easting, altitude) + return this + } + + /** + * Set the position + * @param northing float + * @param easting float + * @return Builder + */ + fun position(northing: Float, easting: Float): Builder { + this.position = GeoObject.Companion.position(northing, easting) + return this + } + + /** + * Set the position + * @param position Position + * @return Builder + */ + fun position(position: Position?): Builder { + this.position = position + return this + } + + /** + * Set the position + * @param position Supplier<Position> + * @return Builder + */ + fun position(position: Supplier): Builder { + return position(position.get()) + } + + override fun coordinates(): Position? { + return position + } + + public override fun doGet(): Point { + return Point(this) + } + } + + override fun iterator(): MutableIterator { + return coordinates().toMutableList().iterator() + } + + + override fun makeWithBoundingBox(): Point { + val pos = Iterables.getFirst(coordinates(), null) + return Builder() + .from(this) + .position(pos) + .boundingBox(BoundingBox.Companion.calculateBoundingBox(pos!!)) + .get() + } + + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: Point) : + AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return doReadResolve() + } + + override fun handle(builder: Builder, key: String, `val`: Any?): Boolean { + if ("coordinates" == key) { + builder.position = `val` as Position? + return true + } + return false + } + + override fun builder(): Builder { + return GeoMakers.point() + } + + companion object { + private const val serialVersionUID = -2060301713159936281L + } + } +} diff --git a/geo/src/main/kotlin/com/ibm/common/geojson/Polygon.kt b/geo/src/main/kotlin/com/ibm/common/geojson/Polygon.kt new file mode 100644 index 0000000..d39221f --- /dev/null +++ b/geo/src/main/kotlin/com/ibm/common/geojson/Polygon.kt @@ -0,0 +1,133 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.geojson + +import com.google.common.base.Preconditions +import com.google.common.base.Supplier +import com.google.common.collect.ImmutableList +import com.ibm.common.geojson.Geometry.CoordinateGeometry +import java.io.ObjectStreamException + +/** + * A GeoJSON Polygon object + * see http://geojson.org/geojson-spec.html#polygon + * @author james + */ +class Polygon +protected constructor(builder: Builder) : + CoordinateGeometry>(builder) { + class Builder + + : CoordinateGeometry.Builder, Polygon, Builder>() { + val strings: ImmutableList.Builder = ImmutableList.builder() + + init { + type(Type.POLYGON) + } + + /** + * Add one or more LineStrings + * @param line LineString + * @param lines LineString[] optional vararg + * @return Builder + */ + fun add(line: LineString, vararg lines: LineString): Builder { + Preconditions.checkArgument(line.linearRing(), "Polygon coordinates MUST be Linear Rings") + + // TODO: Check hole requirement + strings.add(line) + if (lines != null) for (l in lines) add(l) + return this + } + + /** + * Add a LineString + * @param line Supplier<LineString> + * @return Builder + */ + fun add(line: Supplier): Builder { + return add(line.get()) + } + + /** + * Add one or more LineStrings + * @param lines Iterable<LineString> + * @return Builder + */ + fun add(lines: Iterable): Builder { + strings.addAll(lines) + return this + } + + public override fun doGet(): Polygon { + return Polygon(this) + } + + override fun coordinates(): Iterable { + return strings.build() + } + } + + override fun iterator(): MutableIterator { + return coordinates().toMutableList().iterator() + } + + override fun makeWithBoundingBox(): Polygon { + return Builder() + .from(this) + .add(this) + .boundingBox( + BoundingBox.Companion.calculateBoundingBoxLineStrings(this) + ).get() + } + + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: Polygon) : + AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return doReadResolve() + } + + override fun handle(builder: Builder, key: String, `val`: Any?): Boolean { + if ("coordinates" == key) { + val list = `val` as Iterable? + builder.strings.addAll(list) + return true + } + return false + } + + override fun builder(): Builder { + return GeoMakers.polygon() + } + + companion object { + private const val serialVersionUID = -2060301713159936281L + } + } +} diff --git a/geo/src/main/kotlin/com/ibm/common/geojson/Position.kt b/geo/src/main/kotlin/com/ibm/common/geojson/Position.kt new file mode 100644 index 0000000..1cef792 --- /dev/null +++ b/geo/src/main/kotlin/com/ibm/common/geojson/Position.kt @@ -0,0 +1,158 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.geojson + +import com.google.common.base.Supplier +import com.google.common.collect.ImmutableList +import com.google.common.primitives.Floats +import java.io.ObjectStreamException +import java.io.Serializable + +/** + * A GeoJSON Position + * see http://geojson.org/geojson-spec.html#positions. + * + * Position objects consist primarily of three distinct values: + * a northing (latitude or x), easting (longitude or y) and altitude (z). + * + * @author james + */ +class Position +internal constructor(builder: Builder) : Iterable, + Serializable { + class Builder + + : Supplier { + var x: Float = 0f + var y: Float = 0f + var z: Float = 0f + var hasz: Boolean = false + val rest: ImmutableList.Builder = ImmutableList.builder() + + fun northing(x: Float): Builder { + this.x = x + return this + } + + fun easting(y: Float): Builder { + this.y = y + return this + } + + fun altitude(z: Float): Builder { + this.hasz = true + this.z = z + return this + } + + fun additional(m: Float): Builder { + rest.add(m) + return this + } + + override fun get(): Position { + return Position(this) + } + } + + private val x: Float + private val y: Float + private val z: Float + private val hasz: Boolean + private val rest: FloatArray + + init { + this.x = builder.x + this.y = builder.y + this.z = builder.z + this.hasz = builder.hasz + this.rest = Floats.toArray(builder.rest.build()) + } + + fun northing(): Float { + return x + } + + fun easting(): Float { + return y + } + + fun altitude(): Float { + return z + } + + fun hasAltitude(): Boolean { + return hasz + } + + fun size(): Int { + return values().size + } + + private fun values(): FloatArray { + return if (hasz) Floats.concat(floatArrayOf(x, y, z), rest) else Floats.concat( + floatArrayOf(x, y), rest + ) + } + + override fun toString(): String { + return values().contentToString() + } + + override fun iterator(): MutableIterator { + return Floats.asList(*values()).iterator() + } + + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm(obj: Position) : Serializable { + private val x = obj.x + private val y = obj.y + private val z = obj.z + private val hasz: Boolean + private val rest: FloatArray? + + init { + this.hasz = obj.hasz + this.rest = obj.rest + } + + @Throws(ObjectStreamException::class) + fun readResolve(): Any { + val position = + Builder() + .northing(x) + .easting(y) + .altitude(z) + position.hasz = this.hasz + if (rest != null) for (f in rest) position.additional(f) + return position.get() + } + + companion object { + private const val serialVersionUID = -2060301713159936285L + } + } +} diff --git a/geo/src/main/kotlin/com/ibm/common/geojson/as2/GeoAdapter.kt b/geo/src/main/kotlin/com/ibm/common/geojson/as2/GeoAdapter.kt new file mode 100644 index 0000000..d4897c8 --- /dev/null +++ b/geo/src/main/kotlin/com/ibm/common/geojson/as2/GeoAdapter.kt @@ -0,0 +1,350 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.geojson.as2 + +import com.google.common.base.Enums +import com.google.common.base.Preconditions +import com.google.gson.* +import com.ibm.common.activitystreams.i.Adapter +import com.ibm.common.geojson.* +import com.ibm.common.geojson.GeoObject.Type.* +import com.ibm.common.geojson.Geometry.CoordinateGeometry +import java.lang.reflect.Type +import java.util.* + +class GeoAdapter + + : Adapter>() { + override fun serialize( + geo: GeoObject<*>, + type: Type, + context: JsonSerializationContext + ): JsonElement { + val obj = JsonObject() + obj.add("type", context.serialize(geo.type(), GeoObject.Type::class.java)) + when (geo.type()) { + POINT, MULTIPOINT, LINESTRING, MULTILINESTRING, MULTIPOLYGON, POLYGON -> { + val c = + geo as CoordinateGeometry<*, *, *> + obj.add( + "coordinates", + context.serialize( + c.coordinates(), + Iterable::class.java + ) + ) + } + + GEOMETRYCOLLECTION -> { + val gc = + geo as GeometryCollection + obj.add( + "geometries", + context.serialize( + gc.geometries(), + Iterable::class.java + ) + ) + } + + FEATURE -> { + val feature = + geo as Feature + if (feature.id() != null) obj.addProperty("id", feature.id()) + val geometry = feature.geometry() + val properties = feature.properties() + if (geometry != null) obj.add( + "geometry", + context.serialize(feature.geometry()) + ) + if (properties != null) obj.add( + "properties", + context.serialize(properties) + ) + } + + FEATURECOLLECTION -> { + val fc = + geo as FeatureCollection + obj.add( + "features", + context.serialize( + fc.features(), + Iterable::class.java + ) + ) + } + + else -> {} + } + if (geo.boundingBox() != null) { + val bb = geo.boundingBox() + obj.add("bbox", context.serialize(bb, Iterable::class.java)) + } + if (geo.crs() != null) { + val crs = geo.crs() + val crsobj = JsonObject() + crsobj.addProperty("name", crs!!.type()) + if (crs.size() > 0) crsobj.add( + "properties", + context.serialize(crs.properties()) + ) + obj.add("crs", crsobj) + } + return obj + } + + private fun toPosition(pos: FloatArray): Position { + val b = + Position.Builder() + for (n in pos.indices) { + if (n == 0) b.northing(pos[n]) + else if (n == 1) b.easting(pos[n]) + else if (n == 2) b.altitude(pos[n]) + else b.additional(pos[n]) + } + return b.get() + } + + @Throws(JsonParseException::class) + override fun deserialize( + element: JsonElement, + type: Type, + context: JsonDeserializationContext + ): GeoObject<*> { + var type: Type? = type + var geo: GeoObject.Builder<*, *>? = null + Preconditions.checkArgument(element.isJsonObject) + val obj = element.asJsonObject + Preconditions.checkArgument(obj.has("type")) + val et = + Enums.getIfPresent( + GeoObject.Type::class.java, + obj["type"].asString.uppercase(Locale.getDefault()) + ).orNull() + Preconditions.checkArgument(et != null) + when (et) { + FEATURE -> geo = GeoMakers.feature() + FEATURECOLLECTION -> { + geo = GeoMakers.featureCollection() + type = Feature::class.java + } + + GEOMETRYCOLLECTION -> { + geo = GeoMakers.geometryCollection() + type = Geometry::class.java + } + + LINESTRING -> { + geo = GeoMakers.linestring() + type = Position::class.java + } + + MULTILINESTRING -> { + geo = GeoMakers.multiLineString() + type = LineString::class.java + } + + MULTIPOINT -> { + geo = GeoMakers.multipoint() + type = Position::class.java + } + + MULTIPOLYGON -> { + geo = GeoMakers.multiPolygon() + type = Polygon::class.java + } + + POINT -> { + geo = GeoMakers.point() + type = null + } + + POLYGON -> { + geo = GeoMakers.polygon() + type = LineString::class.java + } + + null -> TODO() + } + + for ((name, el) in obj.entrySet()) { + if ("crs" == name) { + val cb = CRS.Builder() + val o = el.asJsonObject + if (o.has("type")) cb.type(o["type"].asString) + if (o.has("properties")) { + val p = o["properties"].asJsonObject + for ((key, value) in p.entrySet()) { + cb[key] = context.deserialize(value, Any::class.java) + } + } + geo!!.crs(cb.get()) + } else if ("properties" == name) { + geo!!["properties"] = context.deserialize( + el, + MutableMap::class.java + ) + } else if ("bbox" == name) { + val bb = + BoundingBox.Builder() + val points = context.deserialize(el, FloatArray::class.java) + bb.add(*points) + geo!!.boundingBox(bb.get()) + } else if ("features" == name) { + val features = context.deserialize>( + el, + Array::class.java + ) + val fcb = geo as FeatureCollection.Builder? + for (f in features) fcb!!.add(f) + } else if ("coordinates" == name) { + when (et) { + LINESTRING -> { + val lsb = geo as LineString.Builder + val positions = context.deserialize>( + el, + Array::class.java + ) + val ring = ring(positions) + if (ring) lsb.linearRing() + var n = 0 + while (n < positions.size) { + if (!ring || (ring && n < positions.size - 1)) lsb.add(toPosition(positions[n])) + n++ + } + } + + MULTIPOINT -> { + val lsb = geo as MultiPoint.Builder + val positions = context.deserialize>( + el, + Array::class.java + ) + for (pos in positions) lsb.add(toPosition(pos)) + } + + MULTILINESTRING -> { + val mlb = geo as MultiLineString.Builder + val positions = context.deserialize>>( + el, + Array>::class.java + ) + for (lines in positions) { + val lsb = + GeoMakers.linestring() + val ring = ring(lines) + if (ring) lsb.linearRing() + var n = 0 + while (n < lines.size) { + if (!ring || (ring && n < lines.size - 1)) lsb.add(toPosition(lines[n])) + n++ + } + for (pos in lines) lsb.add(toPosition(pos)) + mlb.add(lsb) + } + } + + POLYGON -> { + val mlb = geo as Polygon.Builder + val positions = context.deserialize>>( + el, + Array>::class.java + ) + for (lines in positions) { + val lsb = + GeoMakers.linestring() + for (pos in lines) lsb.add(toPosition(pos)) + mlb.add(lsb) + } + } + + MULTIPOLYGON -> { + val mpb = geo as MultiPolygon.Builder + val positions = context.deserialize>>>( + el, + Array>>::class.java + ) + for (polygons in positions) { + val pb = GeoMakers.polygon() + for (lines in polygons) { + val lsb = + GeoMakers.linestring() + for (pos in lines) lsb.add(toPosition(pos)) + pb.add(lsb) + } + mpb.add(pb) + } + } + + POINT -> { + val pb = geo as Point.Builder + val position = context.deserialize(el, FloatArray::class.java) + pb.position(toPosition(position)) + } + + else -> {} + } + } else if ("geometries" == name) { + val geos = context.deserialize>>( + el, + Array::class.java + ) + val fcb = geo as GeometryCollection.Builder? + for (g in geos) fcb!!.add(g) + } else { + if (el.isJsonArray) { + geo!![name] = context.deserialize(el, Any::class.java) + } else if (el.isJsonObject) { + geo!![name] = context.deserialize(el, GeoObject::class.java) + } else if (el.isJsonPrimitive) { + val p = el.asJsonPrimitive + if (p.isBoolean) geo!![name] = p.asBoolean + else if (p.isNumber) geo!![name] = p.asNumber + else if (p.isString) geo!![name] = p.asString + } + } + } + + return geo!!.get()!! + } + + companion object { + private fun ring(line: Array): Boolean { + return ring(first(line), last(line)) + } + + private fun ring(p1: FloatArray?, p2: FloatArray?): Boolean { + return p1.contentEquals(p2) + } + + private fun first(line: Array): FloatArray? { + if (line.size == 0) return null + return line[0] + } + + private fun last(line: Array): FloatArray? { + if (line.size == 0) return null + return line[line.size - 1] + } + } +} diff --git a/geo/src/main/kotlin/com/ibm/common/geojson/as2/GeoModule.kt b/geo/src/main/kotlin/com/ibm/common/geojson/as2/GeoModule.kt new file mode 100644 index 0000000..57eb3ba --- /dev/null +++ b/geo/src/main/kotlin/com/ibm/common/geojson/as2/GeoModule.kt @@ -0,0 +1,109 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.geojson.as2 + +import com.ibm.common.activitystreams.IO +import com.ibm.common.activitystreams.i.EnumAdapter +import com.ibm.common.activitystreams.i.Model +import com.ibm.common.activitystreams.i.Schema +import com.ibm.common.activitystreams.util.Module +import com.ibm.common.geojson.AS1Position +import com.ibm.common.geojson.Address +import com.ibm.common.geojson.GeoObject +import com.ibm.common.geojson.Place + +/** + * Enables the use of the GeoJSON extensions with Activity Streams 2.0 + * + *
+ * import com.ibm.common.geojson.as2.GeoModule;
+ * import com.ibm.common.activitystreams.IO;
+ *
+ * //...
+ *
+ * IO io = IO.makeDefault(GeoModule.instance);
+ *
+
* + * @author james + */ +@Suppress("deprecation") +class GeoModule + + : Module { + override fun apply( + builder: Schema.Builder + ) { + builder.map("place", place) + .map("address", address) + .map("position", as1Position) + } + + override fun apply( + builder: IO.Builder, + schema: Schema + ) { + val base = + GeoObjectAdapter(schema) + val geo = + GeoAdapter() + builder.hierarchicalAdapter(Place::class.java, base) + .hierarchicalAdapter(Address::class.java, base) + .hierarchicalAdapter(AS1Position::class.java, base) + .hierarchicalAdapter(GeoObject::class.java, geo) + .hierarchicalAdapter( + GeoObject.Type::class.java, + EnumAdapter(GeoObject.Type::class.java) + ) + } + + companion object { + val instance: Module = GeoModule() + + val place: Model = Schema.`object`.template() + .type(Place::class.java, Place.Builder::class.java) + .`as`("geo", GeoObject::class.java) + .`as`("address", Address::class.java) + .`as`("position", AS1Position::class.java) + .get() + + val address: Model = Schema.`object`.template() + .type(Address::class.java, Address.Builder::class.java) + .string( + "country", + "formatted", + "locality", + "postalCode", + "region", + "streetAddress" + ) + .get() + + val as1Position: Model = Schema.`object`.template() + .type(AS1Position::class.java, AS1Position.Builder::class.java) + .floatValue( + "latitude", + "longitude", + "altitude" + ) + .get() + } +} diff --git a/geo/src/main/kotlin/com/ibm/common/geojson/as2/GeoObjectAdapter.kt b/geo/src/main/kotlin/com/ibm/common/geojson/as2/GeoObjectAdapter.kt new file mode 100644 index 0000000..f08e6bc --- /dev/null +++ b/geo/src/main/kotlin/com/ibm/common/geojson/as2/GeoObjectAdapter.kt @@ -0,0 +1,81 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.geojson.as2 + +import com.google.common.collect.ImmutableSet +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.i.ASObjectAdapter +import com.ibm.common.activitystreams.i.Model +import com.ibm.common.activitystreams.i.Schema +import com.ibm.common.geojson.AS1Position +import com.ibm.common.geojson.Address +import com.ibm.common.geojson.GeoMakers +import com.ibm.common.geojson.Place +import java.lang.reflect.Type + +@Suppress("deprecation") +class GeoObjectAdapter + (schema: Schema) : ASObjectAdapter(schema) { + override fun knowsType(type: Type?): Boolean { + if (super.knowsType(type)) return true + return knownTypes.contains(type) + } + + override fun builderFor(type: Type): ASObject.AbstractBuilder<*, *>? { + if (super.knowsType(type)) return super.builderFor(type) + return if (type === Address::class.java) { + GeoMakers.address() + } else if (type === AS1Position::class.java) { + GeoMakers.as1Position() + } else if (type === Place::class.java) { + GeoMakers.place() + } else null + } + + override fun modelFor(type: Type): Model? { + if (super.knowsType(type)) return super.modelFor(type) + return if (type === Address::class.java) { + schema().forObjectClassOrType( + Address.Builder::class.java, + "address" + ) + } else if (type === AS1Position::class.java) { + schema().forObjectClassOrType( + AS1Position.Builder::class.java, + "position" + ) + } else if (type === Place::class.java) { + schema().forObjectClassOrType( + Place.Builder::class.java, + "place" + ) + } else null + } + + companion object { + private val knownTypes: ImmutableSet = ImmutableSet.of( + Address::class.java, + AS1Position::class.java, + Place::class.java + ) + } +} diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..3c5df45 --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,18 @@ +# This file was generated by the Gradle 'init' task. +# https://docs.gradle.org/current/userguide/platforms.html#sub::toml-dependencies-format + +[versions] +com-google-code-gson-gson = "2.2.4" +com-google-guava-guava = "16.0.1" +joda-time-joda-time = "2.3" +junit-junit = "4.11" +org-apache-httpcomponents-httpclient-cache = "4.3.3" +org-apache-httpcomponents-httpcomponents-client = "4.3.3" + +[libraries] +com-google-code-gson-gson = { module = "com.google.code.gson:gson", version.ref = "com-google-code-gson-gson" } +com-google-guava-guava = { module = "com.google.guava:guava", version.ref = "com-google-guava-guava" } +joda-time-joda-time = { module = "joda-time:joda-time", version.ref = "joda-time-joda-time" } +junit-junit = { module = "junit:junit", version.ref = "junit-junit" } +org-apache-httpcomponents-httpclient-cache = { module = "org.apache.httpcomponents:httpclient-cache", version.ref = "org-apache-httpcomponents-httpclient-cache" } +org-apache-httpcomponents-httpcomponents-client = { module = "org.apache.httpcomponents:httpcomponents-client", version.ref = "org-apache-httpcomponents-httpcomponents-client" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..e644113 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..a441313 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.8-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100644 index 0000000..b740cf1 --- /dev/null +++ b/gradlew @@ -0,0 +1,249 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..25da30d --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/legacy/build.gradle.kts b/legacy/build.gradle.kts new file mode 100644 index 0000000..12c4719 --- /dev/null +++ b/legacy/build.gradle.kts @@ -0,0 +1,21 @@ +/* + * This file was generated by the Gradle 'init' task. + */ + +plugins { + + kotlin("jvm") +} + +dependencies { + api(project(":core")) + implementation(kotlin("stdlib-jdk8")) +} + +description = "Activity Streams 2.0 - Legacy objectTypes" +repositories { + mavenCentral() +} +kotlin { + jvmToolchain(11) +} \ No newline at end of file diff --git a/legacy/pom.xml b/legacy/pom.xml deleted file mode 100644 index 25e6f3f..0000000 --- a/legacy/pom.xml +++ /dev/null @@ -1,143 +0,0 @@ - - 4.0.0 - - com.ibm.common - activitystreams - 0.0.1-SNAPSHOT - - activitystreams-legacy - Activity Streams 2.0 - Legacy objectTypes - - - Implementation of Legacy Activity Streams 1.0 objectTypes for - use with the Activity Streams 2.0 Reference Implementation - - - - - Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - UTF-8 - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9.1 - - UTF-8 - UTF-8 - UTF-8 - -XDignore.symbol.file - public - - http://www.joda.org/joda-time/apidocs - http://docs.guava-libraries.googlecode.com/git-history/v16.0.1/javadoc/ - - - - - - maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - - - - - maven-jar-plugin - 2.3.1 - - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - - - - - org.apache.felix - maven-bundle-plugin - 2.3.7 - true - - - bundle-manifest - process-classes - - manifest - - - - - - com.ibm.common.activitystreams.legacy.* - - com.ibm.common.activitystreams.*, - com.google.gson.*, - com.google.common.*, - org.joda.time.* - - - - - - - org.apache.maven.plugins - maven-assembly-plugin - 2.2.2 - - - assembly.xml - - - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - org.apache.felix - maven-bundle-plugin - [2.3.7,) - - manifest - - - - - - - - - - - - - - - - - com.ibm.common - activitystreams-core - 0.0.1-SNAPSHOT - - - \ No newline at end of file diff --git a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/AudioVisual.java b/legacy/src/main/java/com/ibm/common/activitystreams/legacy/AudioVisual.java deleted file mode 100644 index 559635a..0000000 --- a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/AudioVisual.java +++ /dev/null @@ -1,118 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.legacy; - -import java.io.ObjectStreamException; - -import com.google.common.base.Supplier; -import com.ibm.common.activitystreams.ASObject; - -/** - * For the legacy "audio" and "video" objectTypes. These have - * a String "embedCode" property whose value specifies a - * snippet of HTML for embedding the resource and a stream - * MediaLink property. - * - * @author james - */ -public final class AudioVisual - extends ASObject { - - public static final class Builder - extends ASObject.AbstractBuilder { - - /** - * Set the embedCode - * @param embed String - * @return Builder - */ - public Builder embedCode(String embed) { - return set("embedCode", embed); - } - - /** - * Set the stream MediaLink - * @param mediaLink MediaLink - * @return Builder - */ - public Builder stream(MediaLink mediaLink) { - return set("stream", mediaLink); - } - - /** - * Set the stream MediaLink - * @param mediaLink Supplier<MediaLink> - * @return Builder - */ - public Builder stream(Supplier mediaLink) { - return stream(mediaLink.get()); - } - - /** - * Get the built AudioVisual object - */ - public AudioVisual get() { - return new AudioVisual(this); - } - - } - - private AudioVisual(Builder builder) { - super(builder); - } - - /** - * Get the embedCode property. This should be a snippet of HTML - * @return String - */ - public String embedCode() { - return getString("embedCode"); - } - - /** - * Get the stream MediaLink or null if not provided - * @return MediaLink - */ - public MediaLink stream() { - return this.get("stream"); - } - - // Java Serialization Support - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936285L; - protected SerializedForm(AudioVisual obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return super.doReadResolve(); - } - protected AudioVisual.Builder builder() { - return new Builder(); - } - } -} diff --git a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Binary.java b/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Binary.java deleted file mode 100644 index 5ac6e4e..0000000 --- a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Binary.java +++ /dev/null @@ -1,294 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.legacy; - -import java.io.IOException; -import java.io.InputStream; -import java.io.ObjectStreamException; -import java.io.OutputStream; -import java.io.StringReader; -import java.io.StringWriter; - -import com.google.common.hash.Hashing; -import com.google.common.hash.HashingInputStream; -import com.google.common.hash.HashingOutputStream; -import com.google.common.io.BaseEncoding; -import com.google.common.net.MediaType; -import com.ibm.common.activitystreams.ASObject; - -/** - * The legacy "binary" objectType. - * - *
- *   InputStream in = ...
- *   // will base64 encode, gzip compress and md5 sum the input data
- *   // will also set the length property accordingly
- *   Binary binary = 
- *     LegacyMakers.binary()
- *       .gzipData(in)
- *       .get();
- * 
- * - * @author james - * - */ -public final class Binary - extends ASObject { - - public static final class Builder - extends ASObject.AbstractBuilder { - - Builder() { - objectType("binary"); - } - - /** - * Set the input data without any compression. Will automatically - * set calculate the md5 sum and length properties - * @param in InputStream - * @return Builder - * @throws IOException - */ - public Builder data( - InputStream in) - throws IOException { - return data(in,null); - } - - /** - * Set the input data with GZip compression. Will automatically - * set calculate the md5 sum and length properties - * @param in InputStream - * @return Builder - * @throws IOException - */ - public Builder gzipData(InputStream in) throws IOException { - return data(in, Compression.GZipCompression); - } - - /** - * Set the input data with Deflate compression. Will automatically - * set calculate the md5 sum and length properties - * @param in InputStream - * @return Builder - * @throws IOException - */ - public Builder deflateData(InputStream in) throws IOException { - return data(in, Compression.DeflateCompression); - } - - /** - * Set the input data the given Compression. Will automatically - * set calculate the md5 sum and length properties - * @param in InputStream - * @return Builder - * @throws IOException - */ - public Builder data( - InputStream in, - Compression compression) - throws IOException { - StringWriter writer = new StringWriter(); - OutputStream out = - BaseEncoding.base64Url().encodingStream(writer); - if (compression != null) - out = compression.compressor(out); - HashingOutputStream hout = - new HashingOutputStream( - Hashing.md5(), out); - byte[] buf = new byte[1024]; - int r = -1; - long size = 0; - while((r = in.read(buf)) > -1) { - hout.write(buf,0,r); - size += r; - } - set("length", size); - if (compression != null) { - set("compression", compression.label()); - compression.finish(out); - } - hout.close(); - set("md5", hout.hash().toString()); - return set("data",writer.toString()); - } - - /** - * Manually set the md5 properties (this is not recommended. calling the data - * methods will automatically generate the md5 checksum for you) - * - * @param md5 String - * @return Builder - */ - public Builder md5(String md5) { - return set("md5", md5); - } - - /** - * Set the fileUrl property - * @param fileUrl String - * @return Builder - */ - public Builder fileUrl(String fileUrl) { - return set("fileUrl", fileUrl); - } - - /** - * Set the MIME Media Type using the Legacy "mimeType" property name - * rather than the AS 2.0 "mediaType" property name - * @param mt MediaType - * @return Builder - */ - @Override - public Builder mediaType(MediaType mt) { - return set("mimeType", mt); - } - - /** - * Get the built Binary object - */ - public Binary get() { - return new Binary(this); - } - - } - - private Binary(Builder builder) { - super(builder); - } - - /** - * Get the fileUrl property - * @return String - */ - public String fileUrl() { - return getString("fileUrl"); - } - - /** - * Get the length property - * @return long - */ - public long length() { - return getLong("length"); - } - - /** - * Get the compression property value (typically "gzip" or "deflate") - * @return String - */ - public String compression() { - return getString("compression"); - } - - /** - * True if compression = gzip - * @return boolean - */ - public boolean isGzip() { - return "gzip".equalsIgnoreCase(compression()); - } - - /** - * True if compression = deflate - * @return boolean - */ - public boolean isDeflate() { - return "deflate".equalsIgnoreCase(compression()); - } - - /** - * Return the md5 checksum - * @return String - */ - public String md5() { - return getString("md5"); - } - - /** - * Return the literal string content of the data property. - * This will be base64 encoded and optionally compressed - * @return String - */ - public String data() { - return getString("data"); - } - - /** - * Return an InputStream for reading the data. Will - * decompress and base64 decode as necessary - * @return InputStream - * @throws IOException - */ - public InputStream read() throws IOException { - Compression compression = - isGzip() ? Compression.GZipCompression : - isDeflate() ? Compression.DeflateCompression : - null; - return read(compression); - } - - /** - * Return an InputStream for reading the data - * @param compression Compression - * @return InputStream - * @throws IOException - */ - public InputStream read(Compression compression) throws IOException { - StringReader reader = new StringReader(data()); - InputStream in = BaseEncoding.base64Url().decodingStream(reader); - if (compression != null) - in = compression.decompressor(in); - if (has("md5")) - in = new HashingInputStream(Hashing.md5(),in); - return in; - } - - /** - * Return the MIME MediaType using the legacy "mimeType" property name - * rather than the AS 2.0 "mediaType" name - */ - @Override - public MediaType mediaType() { - return this.get("mimeType"); - } - - // Java Serialization Support - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936285L; - protected SerializedForm(Binary obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return super.doReadResolve(); - } - protected Binary.Builder builder() { - return new Builder(); - } - } -} diff --git a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Bookmark.java b/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Bookmark.java deleted file mode 100644 index 313f567..0000000 --- a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Bookmark.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.legacy; - -import java.io.ObjectStreamException; - -import com.ibm.common.activitystreams.ASObject; - -/** - * The legacy "bookmark" objectType - * @author james - */ -public class Bookmark - extends ASObject { - - public static final class Builder - extends ASObject.AbstractBuilder { - - Builder() { - objectType("bookmark"); - } - - /** - * Set the targetUrl property - * @param url String - * @return Builder - */ - public Builder targetUrl(String url) { - return set("targetUrl", url); - } - - /** - * Get the built Bookmark object - */ - public Bookmark get() { - return new Bookmark(this); - } - - } - - private Bookmark(Builder builder) { - super(builder); - } - - /** - * Get the targetUrl property - * @return String - */ - public String targetUrl() { - return getString("targetUrl"); - } - - // Java Serialization Support - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936285L; - protected SerializedForm(Bookmark obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return super.doReadResolve(); - } - protected Bookmark.Builder builder() { - return new Builder(); - } - } -} diff --git a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Compression.java b/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Compression.java deleted file mode 100644 index 08f8912..0000000 --- a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Compression.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.legacy; - -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.zip.DeflaterInputStream; -import java.util.zip.DeflaterOutputStream; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; - -/** - * Compression utility for use with the Binary object - * @author james - * - * @param <O extends OutputStream> - * @param <I extends InputStream> - */ -public interface Compression { - String label(); - O compressor(OutputStream wrap) throws IOException; - I decompressor(InputStream in) throws IOException; - void finish(OutputStream out) throws IOException; - - public static final Compression GZipCompression = - new Compression() { - public String label() { - return "gzip"; - } - public GZIPOutputStream compressor(OutputStream wrap) throws IOException { - return new GZIPOutputStream(wrap); - } - public GZIPInputStream decompressor(InputStream in) throws IOException { - return new GZIPInputStream(in); - } - public void finish(OutputStream out) throws IOException { - if (out instanceof GZIPOutputStream) - ((GZIPOutputStream)out).finish(); - } - }; - - public static final Compression DeflateCompression = - new Compression() { - public String label() { - return "deflate"; - } - public DeflaterOutputStream compressor(OutputStream wrap) - throws IOException { - return new DeflaterOutputStream(wrap); - } - public DeflaterInputStream decompressor(InputStream in) - throws IOException { - return new DeflaterInputStream(in); - } - public void finish(OutputStream out) throws IOException { - if (out instanceof DeflaterOutputStream) - ((DeflaterOutputStream)out).finish(); - } - }; - -} diff --git a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Event.java b/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Event.java deleted file mode 100644 index 40b3c07..0000000 --- a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Event.java +++ /dev/null @@ -1,233 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.legacy; - -import java.io.ObjectStreamException; - -import com.google.common.base.Supplier; -import com.ibm.common.activitystreams.ASObject; -import com.ibm.common.activitystreams.Collection; - -/** - * The legacy "event" objectType - * @author james - */ -public class Event - extends ASObject { - - public static final class Builder - extends ASObject.AbstractBuilder { - - Builder() { - objectType("event"); - } - - /** - * Set the attendedBy Collection property - * @param collection Collection - * @return Builder - */ - public Builder attendedBy(Collection collection) { - return set("attendedBy", collection); - } - - /** - * Set the attendedBy Collection property - * @param collection Collection - * @return Builder - */ - public Builder attendedBy(Supplier collection) { - return attendedBy(collection.get()); - } - - /** - * Set the attending Collection property - * @param collection Collection - * @return Builder - */ - public Builder attending(Collection collection) { - return set("attending", collection); - } - - /** - * Set the attending Collection property - * @param collection Collection - * @return Builder - */ - public Builder attending(Supplier collection) { - return attending(collection.get()); - } - - /** - * Set the invited Collection property - * @param collection Collection - * @return Builder - */ - public Builder invited(Collection collection) { - return set("invited", collection); - } - - /** - * Set the invited Collection property - * @param collection Collection - * @return Builder - */ - public Builder invited(Supplier collection) { - return invited(collection.get()); - } - - /** - * Set the maybeAttending Collection property - * @param collection Collection - * @return Builder - */ - public Builder maybeAttending(Collection collection) { - return set("maybeAttending", collection); - } - - /** - * Set the maybeAttending Collection property - * @param collection Collection - * @return Builder - */ - public Builder maybeAttending(Supplier collection) { - return maybeAttending(collection.get()); - } - - /** - * Set the notAttendedBy Collection property - * @param collection Collection - * @return Builder - */ - public Builder notAttendedBy(Collection collection) { - return set("notAttendedBy", collection); - } - - /** - * Set the notAttendedBy Collection property - * @param collection Collection - * @return Builder - */ - public Builder notAttendedBy(Supplier collection) { - return notAttendedBy(collection.get()); - } - - /** - * Set the notAttending Collection property - * @param collection Collection - * @return Builder - */ - public Builder notAttending(Collection collection) { - return set("notAttending", collection); - } - - /** - * Set the notAttending Collection property - * @param collection Collection - * @return Builder - */ - public Builder notAttending(Supplier collection) { - return notAttending(collection.get()); - } - - /** - * Get the built Event object - * @return Event - */ - public Event get() { - return new Event(this); - } - - } - - private Event(Builder builder) { - super(builder); - } - - /** - * Get the attendedBy Collection or null if not provided - * @return Collection - */ - public Collection attendedBy() { - return this.get("attendedBy"); - } - - /** - * Get the attending Collection or null if not provided - * @return Collection - */ - public Collection attending() { - return this.get("attending"); - } - - /** - * Get the invited Collection or null if not provided - * @return Collection - */ - public Collection invited() { - return this.get("invited"); - } - - /** - * Get the maybeAttending Collection or null if not provided - * @return Collection - */ - public Collection maybeAttending() { - return this.get("maybeAttending"); - } - - /** - * Get the notAttendedBy Collection or null if not provided - * @return Collection - */ - public Collection notAttendedBy() { - return this.get("notAttendedBy"); - } - - /** - * Get the notAttending Collection or null if not provided - * @return Collection - */ - public Collection notAttending() { - return this.get("notAttending"); - } - - // Java Serialization Support - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936285L; - protected SerializedForm(Event obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return super.doReadResolve(); - } - protected Event.Builder builder() { - return new Builder(); - } - } -} diff --git a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/File.java b/legacy/src/main/java/com/ibm/common/activitystreams/legacy/File.java deleted file mode 100644 index cdac245..0000000 --- a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/File.java +++ /dev/null @@ -1,110 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.legacy; - -import java.io.ObjectStreamException; - -import com.google.common.net.MediaType; -import com.ibm.common.activitystreams.ASObject; - -/** - * The legacy "file" objectType - * @author james - */ -public class File - extends ASObject { - - public static final class Builder - extends ASObject.AbstractBuilder { - - Builder() { - objectType("file"); - } - - /** - * Set the fileUrl property - * @param url String - * @return Builder - */ - public Builder fileUrl(String url) { - return set("fileUrl", url); - } - - /** - * Set the MIME mediaType using the legacy "mimeType" property - * name rather than the AS 2.0 "mediaType" property name - */ - @Override - public Builder mediaType(MediaType mt) { - return set("mimeType", mt); - } - - /** - * Get the built File object - */ - public File get() { - return new File(this); - } - - } - - private File(Builder builder) { - super(builder); - } - - /** - * Get the MIME mediaType using the legacy "mimeType" property - * name rather than the AS 2.0 "mediaType" property - */ - @Override - public MediaType mediaType() { - return this.get("mimeType"); - } - - /** - * Get the fileUrl property - * @return - */ - public String fileUrl() { - return getString("fileUrl"); - } - - // Java Serialization Support - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936285L; - protected SerializedForm(File obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return super.doReadResolve(); - } - protected File.Builder builder() { - return new Builder(); - } - } -} diff --git a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Issue.java b/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Issue.java deleted file mode 100644 index 7ef0057..0000000 --- a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Issue.java +++ /dev/null @@ -1,109 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.legacy; - -import java.io.ObjectStreamException; - -import com.google.common.collect.ImmutableList; -import com.ibm.common.activitystreams.ASObject; - -/** - * The legacy "issue" objectType. - * @author james - * - */ -public class Issue - extends ASObject { - - public static final class Builder - extends ASObject.AbstractBuilder { - - Builder() { - objectType("issue"); - } - - /** - * Set the "types" property - * @param type String - * @param types String... optional vararg of additional types to set - * @return Builder - */ - public Builder types(String type, String... types) { - ImmutableList.Builder list = - ImmutableList.builder(); - if (type != null) - list.add(type); - if (types != null) - list.add(types); - return types(list.build()); - } - - /** - * Set the "types" property - * @param types Iterable<String> - * @return Builder - */ - public Builder types(Iterable types) { - return set("types", types); - } - - /** - * Get the built Issue object - */ - public Issue get() { - return new Issue(this); - } - - } - - private Issue(Builder builder) { - super(builder); - } - - /** - * Get the listing of types - * @return Iterable<String> - */ - public Iterable types() { - return this.>get("types"); - } - - // Java Serialization Support ` - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936285L; - protected SerializedForm(Issue obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return super.doReadResolve(); - } - protected Issue.Builder builder() { - return new Builder(); - } - } -} diff --git a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/LegacyMakers.java b/legacy/src/main/java/com/ibm/common/activitystreams/legacy/LegacyMakers.java deleted file mode 100644 index bfdae4c..0000000 --- a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/LegacyMakers.java +++ /dev/null @@ -1,183 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.legacy; - -import com.ibm.common.activitystreams.ASObject; -import static com.ibm.common.activitystreams.Makers.object; - -/** - * Makers for the various Legacy object types - * @author james - */ -public final class LegacyMakers { - - private LegacyMakers() {} - - public static Binary.Builder binary() { - return new Binary.Builder(); - } - - public static Task.Builder task() { - return new Task.Builder(); - } - - public static WithImage.Builder withImage() { - return new WithImage.Builder(); - } - - public static Question.Builder question() { - return new Question.Builder(); - } - - public static WithImage.Builder product() { - return new WithImage.Builder().objectType("product"); - } - - public static WithImage.Builder image() { - return new WithImage.Builder().objectType("image"); - } - - public static File.Builder file() { - return new File.Builder(); - } - - public static Bookmark.Builder bookmark() { - return new Bookmark.Builder(); - } - - public static Bookmark bookmark(String targetUrl) { - return bookmark().targetUrl(targetUrl).get(); - } - - public static Membership.Builder role() { - return new Membership.Builder().objectType("role"); - } - - public static Membership.Builder group() { - return new Membership.Builder().objectType("group"); - } - - public static Issue.Builder issue() { - return new Issue.Builder(); - } - - public static Membership.Builder membership() { - return new Membership.Builder(); - } - - public static Event.Builder event() { - return new Event.Builder(); - } - - public static MediaLink.Builder mediaLink() { - return new MediaLink.Builder(); - } - - public static MediaLink mediaLink(String url) { - return mediaLink().url(url).get(); - } - - public static ASObject.Builder permission() { - return object("permission"); - } - - public static AudioVisual.Builder video() { - return new AudioVisual.Builder().objectType("video"); - } - - public static AudioVisual.Builder audioVisual() { - return new AudioVisual.Builder(); - } - - public static AudioVisual.Builder audio() { - return new AudioVisual.Builder().objectType("audio"); - } - - public static ASObject.Builder alert() { - return object("alert"); - } - - public static ASObject.Builder application() { - return object("application"); - } - - public static ASObject.Builder article() { - return object("article"); - } - - public static ASObject.Builder badge() { - return object("badge"); - } - - public static ASObject.Builder comment() { - return object("comment"); - } - - public static ASObject.Builder device() { - return object("device"); - } - - public static ASObject.Builder game() { - return object("game"); - } - - public static ASObject.Builder job() { - return object("job"); - } - - public static ASObject.Builder note() { - return object("note"); - } - - public static ASObject.Builder offer() { - return object("offer"); - } - - public static ASObject.Builder organization() { - return object("organization"); - } - - public static ASObject.Builder page() { - return object("page"); - } - - public static ASObject.Builder person() { - return object("person"); - } - - public static ASObject.Builder process() { - return object("process"); - } - - public static ASObject.Builder review() { - return object("review"); - } - - public static ASObject.Builder service() { - return object("service"); - } - - public static Membership.Builder team() { - return new Membership.Builder().objectType("team"); - } - -} diff --git a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/LegacyModule.java b/legacy/src/main/java/com/ibm/common/activitystreams/legacy/LegacyModule.java deleted file mode 100644 index b974ccf..0000000 --- a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/LegacyModule.java +++ /dev/null @@ -1,173 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.legacy; - -import java.lang.reflect.Type; - -import com.google.common.net.MediaType; -import com.ibm.common.activitystreams.Collection; -import com.ibm.common.activitystreams.IO; -import com.ibm.common.activitystreams.internal.Model; -import com.ibm.common.activitystreams.internal.Schema; -import com.ibm.common.activitystreams.internal.Schema.Builder; -import com.ibm.common.activitystreams.util.Module; - -/** - * Adds support for legacy objectTypes defined by the original - * Activity Streams 1.0 Schema (see https://github.com/activitystreams/activity-schema/blob/master/activity-schema.md) - * - *
- *   import com.ibm.common.activitystreams.IO;
- *   import com.ibm.common.activitystreams.legacy.LegacyModule;
- *   
- *   //...
- *   
- *   IO io = IO.makeDefault(LegacyModule.instance);
- *   
- * 
- * @author james - * - */ -public final class LegacyModule - implements Module { - - public static final Module instance = new LegacyModule(); - - public static final Model binary = - Schema.object.template() - .type(Binary.class, Binary.Builder.class) - .string("compression", "md5", "data", "fileUrl") - .as("mimeType", MediaType.class) - .integer("length") - .get(); - - public static final Model audioVisual = - Schema.object.template() - .type(AudioVisual.class, AudioVisual.Builder.class) - .string("embedCode") - .as("stream", MediaLink.class) - .get(); - - public static final Model withImage = - Schema.object.template() - .type(WithImage.class, WithImage.Builder.class) - .as("fullImage", MediaLink.class) - .get(); - - public static final Model bookmark = - Schema.object.template() - .type(Bookmark.class, Bookmark.Builder.class) - .string("targetUrl") - .get(); - - public static final Model event = - Schema.object.template() - .type(Event.class, Event.Builder.class) - .as("attendedBy", Collection.class) - .as("attending", Collection.class) - .as("invited", Collection.class) - .as("maybeAttending", Collection.class) - .as("notAttendedBy", Collection.class) - .as("notAttending", Collection.class) - .get(); - - public static final Model membership = - Schema.object.template() - .type(Membership.class, Membership.Builder.class) - .as("members", Collection.class) - .get(); - - public static final Model file = - Schema.object.template() - .type(File.class, File.Builder.class) - .string("fileUrl") - .as("mimeType", MediaType.class) - .get(); - - public static final Model issue = - Schema.object.template() - .type(Issue.class, Issue.Builder.class) - .string("types") - .get(); - - public static final Model question = - Schema.object.template() - .type(Question.class, Question.Builder.class) - .linkValue("options") - .get(); - - public static final Model task = - Schema.object.template() - .type(Task.class, Task.Builder.class) - .object("actor", "object") - .dateTime("by") - .as("required", Boolean.class) - .string("verb") - .as("prerequisites", Task.class) - .as("supersedes", Task.class) - .get(); - - public void apply(Builder builder) { - builder.map("alert", Schema.object) - .map("binary", binary) - .map("application", Schema.object) - .map("article", Schema.object) - .map("audio", audioVisual) - .map("badge", Schema.object) - .map("bookmark",bookmark) - .map("comment", Schema.object) - .map("device", Schema.object) - .map("event", event) - .map("file", file) - .map("game", Schema.object) - .map("group", membership) - .map("image", withImage) - .map("issue", issue) - .map("job", Schema.object) - .map("note", Schema.object) - .map("offer", Schema.object) - .map("organization", Schema.object) - .map("page", Schema.object) - .map("person", Schema.object) - .map("process", Schema.object) - .map("product", Schema.object) - .map("question", question) - .map("review", Schema.object) - .map("role", membership) - .map("service", Schema.object) - .map("team", membership) - .map("video", audioVisual) - ; - } - - @SuppressWarnings({ "unchecked", "rawtypes" }) - public void apply( - IO.Builder builder, - Schema schema) { - LegacyObjectAdapter base = - new LegacyObjectAdapter(schema); - builder.adapter(MediaLink.class, new MediaLinkAdapter()); - for (Type type : LegacyObjectAdapter.knownTypes) - builder.hierarchicalAdapter((Class)type, base); - } - -} diff --git a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/LegacyObjectAdapter.java b/legacy/src/main/java/com/ibm/common/activitystreams/legacy/LegacyObjectAdapter.java deleted file mode 100644 index f279286..0000000 --- a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/LegacyObjectAdapter.java +++ /dev/null @@ -1,119 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.legacy; - -import java.lang.reflect.Type; - -import com.google.common.collect.ImmutableSet; -import com.ibm.common.activitystreams.ASObject.AbstractBuilder; -import com.ibm.common.activitystreams.internal.ASObjectAdapter; -import com.ibm.common.activitystreams.internal.Model; -import com.ibm.common.activitystreams.internal.Schema; -import static com.ibm.common.activitystreams.Makers.object; - -public class LegacyObjectAdapter - extends ASObjectAdapter { - - protected LegacyObjectAdapter(Schema schema) { - super(schema); - } - - @SuppressWarnings("unchecked") - public static final ImmutableSet knownTypes = - ImmutableSet.of( - Binary.class, - AudioVisual.class, - Bookmark.class, - Event.class, - File.class, - Issue.class, - Membership.class, - Question.class, - Task.class, - WithImage.class); - - @Override - protected boolean knowsType(Type type) { - if (super.knowsType(type)) - return true; - return knownTypes.contains(type); - } - - @Override - protected AbstractBuilder builderFor(Type type) { - if (super.knowsType(type)) - return super.builderFor(type); - if (knowsType(type)) { - if (type == AudioVisual.class) - return LegacyMakers.audioVisual(); - else if (type == Binary.class) - return LegacyMakers.binary(); - else if (type == Bookmark.class) - return LegacyMakers.bookmark(); - else if (type == Event.class) - return LegacyMakers.event(); - else if (type == File.class) - return LegacyMakers.file(); - else if (type == Issue.class) - return LegacyMakers.issue(); - else if (type == Membership.class) - return LegacyMakers.membership(); - else if (type == Question.class) - return LegacyMakers.question(); - else if (type == Task.class) - return LegacyMakers.task(); - else if (type == WithImage.class) - return LegacyMakers.withImage(); - else return object(); - } else return null; - } - - @Override - protected Model modelFor(Type type) { - if (super.knowsType(type)) - return super.modelFor(type); - if (knowsType(type)) { - if (type == AudioVisual.class) - return LegacyModule.audioVisual; - else if (type == Bookmark.class) - return LegacyModule.bookmark; - else if (type == Binary.class) - return LegacyModule.binary; - else if (type == Event.class) - return LegacyModule.event; - else if (type == File.class) - return LegacyModule.file; - else if (type == Issue.class) - return LegacyModule.issue; - else if (type == Membership.class) - return LegacyModule.membership; - else if (type == Question.class) - return LegacyModule.question; - else if (type == Task.class) - return LegacyModule.task; - else if (type == WithImage.class) - return LegacyModule.withImage; - else return Schema.object; - } else return null; - } - -} diff --git a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/MediaLink.java b/legacy/src/main/java/com/ibm/common/activitystreams/legacy/MediaLink.java deleted file mode 100644 index 6d1d11e..0000000 --- a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/MediaLink.java +++ /dev/null @@ -1,199 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.legacy; - -import java.io.ObjectStreamException; -import java.io.Serializable; -import java.util.Iterator; -import java.util.Map; - -import com.google.common.base.Supplier; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import com.ibm.common.activitystreams.util.AbstractWritable; - -/** - * An Activity Streams 1.0 Media Link object. - * @author james - * - */ -public final class MediaLink - extends AbstractWritable - implements Iterable, Serializable { - - public static final class Builder - extends AbstractWritableBuilder - implements Supplier { - - private Map map = - Maps.newHashMap(); - - /** - * When the media link refers to a video or audio resource, - * the duration property indicates the total length in seconds - * @param duration int - * @return Builder - */ - public Builder duration(int duration) { - map.put("duration", duration); - return this; - } - - /** - * When the media link refers to an object intended to be - * displayed visually, such as a video or image, the - * height property specifies the display height in terms - * of device independent pixels. - * @param height int - * @return Builder - */ - public Builder height(int height) { - map.put("height", height); - return this; - } - - /** - * When the media link refers to an object intended to be - * displayed visually, such as a video or image, the - * width property specifies the display width in terms - * of device independent pixels. - * @param height int - * @return Builder - */ - public Builder width(int width) { - map.put("width", width); - return this; - } - - /** - * The URL of the resource - * @param url String - * @return Builder - */ - public Builder url(String url) { - map.put("url", url); - return this; - } - - /** - * Set an arbitrary property on the Media Link - * @param key String - * @param val Object - * @return Builder - */ - public Builder set(String key, Object val) { - map.put(key,val); - return this; - } - - /** - * Get the built MediaLink object - */ - public MediaLink get() { - return new MediaLink(this); - } - - } - - private final ImmutableMap map; - - private MediaLink(Builder builder) { - super(builder); - this.map = ImmutableMap.copyOf(builder.map); - } - - /** - * Get the url property - * @return - */ - public String url() { - return (String)map.get("url"); - } - - /** - * When the media link refers to a video or audio resource, - * the duration property indicates the total length in seconds - * @return int - */ - public int duration() { - return (Integer)map.get("duration"); - } - - /** - * When the media link refers to an object intended to be - * displayed visually, such as a video or image, the - * height property specifies the display height in terms - * of device independent pixels. - * @return int - */ - public int height() { - return (Integer)map.get("height"); - } - - /** - * When the media link refers to an object intended to be - * displayed visually, such as a video or image, the - * width property specifies the display width in terms - * of device independent pixels. - * @return int - */ - public int width() { - return (Integer)map.get("width"); - } - - /** - * Return the given property - * @param key - * @return <T>T - */ - @SuppressWarnings("unchecked") - public T get(String key) { - return (T)map.get(key); - } - - public Iterator iterator() { - return map.keySet().iterator(); - } - - // Java Serialization Support - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - implements Serializable { - private static final long serialVersionUID = -2060301713159936285L; - - private ImmutableMap map; - - protected SerializedForm(MediaLink obj) { - this.map = obj.map; - } - Object readResolve() throws ObjectStreamException { - MediaLink.Builder builder = - new Builder(); - builder.map.putAll(map); - return builder.get(); - } - } -} diff --git a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/MediaLinkAdapter.java b/legacy/src/main/java/com/ibm/common/activitystreams/legacy/MediaLinkAdapter.java deleted file mode 100644 index c7eea24..0000000 --- a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/MediaLinkAdapter.java +++ /dev/null @@ -1,85 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.legacy; - -import java.lang.reflect.Type; -import java.util.Map; - -import static com.google.common.base.Preconditions.checkArgument; - -import com.google.gson.JsonDeserializationContext; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import com.google.gson.JsonParseException; -import com.google.gson.JsonSerializationContext; -import com.ibm.common.activitystreams.ASObject; -import static com.ibm.common.activitystreams.internal.ASObjectAdapter.primConverter; -import com.ibm.common.activitystreams.internal.Adapter; - -public final class MediaLinkAdapter - extends Adapter { - - public JsonElement serialize( - MediaLink src, - Type typeOfSrc, - JsonSerializationContext context) { - JsonObject el = new JsonObject(); - for (String key : src) { - Object val = src.get(key); - if (val != null) - el.add(key, context.serialize(val, val.getClass())); - } - return el; - } - - public MediaLink deserialize( - JsonElement json, - Type typeOfT, - JsonDeserializationContext context) - throws JsonParseException { - - checkArgument(json.isJsonObject()); - JsonObject obj = (JsonObject) json; - MediaLink.Builder builder = - LegacyMakers.mediaLink(); - for (Map.Entry entry : obj.entrySet()) { - String name = entry.getKey(); - JsonElement val = entry.getValue(); - if (val.isJsonPrimitive()) - builder.set( - name, - primConverter.convert(val.getAsJsonPrimitive())); - else if (val.isJsonArray()) - builder.set( - name, - context.deserialize(val, Iterable.class)); - else if (val.isJsonObject()) - builder.set( - name, - context.deserialize( - val, - ASObject.class)); - } - return builder.get(); - } - -} diff --git a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Membership.java b/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Membership.java deleted file mode 100644 index 2fc43c5..0000000 --- a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Membership.java +++ /dev/null @@ -1,101 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.legacy; - -import java.io.ObjectStreamException; - -import com.google.common.base.Supplier; -import com.ibm.common.activitystreams.ASObject; -import com.ibm.common.activitystreams.Collection; - -/** - * For the legacy "role", "group" and "team" objectTypes. - * Membership objects include an additional "members" - * collection property. - * - * @author james - * - */ -public class Membership extends ASObject { - - public static final class Builder - extends ASObject.AbstractBuilder { - - /** - * Set the members collection - * @param collection Collection - * @return Builder - */ - public Builder members(Collection collection) { - return set("members", collection); - } - - /** - * Set the members collection - * @param collection Collection - * @return Builder - */ - public Builder members(Supplier collection) { - return members(collection.get()); - } - - /** - * Get the built Membership object - */ - public Membership get() { - return new Membership(this); - } - - } - - private Membership(Builder builder) { - super(builder); - } - - /** - * Return the members collection - * @return Collection - */ - public Collection members() { - return this.get("members"); - } - - // Java Serialization Support - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936285L; - protected SerializedForm(Membership obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return super.doReadResolve(); - } - protected Membership.Builder builder() { - return new Builder(); - } - } -} diff --git a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Question.java b/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Question.java deleted file mode 100644 index c2f8b18..0000000 --- a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Question.java +++ /dev/null @@ -1,140 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.legacy; - -import java.io.ObjectStreamException; - -import com.google.common.base.Predicate; -import com.google.common.base.Supplier; -import com.ibm.common.activitystreams.ASObject; -import com.ibm.common.activitystreams.LinkValue; - -/** - * The legacy "question" object. Question objects - * have an additional "options" property that lists - * the possible answers to the question. - * - * This implementation varies from the Legacy AS 1.0 - * model in that it allows AS 2.0 style LinkValues - * to be used as the value of the options property. - * - * @author james - * - */ -public class Question extends ASObject { - - public static final class Builder - extends ASObject.AbstractBuilder { - - Builder() { - objectType("question"); - } - - /** - * Add one or more answers to the question - * @param url String - * @param urls String[] optional vararg - * @return Builder - */ - public Builder option(String url, String... urls) { - if (url != null) - link("options", url); - if (urls != null) - for (String u : urls) - link("options", u); - return this; - } - - /** - * Add one or more answers to the question - * @param url LinkValue - * @param urls LinkValue[] optional vararg - * @return Builder - */ - public Builder option(LinkValue link, LinkValue... links) { - if (link != null) - link("options", link); - if (links != null) - for (LinkValue l : links) - link("options", l); - return this; - } - - /** - * Add an answer to the question - * @param link Supplier<? extends LinkValue> - * @return Builder - */ - public Builder option(Supplier link) { - return option(link.get()); - } - - /** - * Get the built question object - */ - public Question get() { - return new Question(this); - } - - } - - public Question(Builder builder) { - super(builder); - } - - /** - * Get the list of options for the question - * @return Iterable<LinkValue> - */ - public Iterable options() { - return links("options"); - } - - /** - * Get the list of options for the question - * @param filter Predicate<? super LinkValue> - * @return Iterable<LinkValue> - */ - public Iterable options(Predicate filter) { - return links("options", filter); - } - - // Java Serialization Support - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936285L; - protected SerializedForm(Question obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return super.doReadResolve(); - } - protected Question.Builder builder() { - return new Builder(); - } - } -} diff --git a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Task.java b/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Task.java deleted file mode 100644 index 679f9c1..0000000 --- a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/Task.java +++ /dev/null @@ -1,354 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.legacy; - -import static com.google.common.collect.Iterables.transform; - -import java.io.ObjectStreamException; - -import org.joda.time.DateTime; -import org.joda.time.ReadableDuration; -import org.joda.time.ReadablePeriod; - -import com.google.common.base.Function; -import com.google.common.base.Predicate; -import com.google.common.base.Supplier; -import com.ibm.common.activitystreams.ASObject; -import com.ibm.common.activitystreams.LinkValue; - -/** - * The Legacy "task" objectType. Task objects in AS 1.0 are essentially - * pending Activity statements. - * @author james - * - */ -public class Task - extends ASObject { - - public static final class Builder - extends ASObject.AbstractBuilder { - - Builder() { - objectType("task"); - } - - /** - * Set the actor - * @param actor ASObject - * @return Builder - */ - public Builder actor(ASObject actor) { - return set("actor", actor); - } - - /** - * Set the actor - * @param actor Supplier<? extends ASObject> - * @return Builder - */ - public Builder actor(Supplier actor) { - return actor(actor.get()); - } - - /** - * Set the object - * @param object ASObject - * @return Builder - */ - public Builder object(ASObject object) { - return set("object", object); - } - - /** - * Set the object - * @param object Supplier<? extends ASObject> - * @return Builder - */ - public Builder object(Supplier object) { - return object(object.get()); - } - - /** - * Set one or more prerequisite taskss - * @param task Task - * @param tasks Task[] optional vararg - * @return Builder - */ - public Builder prerequisites(Task task, Task... tasks) { - if (task != null) - link("prerequisites",task); - if (tasks != null) - for (Task t : tasks) - link("prerequisites", t); - return this; - } - - /** - * Set one or more prerequisite tasks - * @param tasks Iterable<Task> - * @return Builder - */ - public Builder prerequisites(Iterable tasks) { - if (tasks != null) - for (Task task : tasks) - link("prerequisites", task); - return this; - } - - /** - * Set an optional prerequisite - * @param task Supplier<? extends Task> - * @return Builder - */ - public Builder prerequisites(Supplier task) { - return prerequisites(task.get()); - } - - /** - * Specify one or more other tasks that this task supersedes - * @param task Task - * @param tasks Task[] optional vararg - * @return Builder - */ - public Builder supersedes(Task task, Task... tasks) { - if (task != null) - link("supersedes",task); - if (tasks != null) - for (Task t : tasks) - link("supersedes", t); - return this; - } - - /** - * Specify one or more other tasks that this task supersedes - * @param tasks Iterable<Task> - * @return Builder - */ - public Builder supersedes(Iterable tasks) { - if (tasks != null) - for (Task task : tasks) - link("supersedes", task); - return this; - } - - /** - * Specify a task that this task supersedes - * @param task Supplier<? extends Task> - * @return Builder - */ - public Builder supersedes(Supplier task) { - return supersedes(task.get()); - } - - /** - * Indicates whether this task is required or not - * @param on boolean - * @return Builder - */ - public Builder required(boolean on) { - return set("required", on); - } - - /** - * Indicates that this task is required - * @return Builder - */ - public Builder required() { - return required(true); - } - - /** - * Specifies the verb for this task - * @param verb String - * @return Builder - */ - public Builder verb(String verb) { - return set("verb", verb); - } - - /** - * Specifies the due date for this task - * @param dt DateTime - * @return Builder - */ - public Builder by(DateTime dt) { - return this._dt("by", dt); - } - - /** - * Specifies that this task is due right now - * @return Builder - */ - public Builder byNow() { - return this._dtNow("by"); - } - - /** - * Specifies the due date for this task in terms of a specific - * duration of time from right now - * @param duration ReadableDuration - * @return Builder - */ - public Builder byFromNow(ReadableDuration duration) { - return this._dtFromNow("by", duration); - } - - /** - * Specifies the due date for this task in terms of a specific - * period of time from right now - * @param period ReadablePeriod - * @return Builder - */ - public Builder byFromNow(ReadablePeriod period) { - return this._dtFromNow("by", period); - } - - /** - * Specifies the due date for this task in terms of a specific - * duration of time from the given instant; - * @param dt DateTime - * @param duration ReadableDuration - * @return Builder - */ - public Builder by(DateTime dt, ReadableDuration duration) { - return this._dtFrom("by", dt, duration); - } - - /** - * Specifies the due date for this task in terms of a specific - * period of time from the given instant - * @param dt DateTime - * @param period ReadablePeriod - * @return Builder - */ - public Builder by(DateTime dt, ReadablePeriod period) { - return this._dtFrom("by", dt, period); - } - - /** - * Get the completed Task object - */ - public Task get() { - return new Task(this); - } - - } - - private Task(Builder builder) { - super(builder); - } - - /** - * Get the actor - * @return <A extends ASObject>A - */ - public
A actor() { - return this.get("actor"); - } - - /** - * Get the object - * @return <A extends ASObject>A - */ - public A object() { - return this.get("object"); - } - - /** - * Get the due date - * @return DateTime - */ - public DateTime by() { - return getDateTime("by"); - } - - /** - * Get the verb - * @return String - */ - public String verb() { - return getString("verb"); - } - - /** - * Return true if this task is required - * @return boolean - */ - public boolean required() { - return getBoolean("required"); - } - - /** - * Return the listing of other tasks superseded by this one - * (will return an empty iterable if there are no superseded - * tasks) - * @return Iterable<Task> - */ - public Iterable supersedes() { - return transform(links("supersedes",filter), transformer); - } - - /** - * Return the listing of other tasks upon which this task depends. - * (will return an empty iterable if there are no prerequisite - * tasks) - * @return Iterable<Task> - */ - public Iterable prerequisites() { - return transform(links("prerequisites",filter), transformer); - } - - private static final Predicate filter = - new Predicate() { - public boolean apply(LinkValue input) { - return input instanceof Task; - } - }; - - private static final Function transformer = - new Function() { - public Task apply(LinkValue input) { - return (Task)input; - } - - }; - - // Java Serialization Support - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936285L; - protected SerializedForm(Task obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return super.doReadResolve(); - } - protected Task.Builder builder() { - return new Builder(); - } - } -} diff --git a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/WithImage.java b/legacy/src/main/java/com/ibm/common/activitystreams/legacy/WithImage.java deleted file mode 100644 index 1d90428..0000000 --- a/legacy/src/main/java/com/ibm/common/activitystreams/legacy/WithImage.java +++ /dev/null @@ -1,97 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.legacy; - -import java.io.ObjectStreamException; - -import com.google.common.base.Supplier; -import com.ibm.common.activitystreams.ASObject; - -/** - * For the legacy "product" and "image" objectTypes. These - * include an additional "fullImage" property whose value - * is a MediaLink. - * - * @author james - * - */ -public class WithImage extends ASObject { - - public static final class Builder - extends ASObject.AbstractBuilder { - - /** - * Set the fullImage property - * @param link MediaLink - * @return Builder - */ - public Builder fullImage(MediaLink link) { - return set("fullImage", link); - } - - /** - * Set the fullImage property - * @param link Supplier<? extends MediaLink> - * @return Builder - */ - public Builder fullImage(Supplier link) { - return fullImage(link.get()); - } - - public WithImage get() { - return new WithImage(this); - } - - } - - private WithImage(Builder builder) { - super(builder); - } - - /** - * Get the fullImage property - * @return MediaLink - */ - public MediaLink fullImage() { - return this.get("fullImage"); - } - - // Java Serialization Support - - Object writeReplace() throws java.io.ObjectStreamException { - return new SerializedForm(this); - } - - private static class SerializedForm - extends AbstractSerializedForm { - private static final long serialVersionUID = -2060301713159936285L; - protected SerializedForm(WithImage obj) { - super(obj); - } - Object readResolve() throws ObjectStreamException { - return super.doReadResolve(); - } - protected WithImage.Builder builder() { - return new Builder(); - } - } -} diff --git a/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/AudioVisual.kt b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/AudioVisual.kt new file mode 100644 index 0000000..b580122 --- /dev/null +++ b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/AudioVisual.kt @@ -0,0 +1,113 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.legacy + +import com.google.common.base.Supplier +import com.ibm.common.activitystreams.ASObject +import java.io.ObjectStreamException + +/** + * For the legacy "audio" and "video" objectTypes. These have + * a String "embedCode" property whose value specifies a + * snippet of HTML for embedding the resource and a stream + * MediaLink property. + * + * @author james + */ +class AudioVisual +private constructor(builder: Builder) : ASObject(builder) { + class Builder + + : AbstractBuilder() { + /** + * Set the embedCode + * @param embed String + * @return Builder + */ + fun embedCode(embed: String?): Builder? { + return set("embedCode", embed) + } + + /** + * Set the stream MediaLink + * @param mediaLink MediaLink + * @return Builder + */ + fun stream(mediaLink: MediaLink?): Builder? { + return set("stream", mediaLink) + } + + /** + * Set the stream MediaLink + * @param mediaLink Supplier<MediaLink> + * @return Builder + */ + fun stream(mediaLink: Supplier): Builder? { + return stream(mediaLink.get()) + } + + /** + * Get the built AudioVisual object + */ + override fun get(): AudioVisual { + return AudioVisual(this) + } + } + + /** + * Get the embedCode property. This should be a snippet of HTML + * @return String + */ + fun embedCode(): String? { + return getString("embedCode") + } + + /** + * Get the stream MediaLink or null if not provided + * @return MediaLink + */ + fun stream(): MediaLink? { + return this.get("stream") + } + + // Java Serialization Support + @Throws(ObjectStreamException::class) + override fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: AudioVisual?) : AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + override fun builder(): Builder { + return Builder() + } + + companion object { + private const val serialVersionUID = -2060301713159936285L + } + } +} diff --git a/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Binary.kt b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Binary.kt new file mode 100644 index 0000000..df7956a --- /dev/null +++ b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Binary.kt @@ -0,0 +1,276 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.legacy + +import com.google.common.hash.Hashing +import com.google.common.hash.HashingInputStream +import com.google.common.hash.HashingOutputStream +import com.google.common.io.BaseEncoding +import com.google.common.net.MediaType +import com.ibm.common.activitystreams.ASObject +import java.io.* + +/** + * The legacy "binary" objectType. + * + *
+ * InputStream in = ...
+ * // will base64 encode, gzip compress and md5 sum the input data
+ * // will also set the length property accordingly
+ * Binary binary =
+ * LegacyMakers.binary()
+ * .gzipData(in)
+ * .get();
+
* + * + * @author james + */ +class Binary +private constructor(builder: Builder) : ASObject(builder) { + class Builder + internal constructor() : + AbstractBuilder() { + init { + objectType("binary") + } + + /** + * Set the input data with GZip compression. Will automatically + * set calculate the md5 sum and length properties + * @param in InputStream + * @return Builder + * @throws IOException + */ + @Throws(IOException::class) + fun gzipData(`in`: InputStream): Builder? { + return data(`in`, Compression.Companion.GZipCompression) + } + + /** + * Set the input data with Deflate compression. Will automatically + * set calculate the md5 sum and length properties + * @param in InputStream + * @return Builder + * @throws IOException + */ + @Throws(IOException::class) + fun deflateData(`in`: InputStream): Builder? { + return data(`in`, Compression.Companion.DeflateCompression) + } + + /** + * Set the input data the given Compression. Will automatically + * set calculate the md5 sum and length properties + * @param in InputStream + * @return Builder + * @throws IOException + */ + /** + * Set the input data without any compression. Will automatically + * set calculate the md5 sum and length properties + * @param in InputStream + * @return Builder + * @throws IOException + */ + @JvmOverloads + @Throws(IOException::class) + fun data( + `in`: InputStream, + compression: Compression<*, *>? = null + ): Builder? { + val writer = StringWriter() + var out = + BaseEncoding.base64Url().encodingStream(writer) + if (compression != null) out = compression.compressor(out) + val hout = + HashingOutputStream( + Hashing.md5(), out + ) + val buf = ByteArray(1024) + var r = -1 + var size: Long = 0 + while ((`in`.read(buf).also { r = it }) > -1) { + hout.write(buf, 0, r) + size += r.toLong() + } + set("length", size) + if (compression != null) { + set("compression", compression.label()) + compression.finish(out) + } + hout.close() + set("md5", hout.hash().toString()) + return set("data", writer.toString()) + } + + /** + * Manually set the md5 properties (this is not recommended. calling the data + * methods will automatically generate the md5 checksum for you) + * + * @param md5 String + * @return Builder + */ + fun md5(md5: String?): Builder? { + return set("md5", md5) + } + + /** + * Set the fileUrl property + * @param fileUrl String + * @return Builder + */ + fun fileUrl(fileUrl: String?): Builder? { + return set("fileUrl", fileUrl) + } + + /** + * Set the MIME Media Type using the Legacy "mimeType" property name + * rather than the AS 2.0 "mediaType" property name + * @param mt MediaType + * @return Builder + */ + override fun mediaType(mt: MediaType?): Builder { + return set("mimeType", mt)!! + } + + /** + * Get the built Binary object + */ + override fun get(): Binary { + return Binary(this) + } + } + + /** + * Get the fileUrl property + * @return String + */ + fun fileUrl(): String? { + return getString("fileUrl") + } + + /** + * Get the length property + * @return long + */ + fun length(): Long { + return getLong("length") + } + + /** + * Get the compression property value (typically "gzip" or "deflate") + * @return String + */ + fun compression(): String? { + return getString("compression") + } + + val isGzip: Boolean + /** + * True if compression = gzip + * @return boolean + */ + get() = "gzip".equals(compression(), ignoreCase = true) + + val isDeflate: Boolean + /** + * True if compression = deflate + * @return boolean + */ + get() = "deflate".equals(compression(), ignoreCase = true) + + /** + * Return the md5 checksum + * @return String + */ + fun md5(): String? { + return getString("md5") + } + + /** + * Return the literal string content of the data property. + * This will be base64 encoded and optionally compressed + * @return String + */ + fun data(): String? { + return getString("data") + } + + /** + * Return an InputStream for reading the data. Will + * decompress and base64 decode as necessary + * @return InputStream + * @throws IOException + */ + @Throws(IOException::class) + fun read(): InputStream? { + val compression: Compression<*, *>? = + if (isGzip) Compression.Companion.GZipCompression else if (isDeflate) Compression.Companion.DeflateCompression else null + return read(compression) + } + + /** + * Return an InputStream for reading the data + * @param compression Compression + * @return InputStream + * @throws IOException + */ + @Throws(IOException::class) + fun read(compression: Compression<*, *>?): InputStream? { + val reader = StringReader(data()) + var `in` = BaseEncoding.base64Url().decodingStream(reader) + if (compression != null) `in` = compression.decompressor(`in`) + if (has("md5")) `in` = HashingInputStream(Hashing.md5(), `in`) + return `in` + } + + /** + * Return the MIME MediaType using the legacy "mimeType" property name + * rather than the AS 2.0 "mediaType" name + */ + override fun mediaType(): MediaType? { + return this.get("mimeType") + } + + // Java Serialization Support + @Throws(ObjectStreamException::class) + override fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: Binary?) : + AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + override fun builder(): Builder { + return Builder() + } + + companion object { + private const val serialVersionUID = -2060301713159936285L + } + } +} diff --git a/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Bookmark.kt b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Bookmark.kt new file mode 100644 index 0000000..44eba25 --- /dev/null +++ b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Bookmark.kt @@ -0,0 +1,87 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.legacy + +import com.ibm.common.activitystreams.ASObject +import java.io.ObjectStreamException + +/** + * The legacy "bookmark" objectType + * @author james + */ +class Bookmark +private constructor(builder: Builder) : ASObject(builder) { + class Builder + internal constructor() : + AbstractBuilder() { + init { + objectType("bookmark") + } + + /** + * Set the targetUrl property + * @param url String + * @return Builder + */ + fun targetUrl(url: String?): Builder? { + return set("targetUrl", url) + } + + /** + * Get the built Bookmark object + */ + override fun get(): Bookmark { + return Bookmark(this) + } + } + + /** + * Get the targetUrl property + * @return String + */ + fun targetUrl(): String? { + return getString("targetUrl") + } + + // Java Serialization Support + @Throws(ObjectStreamException::class) + override fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: Bookmark?) : + AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + override fun builder(): Builder { + return Builder() + } + + companion object { + private const val serialVersionUID = -2060301713159936285L + } + } +} diff --git a/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Compression.kt b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Compression.kt new file mode 100644 index 0000000..90d1437 --- /dev/null +++ b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Compression.kt @@ -0,0 +1,96 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.legacy + +import java.io.IOException +import java.io.InputStream +import java.io.OutputStream +import java.util.zip.DeflaterInputStream +import java.util.zip.DeflaterOutputStream +import java.util.zip.GZIPInputStream +import java.util.zip.GZIPOutputStream + +/** + * Compression utility for use with the Binary object + * @author james + * + * @param <O extends OutputStream> + * @param <I extends InputStream> + */ +interface Compression { + fun label(): String + + @Throws(IOException::class) + fun compressor(wrap: OutputStream?): O + + @Throws(IOException::class) + fun decompressor(`in`: InputStream?): I + + @Throws(IOException::class) + fun finish(out: OutputStream?) + + companion object { + val GZipCompression: Compression = + object : Compression { + override fun label(): String { + return "gzip" + } + + @Throws(IOException::class) + override fun compressor(wrap: OutputStream?): GZIPOutputStream { + return GZIPOutputStream(wrap) + } + + @Throws(IOException::class) + override fun decompressor(`in`: InputStream?): GZIPInputStream { + return GZIPInputStream(`in`) + } + + @Throws(IOException::class) + override fun finish(out: OutputStream?) { + if (out is GZIPOutputStream) out.finish() + } + } + + val DeflateCompression: Compression = + object : Compression { + override fun label(): String { + return "deflate" + } + + @Throws(IOException::class) + override fun compressor(wrap: OutputStream?): DeflaterOutputStream { + return DeflaterOutputStream(wrap) + } + + @Throws(IOException::class) + override fun decompressor(`in`: InputStream?): DeflaterInputStream { + return DeflaterInputStream(`in`) + } + + @Throws(IOException::class) + override fun finish(out: OutputStream?) { + if (out is DeflaterOutputStream) out.finish() + } + } + } +} diff --git a/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Event.kt b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Event.kt new file mode 100644 index 0000000..f72aa2f --- /dev/null +++ b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Event.kt @@ -0,0 +1,229 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.legacy + +import com.google.common.base.Supplier +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.Collection +import java.io.ObjectStreamException + +/** + * The legacy "event" objectType + * @author james + */ +class Event +private constructor(builder: Builder) : ASObject(builder) { + class Builder + internal constructor() : + AbstractBuilder() { + init { + objectType("event") + } + + /** + * Set the attendedBy Collection property + * @param collection Collection + * @return Builder + */ + fun attendedBy(collection: Collection?): Builder? { + return set("attendedBy", collection) + } + + /** + * Set the attendedBy Collection property + * @param collection Collection + * @return Builder + */ + fun attendedBy(collection: Supplier): Builder? { + return attendedBy(collection.get()) + } + + /** + * Set the attending Collection property + * @param collection Collection + * @return Builder + */ + fun attending(collection: Collection?): Builder? { + return set("attending", collection) + } + + /** + * Set the attending Collection property + * @param collection Collection + * @return Builder + */ + fun attending(collection: Supplier): Builder? { + return attending(collection.get()) + } + + /** + * Set the invited Collection property + * @param collection Collection + * @return Builder + */ + fun invited(collection: Collection?): Builder? { + return set("invited", collection) + } + + /** + * Set the invited Collection property + * @param collection Collection + * @return Builder + */ + fun invited(collection: Supplier): Builder? { + return invited(collection.get()) + } + + /** + * Set the maybeAttending Collection property + * @param collection Collection + * @return Builder + */ + fun maybeAttending(collection: Collection?): Builder? { + return set("maybeAttending", collection) + } + + /** + * Set the maybeAttending Collection property + * @param collection Collection + * @return Builder + */ + fun maybeAttending(collection: Supplier): Builder? { + return maybeAttending(collection.get()) + } + + /** + * Set the notAttendedBy Collection property + * @param collection Collection + * @return Builder + */ + fun notAttendedBy(collection: Collection?): Builder? { + return set("notAttendedBy", collection) + } + + /** + * Set the notAttendedBy Collection property + * @param collection Collection + * @return Builder + */ + fun notAttendedBy(collection: Supplier): Builder? { + return notAttendedBy(collection.get()) + } + + /** + * Set the notAttending Collection property + * @param collection Collection + * @return Builder + */ + fun notAttending(collection: Collection?): Builder? { + return set("notAttending", collection) + } + + /** + * Set the notAttending Collection property + * @param collection Collection + * @return Builder + */ + fun notAttending(collection: Supplier): Builder? { + return notAttending(collection.get()) + } + + /** + * Get the built Event object + * @return Event + */ + override fun get(): Event { + return Event(this) + } + } + + /** + * Get the attendedBy Collection or null if not provided + * @return Collection + */ + fun attendedBy(): Collection? { + return this.get("attendedBy") + } + + /** + * Get the attending Collection or null if not provided + * @return Collection + */ + fun attending(): Collection? { + return this.get("attending") + } + + /** + * Get the invited Collection or null if not provided + * @return Collection + */ + fun invited(): Collection? { + return this.get("invited") + } + + /** + * Get the maybeAttending Collection or null if not provided + * @return Collection + */ + fun maybeAttending(): Collection? { + return this.get("maybeAttending") + } + + /** + * Get the notAttendedBy Collection or null if not provided + * @return Collection + */ + fun notAttendedBy(): Collection? { + return this.get("notAttendedBy") + } + + /** + * Get the notAttending Collection or null if not provided + * @return Collection + */ + fun notAttending(): Collection? { + return this.get("notAttending") + } + + // Java Serialization Support + @Throws(ObjectStreamException::class) + override fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: Event?) : + AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + override fun builder(): Builder { + return Builder() + } + + companion object { + private const val serialVersionUID = -2060301713159936285L + } + } +} diff --git a/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/File.kt b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/File.kt new file mode 100644 index 0000000..b81250c --- /dev/null +++ b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/File.kt @@ -0,0 +1,104 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.legacy + +import com.google.common.net.MediaType +import com.ibm.common.activitystreams.ASObject +import java.io.ObjectStreamException + +/** + * The legacy "file" objectType + * @author james + */ +class File +private constructor(builder: Builder) : ASObject(builder) { + class Builder + internal constructor() : + AbstractBuilder() { + init { + objectType("file") + } + + /** + * Set the fileUrl property + * @param url String + * @return Builder + */ + fun fileUrl(url: String?): Builder? { + return set("fileUrl", url) + } + + /** + * Set the MIME mediaType using the legacy "mimeType" property + * name rather than the AS 2.0 "mediaType" property name + */ + override fun mediaType(mt: MediaType?): Builder { + return set("mimeType", mt)!! + } + + /** + * Get the built File object + */ + override fun get(): File { + return File(this) + } + } + + /** + * Get the MIME mediaType using the legacy "mimeType" property + * name rather than the AS 2.0 "mediaType" property + */ + override fun mediaType(): MediaType? { + return this.get("mimeType") + } + + /** + * Get the fileUrl property + * @return + */ + fun fileUrl(): String? { + return getString("fileUrl") + } + + // Java Serialization Support + @Throws(ObjectStreamException::class) + override fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: File?) : + AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + override fun builder(): Builder { + return Builder() + } + + companion object { + private const val serialVersionUID = -2060301713159936285L + } + } +} diff --git a/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Issue.kt b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Issue.kt new file mode 100644 index 0000000..1b32584 --- /dev/null +++ b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Issue.kt @@ -0,0 +1,100 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.legacy + +import com.google.common.collect.ImmutableList +import com.ibm.common.activitystreams.ASObject +import java.io.ObjectStreamException + +/** + * The legacy "issue" objectType. + * @author james + */ +class Issue +private constructor(builder: Builder) : ASObject(builder) { + class Builder + internal constructor() : AbstractBuilder() { + init { + objectType("issue") + } + + /** + * Set the "types" property + * @param type String + * @param types String... optional vararg of additional types to set + * @return Builder + */ + fun types(type: String?, vararg types: String?): Builder? { + val list = + ImmutableList.builder() + if (type != null) list.add(type) + if (types != null) list.add(*types) + return types(list.build()) + } + + /** + * Set the "types" property + * @param types Iterable<String> + * @return Builder + */ + fun types(types: Iterable?): Builder? { + return set("types", types) + } + + /** + * Get the built Issue object + */ + override fun get(): Issue { + return Issue(this) + } + } + + /** + * Get the listing of types + * @return Iterable<String> + */ + fun types(): Iterable? { + return this.get>("types") + } + + // Java Serialization Support ` + @Throws(ObjectStreamException::class) + override fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: Issue?) : AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + override fun builder(): Builder { + return Builder() + } + + companion object { + private const val serialVersionUID = -2060301713159936285L + } + } +} diff --git a/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/LegacyMakers.kt b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/LegacyMakers.kt new file mode 100644 index 0000000..4893b75 --- /dev/null +++ b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/LegacyMakers.kt @@ -0,0 +1,179 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.legacy + +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.Makers.`object` + +/** + * Makers for the various Legacy object types + * @author james + */ +object LegacyMakers { + fun binary(): Binary.Builder { + return Binary.Builder() + } + + fun task(): Task.Builder { + return Task.Builder() + } + + fun withImage(): WithImage.Builder { + return WithImage.Builder() + } + + fun question(): Question.Builder { + return Question.Builder() + } + + fun product(): WithImage.Builder? { + return WithImage.Builder().objectType("product") + } + + fun image(): WithImage.Builder? { + return WithImage.Builder().objectType("image") + } + + fun file(): File.Builder { + return File.Builder() + } + + fun bookmark(): Bookmark.Builder { + return Bookmark.Builder() + } + + fun bookmark(targetUrl: String?): Bookmark { + return bookmark().targetUrl(targetUrl)!!.get() + } + + fun role(): Membership.Builder? { + return Membership.Builder().objectType("role") + } + + fun group(): Membership.Builder? { + return Membership.Builder().objectType("group") + } + + fun issue(): Issue.Builder { + return Issue.Builder() + } + + fun membership(): Membership.Builder { + return Membership.Builder() + } + + fun event(): Event.Builder { + return Event.Builder() + } + + fun mediaLink(): MediaLink.Builder { + return MediaLink.Builder() + } + + fun mediaLink(url: String?): MediaLink { + return mediaLink().url(url).get() + } + + fun permission(): ASObject.Builder? { + return `object`("permission") + } + + fun video(): AudioVisual.Builder? { + return AudioVisual.Builder().objectType("video") + } + + fun audioVisual(): AudioVisual.Builder { + return AudioVisual.Builder() + } + + fun audio(): AudioVisual.Builder? { + return AudioVisual.Builder().objectType("audio") + } + + fun alert(): ASObject.Builder? { + return `object`("alert") + } + + fun application(): ASObject.Builder? { + return `object`("application") + } + + fun article(): ASObject.Builder? { + return `object`("article") + } + + fun badge(): ASObject.Builder? { + return `object`("badge") + } + + fun comment(): ASObject.Builder? { + return `object`("comment") + } + + fun device(): ASObject.Builder? { + return `object`("device") + } + + fun game(): ASObject.Builder? { + return `object`("game") + } + + fun job(): ASObject.Builder? { + return `object`("job") + } + + fun note(): ASObject.Builder? { + return `object`("note") + } + + fun offer(): ASObject.Builder? { + return `object`("offer") + } + + fun organization(): ASObject.Builder? { + return `object`("organization") + } + + fun page(): ASObject.Builder? { + return `object`("page") + } + + fun person(): ASObject.Builder? { + return `object`("person") + } + + fun process(): ASObject.Builder? { + return `object`("process") + } + + fun review(): ASObject.Builder? { + return `object`("review") + } + + fun service(): ASObject.Builder? { + return `object`("service") + } + + fun team(): Membership.Builder? { + return Membership.Builder().objectType("team") + } +} diff --git a/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/LegacyModule.kt b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/LegacyModule.kt new file mode 100644 index 0000000..646d29c --- /dev/null +++ b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/LegacyModule.kt @@ -0,0 +1,162 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.legacy + +import com.google.common.net.MediaType +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.Collection +import com.ibm.common.activitystreams.IO +import com.ibm.common.activitystreams.i.Model +import com.ibm.common.activitystreams.i.Schema +import com.ibm.common.activitystreams.util.Module + +/** + * Adds support for legacy objectTypes defined by the original + * Activity Streams 1.0 Schema (see https://github.com/activitystreams/activity-schema/blob/master/activity-schema.md) + * + *
+ * import com.ibm.common.activitystreams.IO;
+ * import com.ibm.common.activitystreams.legacy.LegacyModule;
+ *
+ * //...
+ *
+ * IO io = IO.makeDefault(LegacyModule.instance);
+ *
+
* + * @author james + */ +class LegacyModule + + : Module { + override fun apply(builder: Schema.Builder) { + builder.map("alert", Schema.`object`) + .map("binary", binary) + .map("application", Schema.`object`) + .map("article", Schema.`object`) + .map("audio", audioVisual) + .map("badge", Schema.`object`) + .map("bookmark", bookmark) + .map("comment", Schema.`object`) + .map("device", Schema.`object`) + .map("event", event) + .map("file", file) + .map("game", Schema.`object`) + .map("group", membership) + .map("image", withImage) + .map("issue", issue) + .map("job", Schema.`object`) + .map("note", Schema.`object`) + .map("offer", Schema.`object`) + .map("organization", Schema.`object`) + .map("page", Schema.`object`) + .map("person", Schema.`object`) + .map("process", Schema.`object`) + .map("product", Schema.`object`) + .map("question", question) + .map("review", Schema.`object`) + .map("role", membership) + .map("service", Schema.`object`) + .map("team", membership) + .map("video", audioVisual) + } + + override fun apply( + builder: IO.Builder, + schema: Schema + ) { + val base = + LegacyObjectAdapter(schema) + builder.adapter(MediaLink::class.java, MediaLinkAdapter()) + for (type in LegacyObjectAdapter.Companion.knownTypes) builder.hierarchicalAdapter( + type as Class, + base + ) + } + + companion object { + val instance: Module = LegacyModule() + + val binary: Model = Schema.`object`.template() + .type(Binary::class.java, Binary.Builder::class.java) + .string("compression", "md5", "data", "fileUrl") + .`as`("mimeType", MediaType::class.java) + .integer("length") + .get() + + val audioVisual: Model = Schema.`object`.template() + .type(AudioVisual::class.java, AudioVisual.Builder::class.java) + .string("embedCode") + .`as`("stream", MediaLink::class.java) + .get() + + val withImage: Model = Schema.`object`.template() + .type(WithImage::class.java, WithImage.Builder::class.java) + .`as`("fullImage", MediaLink::class.java) + .get() + + val bookmark: Model = Schema.`object`.template() + .type(Bookmark::class.java, Bookmark.Builder::class.java) + .string("targetUrl") + .get() + + val event: Model = Schema.`object`.template() + .type(Event::class.java, Event.Builder::class.java) + .`as`("attendedBy", Collection::class.java) + .`as`("attending", Collection::class.java) + .`as`("invited", Collection::class.java) + .`as`("maybeAttending", Collection::class.java) + .`as`("notAttendedBy", Collection::class.java) + .`as`("notAttending", Collection::class.java) + .get() + + val membership: Model = Schema.`object`.template() + .type(Membership::class.java, Membership.Builder::class.java) + .`as`("members", Collection::class.java) + .get() + + val file: Model = Schema.`object`.template() + .type(File::class.java, File.Builder::class.java) + .string("fileUrl") + .`as`("mimeType", MediaType::class.java) + .get() + + val issue: Model = Schema.`object`.template() + .type(Issue::class.java, Issue.Builder::class.java) + .string("types") + .get() + + val question: Model = Schema.`object`.template() + .type(Question::class.java, Question.Builder::class.java) + .linkValue("options") + .get() + + val task: Model = Schema.`object`.template() + .type(Task::class.java, Task.Builder::class.java) + .`object`("actor", "object") + .dateTime("by") + .`as`("required", Boolean::class.java) + .string("verb") + .`as`("prerequisites", Task::class.java) + .`as`("supersedes", Task::class.java) + .get() + } +} diff --git a/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/LegacyObjectAdapter.kt b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/LegacyObjectAdapter.kt new file mode 100644 index 0000000..1012727 --- /dev/null +++ b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/LegacyObjectAdapter.kt @@ -0,0 +1,87 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.legacy + +import com.google.common.collect.ImmutableSet +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.Makers.`object` +import com.ibm.common.activitystreams.i.ASObjectAdapter +import com.ibm.common.activitystreams.i.Model +import com.ibm.common.activitystreams.i.Schema +import java.lang.reflect.Type + +class LegacyObjectAdapter + (schema: Schema) : ASObjectAdapter(schema) { + override fun knowsType(type: Type?): Boolean { + if (super.knowsType(type)) return true + return knownTypes.contains(type) + } + + override fun builderFor(type: Type): ASObject.AbstractBuilder<*, *>? { + if (super.knowsType(type)) return super.builderFor(type) + return if (knowsType(type)) { + if (type === AudioVisual::class.java) LegacyMakers.audioVisual() + else if (type === Binary::class.java) LegacyMakers.binary() + else if (type === Bookmark::class.java) LegacyMakers.bookmark() + else if (type === Event::class.java) LegacyMakers.event() + else if (type === File::class.java) LegacyMakers.file() + else if (type === Issue::class.java) LegacyMakers.issue() + else if (type === Membership::class.java) LegacyMakers.membership() + else if (type === Question::class.java) LegacyMakers.question() + else if (type === Task::class.java) LegacyMakers.task() + else if (type === WithImage::class.java) LegacyMakers.withImage() + else `object`() + } else null + } + + override fun modelFor(type: Type): Model? { + if (super.knowsType(type)) return super.modelFor(type) + return if (knowsType(type)) { + if (type === AudioVisual::class.java) LegacyModule.Companion.audioVisual + else if (type === Bookmark::class.java) LegacyModule.Companion.bookmark + else if (type === Binary::class.java) LegacyModule.Companion.binary + else if (type === Event::class.java) LegacyModule.Companion.event + else if (type === File::class.java) LegacyModule.Companion.file + else if (type === Issue::class.java) LegacyModule.Companion.issue + else if (type === Membership::class.java) LegacyModule.Companion.membership + else if (type === Question::class.java) LegacyModule.Companion.question + else if (type === Task::class.java) LegacyModule.Companion.task + else if (type === WithImage::class.java) LegacyModule.Companion.withImage + else Schema.`object` + } else null + } + + companion object { + val knownTypes: ImmutableSet = ImmutableSet.of( + Binary::class.java, + AudioVisual::class.java, + Bookmark::class.java, + Event::class.java, + File::class.java, + Issue::class.java, + Membership::class.java, + Question::class.java, + Task::class.java, + WithImage::class.java + ) + } +} diff --git a/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/MediaLink.kt b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/MediaLink.kt new file mode 100644 index 0000000..bf42acb --- /dev/null +++ b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/MediaLink.kt @@ -0,0 +1,187 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.legacy + +import com.google.common.base.Supplier +import com.google.common.collect.ImmutableMap +import com.google.common.collect.Maps +import com.ibm.common.activitystreams.util.AbstractWritable +import java.io.ObjectStreamException +import java.io.Serializable + +/** + * An Activity Streams 1.0 Media Link object. + * @author james + */ +class MediaLink +private constructor(builder: Builder) : AbstractWritable(builder), + Iterable, Serializable { + class Builder + + : AbstractWritableBuilder(), + Supplier { + val map: MutableMap = Maps.newHashMap() + + /** + * When the media link refers to a video or audio resource, + * the duration property indicates the total length in seconds + * @param duration int + * @return Builder + */ + fun duration(duration: Int): Builder { + map["duration"] = duration + return this + } + + /** + * When the media link refers to an object intended to be + * displayed visually, such as a video or image, the + * height property specifies the display height in terms + * of device independent pixels. + * @param height int + * @return Builder + */ + fun height(height: Int): Builder { + map["height"] = height + return this + } + + /** + * When the media link refers to an object intended to be + * displayed visually, such as a video or image, the + * width property specifies the display width in terms + * of device independent pixels. + * @param height int + * @return Builder + */ + fun width(width: Int): Builder { + map["width"] = width + return this + } + + /** + * The URL of the resource + * @param url String + * @return Builder + */ + fun url(url: String?): Builder { + map["url"] = url + return this + } + + /** + * Set an arbitrary property on the Media Link + * @param key String + * @param val Object + * @return Builder + */ + operator fun set(key: String, `val`: Any?): Builder { + map[key] = `val` + return this + } + + /** + * Get the built MediaLink object + */ + override fun get(): MediaLink { + return MediaLink(this) + } + } + + private val map: ImmutableMap = + ImmutableMap.copyOf(builder.map) + + /** + * Get the url property + * @return + */ + fun url(): String? { + return map["url"] as String? + } + + /** + * When the media link refers to a video or audio resource, + * the duration property indicates the total length in seconds + * @return int + */ + fun duration(): Int { + return map["duration"] as Int + } + + /** + * When the media link refers to an object intended to be + * displayed visually, such as a video or image, the + * height property specifies the display height in terms + * of device independent pixels. + * @return int + */ + fun height(): Int { + return map["height"] as Int + } + + /** + * When the media link refers to an object intended to be + * displayed visually, such as a video or image, the + * width property specifies the display width in terms + * of device independent pixels. + * @return int + */ + fun width(): Int { + return map["width"] as Int + } + + /** + * Return the given property + * @param key + * @return <T>T + */ + fun get(key: String?): T? { + return map[key] as T? + } + + override fun iterator(): MutableIterator { + return map.keys.iterator() + } + + // Java Serialization Support + @Throws(ObjectStreamException::class) + fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: MediaLink) : Serializable { + private val map = obj.map + + @Throws(ObjectStreamException::class) + fun readResolve(): Any { + val builder = + Builder() + builder.map.putAll(map) + return builder.get() + } + + companion object { + private const val serialVersionUID = -2060301713159936285L + } + } +} diff --git a/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/MediaLinkAdapter.kt b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/MediaLinkAdapter.kt new file mode 100644 index 0000000..356adb8 --- /dev/null +++ b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/MediaLinkAdapter.kt @@ -0,0 +1,68 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.legacy + +import com.google.common.base.Preconditions +import com.google.gson.* +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.i.ASObjectAdapter +import com.ibm.common.activitystreams.i.Adapter +import java.lang.reflect.Type + +class MediaLinkAdapter + + : Adapter() { + override fun serialize( + src: MediaLink, + typeOfSrc: Type, + context: JsonSerializationContext + ): JsonElement { + val el = JsonObject() + for (key: String in src) { + val `val` = src.get(key) + if (`val` != null) el.add(key, context.serialize(`val`, `val`.javaClass)) + } + return el + } + + @Throws(JsonParseException::class) + override fun deserialize( + json: JsonElement, + typeOfT: Type, + context: JsonDeserializationContext + ): MediaLink { + Preconditions.checkArgument(json.isJsonObject) + val obj = json as JsonObject + val builder = + LegacyMakers.mediaLink() + for (entry: Map.Entry in obj.entrySet()) { + if (obj.isJsonPrimitive) builder[entry.key] = ASObjectAdapter.primConverter.convert(obj.asJsonPrimitive) + else if (obj.isJsonArray) builder[entry.key] = + context.deserialize(obj, Iterable::class.java) + else if (obj.isJsonObject) builder[entry.key] = context.deserialize( + obj, + ASObject::class.java + ) + } + return builder.get() + } +} diff --git a/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Membership.kt b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Membership.kt new file mode 100644 index 0000000..0f1992e --- /dev/null +++ b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Membership.kt @@ -0,0 +1,95 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.legacy + +import com.google.common.base.Supplier +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.Collection +import java.io.ObjectStreamException + +/** + * For the legacy "role", "group" and "team" objectTypes. + * Membership objects include an additional "members" + * collection property. + * + * @author james + */ +class Membership private constructor(builder: Builder) : ASObject(builder) { + class Builder + + : AbstractBuilder() { + /** + * Set the members collection + * @param collection Collection + * @return Builder + */ + fun members(collection: Collection?): Builder? { + return set("members", collection) + } + + /** + * Set the members collection + * @param collection Collection + * @return Builder + */ + fun members(collection: Supplier): Builder? { + return members(collection.get()) + } + + /** + * Get the built Membership object + */ + override fun get(): Membership { + return Membership(this) + } + } + + /** + * Return the members collection + * @return Collection + */ + fun members(): Collection? { + return this.get("members") + } + + // Java Serialization Support + @Throws(ObjectStreamException::class) + override fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: Membership?) : AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + override fun builder(): Builder { + return Builder() + } + + companion object { + private val serialVersionUID: Long = -2060301713159936285L + } + } +} diff --git a/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Question.kt b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Question.kt new file mode 100644 index 0000000..7204270 --- /dev/null +++ b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Question.kt @@ -0,0 +1,127 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.legacy + +import com.google.common.base.Predicate +import com.google.common.base.Supplier +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.LinkValue +import java.io.ObjectStreamException + +/** + * The legacy "question" object. Question objects + * have an additional "options" property that lists + * the possible answers to the question. + * + * This implementation varies from the Legacy AS 1.0 + * model in that it allows AS 2.0 style LinkValues + * to be used as the value of the options property. + * + * @author james + */ +class Question(builder: Builder) : ASObject(builder) { + class Builder + internal constructor() : AbstractBuilder() { + init { + objectType("question") + } + + /** + * Add one or more answers to the question + * @param url String + * @param urls String[] optional vararg + * @return Builder + */ + fun option(url: String?, vararg urls: String?): Builder { + if (url != null) link("options", url) + if (urls != null) for (u: String? in urls) link("options", u) + return this + } + + /** + * Add one or more answers to the question + * @param url LinkValue + * @param urls LinkValue[] optional vararg + * @return Builder + */ + fun option(link: LinkValue?, vararg links: LinkValue?): Builder { + if (link != null) link("options", link) + if (links != null) for (l: LinkValue? in links) link("options", l) + return this + } + + /** + * Add an answer to the question + * @param link Supplier<? extends LinkValue> + * @return Builder + */ + fun option(link: Supplier): Builder { + return option(link.get()) + } + + /** + * Get the built question object + */ + override fun get(): Question { + return Question(this) + } + } + + /** + * Get the list of options for the question + * @return Iterable<LinkValue> + */ + fun options(): Iterable { + return links("options") + } + + /** + * Get the list of options for the question + * @param filter Predicate<? super LinkValue> + * @return Iterable<LinkValue> + */ + fun options(filter: Predicate): Iterable { + return links("options", filter) + } + + // Java Serialization Support + @Throws(ObjectStreamException::class) + override fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: Question?) : AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + override fun builder(): Builder { + return Builder() + } + + companion object { + private val serialVersionUID: Long = -2060301713159936285L + } + } +} diff --git a/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Task.kt b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Task.kt new file mode 100644 index 0000000..4cd194a --- /dev/null +++ b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/Task.kt @@ -0,0 +1,327 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.legacy + +import com.google.common.base.Function +import com.google.common.base.Predicate +import com.google.common.base.Supplier +import com.google.common.collect.Iterables +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.LinkValue +import org.joda.time.DateTime +import org.joda.time.ReadableDuration +import org.joda.time.ReadablePeriod +import java.io.ObjectStreamException + +/** + * The Legacy "task" objectType. Task objects in AS 1.0 are essentially + * pending Activity statements. + * @author james + */ +class Task +private constructor(builder: Builder) : ASObject(builder) { + class Builder + internal constructor() : + AbstractBuilder() { + init { + objectType("task") + } + + /** + * Set the actor + * @param actor ASObject + * @return Builder + */ + fun actor(actor: ASObject?): Builder? { + return set("actor", actor) + } + + /** + * Set the actor + * @param actor Supplier<? extends ASObject> + * @return Builder + */ + fun actor(actor: Supplier): Builder? { + return actor(actor.get()) + } + + /** + * Set the object + * @param object ASObject + * @return Builder + */ + fun `object`(`object`: ASObject?): Builder? { + return set("object", `object`) + } + + /** + * Set the object + * @param object Supplier<? extends ASObject> + * @return Builder + */ + fun `object`(`object`: Supplier): Builder? { + return `object`(`object`.get()) + } + + /** + * Set one or more prerequisite taskss + * @param task Task + * @param tasks Task[] optional vararg + * @return Builder + */ + fun prerequisites(task: Task?, vararg tasks: Task?): Builder { + if (task != null) link("prerequisites", task) + if (tasks != null) for (t: Task? in tasks) link("prerequisites", t) + return this + } + + /** + * Set one or more prerequisite tasks + * @param tasks Iterable<Task> + * @return Builder + */ + fun prerequisites(tasks: Iterable?): Builder { + if (tasks != null) for (task: Task? in tasks) link("prerequisites", task) + return this + } + + /** + * Set an optional prerequisite + * @param task Supplier<? extends Task> + * @return Builder + */ + fun prerequisites(task: Supplier): Builder { + return prerequisites(task.get()) + } + + /** + * Specify one or more other tasks that this task supersedes + * @param task Task + * @param tasks Task[] optional vararg + * @return Builder + */ + fun supersedes(task: Task?, vararg tasks: Task?): Builder { + if (task != null) link("supersedes", task) + if (tasks != null) for (t: Task? in tasks) link("supersedes", t) + return this + } + + /** + * Specify one or more other tasks that this task supersedes + * @param tasks Iterable<Task> + * @return Builder + */ + fun supersedes(tasks: Iterable?): Builder { + if (tasks != null) for (task: Task? in tasks) link("supersedes", task) + return this + } + + /** + * Specify a task that this task supersedes + * @param task Supplier<? extends Task> + * @return Builder + */ + fun supersedes(task: Supplier): Builder { + return supersedes(task.get()) + } + + /** + * Indicates whether this task is required or not + * @param on boolean + * @return Builder + */ + /** + * Indicates that this task is required + * @return Builder + */ + @JvmOverloads + fun required(on: Boolean = true): Builder? { + return set("required", on) + } + + /** + * Specifies the verb for this task + * @param verb String + * @return Builder + */ + fun verb(verb: String?): Builder? { + return set("verb", verb) + } + + /** + * Specifies the due date for this task + * @param dt DateTime + * @return Builder + */ + fun by(dt: DateTime?): Builder? { + return this._dt("by", dt) + } + + /** + * Specifies that this task is due right now + * @return Builder + */ + fun byNow(): Builder? { + return this._dtNow("by") + } + + /** + * Specifies the due date for this task in terms of a specific + * duration of time from right now + * @param duration ReadableDuration + * @return Builder + */ + fun byFromNow(duration: ReadableDuration?): Builder? { + return this._dtFromNow("by", duration) + } + + /** + * Specifies the due date for this task in terms of a specific + * period of time from right now + * @param period ReadablePeriod + * @return Builder + */ + fun byFromNow(period: ReadablePeriod?): Builder? { + return this._dtFromNow("by", period) + } + + /** + * Specifies the due date for this task in terms of a specific + * duration of time from the given instant; + * @param dt DateTime + * @param duration ReadableDuration + * @return Builder + */ + fun by(dt: DateTime, duration: ReadableDuration?): Builder? { + return this._dtFrom("by", dt, duration) + } + + /** + * Specifies the due date for this task in terms of a specific + * period of time from the given instant + * @param dt DateTime + * @param period ReadablePeriod + * @return Builder + */ + fun by(dt: DateTime, period: ReadablePeriod?): Builder? { + return this._dtFrom("by", dt, period) + } + + /** + * Get the completed Task object + */ + override fun get(): Task { + return Task(this) + } + } + + /** + * Get the actor + * @return <A extends ASObject>A + */ + fun
actor(): A? { + return this.get("actor") + } + + /** + * Get the object + * @return <A extends ASObject>A + */ + fun `object`(): A? { + return this.get("object") + } + + /** + * Get the due date + * @return DateTime + */ + fun by(): DateTime? { + return getDateTime("by") + } + + /** + * Get the verb + * @return String + */ + fun verb(): String? { + return getString("verb") + } + + /** + * Return true if this task is required + * @return boolean + */ + fun required(): Boolean { + return getBoolean("required") + } + + /** + * Return the listing of other tasks superseded by this one + * (will return an empty iterable if there are no superseded + * tasks) + * @return Iterable<Task> + */ + fun supersedes(): Iterable { + return Iterables.transform(links("supersedes", filter), transformer) + } + + /** + * Return the listing of other tasks upon which this task depends. + * (will return an empty iterable if there are no prerequisite + * tasks) + * @return Iterable<Task> + */ + fun prerequisites(): Iterable { + return Iterables.transform(links("prerequisites", filter), transformer) + } + + // Java Serialization Support + @Throws(ObjectStreamException::class) + override fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: Task?) : + AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + override fun builder(): Builder { + return Builder() + } + + companion object { + private val serialVersionUID: Long = -2060301713159936285L + } + } + + companion object { + private val filter: Predicate = + Predicate { input -> input is Task } + + private val transformer: Function = + Function { input -> input as Task? } + } +} diff --git a/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/WithImage.kt b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/WithImage.kt new file mode 100644 index 0000000..0758833 --- /dev/null +++ b/legacy/src/main/kotlin/com/ibm/common/activitystreams/legacy/WithImage.kt @@ -0,0 +1,91 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.legacy + +import com.google.common.base.Supplier +import com.ibm.common.activitystreams.ASObject +import java.io.ObjectStreamException + +/** + * For the legacy "product" and "image" objectTypes. These + * include an additional "fullImage" property whose value + * is a MediaLink. + * + * @author james + */ +class WithImage private constructor(builder: Builder) : ASObject(builder) { + class Builder + + : AbstractBuilder() { + /** + * Set the fullImage property + * @param link MediaLink + * @return Builder + */ + fun fullImage(link: MediaLink?): Builder? { + return set("fullImage", link) + } + + /** + * Set the fullImage property + * @param link Supplier<? extends MediaLink> + * @return Builder + */ + fun fullImage(link: Supplier): Builder? { + return fullImage(link.get()) + } + + override fun get(): WithImage { + return WithImage(this) + } + } + + /** + * Get the fullImage property + * @return MediaLink + */ + fun fullImage(): MediaLink? { + return this.get("fullImage") + } + + // Java Serialization Support + @Throws(ObjectStreamException::class) + override fun writeReplace(): Any { + return SerializedForm(this) + } + + private class SerializedForm + (obj: WithImage?) : AbstractSerializedForm(obj) { + @Throws(ObjectStreamException::class) + fun readResolve(): Any? { + return super.doReadResolve() + } + + override fun builder(): Builder { + return Builder() + } + + companion object { + private val serialVersionUID: Long = -2060301713159936285L + } + } +} diff --git a/pom.xml b/pom.xml deleted file mode 100644 index e8b7f52..0000000 --- a/pom.xml +++ /dev/null @@ -1,85 +0,0 @@ - - 4.0.0 - com.ibm.common - activitystreams - 0.0.1-SNAPSHOT - pom - Activity Streams 2.0 Java Reference Implementation - - - - jasnell - James M Snell - jasnell@us.ibm.com - IBM - http://www.ibm.com - - owner - developer - - -8 - - - - - - Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - IBM - http://www.ibm.com - - - scm:https://github.com/OpenSocial/incubator.git - http://github.com/OpenSocial/activitystreams - - - - UTF-8 - - - - core - actions - geo - assembly - legacy - typext - - - - - com.google.code.gson - gson - 2.2.4 - - - com.google.guava - guava - 16.0.1 - - - joda-time - joda-time - 2.3 - - - - junit - junit - 4.11 - test - - - - http://github.com/OpenSocial/activitystreams - An implementation of the Activity Streams 2.0 data format. - 2013 - - https://github.com/OpenSocial/activitystreams/issues - - diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..7b47dee --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,19 @@ +pluginManagement { + plugins { + kotlin("jvm") version "2.0.21" + } +} +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "0.8.0" +} +/* + * This file was generated by the Gradle 'init' task. + */ + +rootProject.name = "activitystreams" +include(":geo") +include(":legacy") +include(":assembly") +include(":actions") +include(":typext") +include(":core") diff --git a/typext/build.gradle.kts b/typext/build.gradle.kts new file mode 100644 index 0000000..3ac4cbc --- /dev/null +++ b/typext/build.gradle.kts @@ -0,0 +1,27 @@ +/* + * This file was generated by the Gradle 'init' task. + */ + +plugins { + java + kotlin("jvm") +} + +dependencies { + api(project(":core")) + api(libs.org.apache.httpcomponents.httpclient.cache) + api(libs.org.apache.httpcomponents.httpcomponents.client) + testImplementation(libs.junit.junit) + implementation(kotlin("stdlib-jdk8")) +} + +description = "Activity Streams 2.0 - Type Extension Support" +repositories { + mavenCentral() +} +kotlin { + jvmToolchain(11) +} +tasks.test { + useJUnit() +} \ No newline at end of file diff --git a/typext/pom.xml b/typext/pom.xml deleted file mode 100644 index 9966778..0000000 --- a/typext/pom.xml +++ /dev/null @@ -1,157 +0,0 @@ - - 4.0.0 - - com.ibm.common - activitystreams - 0.0.1-SNAPSHOT - - activitystreams-ext - Activity Streams 2.0 - Type Extension Support - - - - Apache License, Version 2.0 - http://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - - - UTF-8 - - - - - - org.apache.maven.plugins - maven-javadoc-plugin - 2.9.1 - - UTF-8 - UTF-8 - UTF-8 - -XDignore.symbol.file - public - - http://www.joda.org/joda-time/apidocs - http://docs.guava-libraries.googlecode.com/git-history/v16.0.1/javadoc/ - - - - - - maven-compiler-plugin - 2.3.2 - - 1.7 - 1.7 - - - - - maven-jar-plugin - 2.3.1 - - - ${project.build.outputDirectory}/META-INF/MANIFEST.MF - - - - - - org.apache.felix - maven-bundle-plugin - 2.3.7 - true - - - bundle-manifest - process-classes - - manifest - - - - - - - com.ibm.common.activitystreams.ext.*, - com.ibm.common.activitystreams.registry.* - - - com.ibm.common.activitystreams.*, - com.google.gson.*, - com.google.common.*, - org.joda.time.*, - org.apache.http.*, - - - - - - - org.apache.maven.plugins - maven-assembly-plugin - 2.2.2 - - - assembly.xml - - - - - - - - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - org.apache.felix - maven-bundle-plugin - [2.3.7,) - - manifest - - - - - - - - - - - - - - - - - com.ibm.common - activitystreams-core - 0.0.1-SNAPSHOT - - - org.apache.httpcomponents - httpclient-cache - 4.3.3 - - - org.apache.httpcomponents - httpcomponents-client - 4.3.3 - pom - - - junit - junit - - - \ No newline at end of file diff --git a/typext/src/main/java/com/ibm/common/activitystreams/ext/ExtAdapter.java b/typext/src/main/java/com/ibm/common/activitystreams/ext/ExtAdapter.java deleted file mode 100644 index 8dd5b80..0000000 --- a/typext/src/main/java/com/ibm/common/activitystreams/ext/ExtAdapter.java +++ /dev/null @@ -1,74 +0,0 @@ -/** - * Copyright 2013 OpenSocial Foundation - * Copyright 2013 International Business Machines Corporation - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - * Utility library for working with Activity Streams Actions - * Requires underscorejs. - * - * @author James M Snell (jasnell@us.ibm.com) - */ -package com.ibm.common.activitystreams.ext; - -import java.lang.reflect.Type; - -import com.google.common.collect.ImmutableSet; -import com.ibm.common.activitystreams.ASObject.AbstractBuilder; -import com.ibm.common.activitystreams.internal.ASObjectAdapter; -import com.ibm.common.activitystreams.internal.Model; -import com.ibm.common.activitystreams.internal.Schema; - -public class ExtAdapter - extends ASObjectAdapter { - - protected ExtAdapter(Schema schema) { - super(schema); - } - - private static final ImmutableSet knownTypes = - ImmutableSet.of(Verb.class,ObjectType.class); - - @Override - protected boolean knowsType(Type type) { - if (super.knowsType(type)) - return true; - return knownTypes.contains(type); - } - - @Override - protected AbstractBuilder builderFor(Type type) { - if (super.knowsType(type)) - return super.builderFor(type); - if (type == Verb.class) { - return ExtMakers.verb(); - } else if (type == ObjectType.class) { - return ExtMakers.objectType(); - } else return null; - } - - @Override - protected Model modelFor(Type type) { - if (super.knowsType(type)) - return super.modelFor(type); - if (type == Verb.class) { - return schema().forObjectClassOrType( - Verb.Builder.class, - "verb"); - } else if (type == ObjectType.class) { - return schema().forObjectClassOrType( - ObjectType.Builder.class, - "objectType"); - } else return null; - } -} diff --git a/typext/src/main/java/com/ibm/common/activitystreams/ext/ExtMakers.java b/typext/src/main/java/com/ibm/common/activitystreams/ext/ExtMakers.java deleted file mode 100644 index 791355d..0000000 --- a/typext/src/main/java/com/ibm/common/activitystreams/ext/ExtMakers.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.ibm.common.activitystreams.ext; - -public final class ExtMakers { - - private ExtMakers() {} - - public static Verb.Builder verb() { - return new Verb.Builder(); - } - - public static Verb.Builder verb(String id) { - return verb().id(id); - } - - public static ObjectType.Builder objectType() { - return new ObjectType.Builder(); - } - - public static ObjectType.Builder objectType(String id) { - return objectType().id(id); - } - -} diff --git a/typext/src/main/java/com/ibm/common/activitystreams/ext/ExtModule.java b/typext/src/main/java/com/ibm/common/activitystreams/ext/ExtModule.java deleted file mode 100644 index c2ec2a9..0000000 --- a/typext/src/main/java/com/ibm/common/activitystreams/ext/ExtModule.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.ibm.common.activitystreams.ext; - -import com.ibm.common.activitystreams.IO; -import com.ibm.common.activitystreams.internal.Model; -import com.ibm.common.activitystreams.internal.Schema; -import com.ibm.common.activitystreams.internal.Schema.Builder; -import com.ibm.common.activitystreams.util.Module; - -public class ExtModule implements Module { - - public static Module instance = new ExtModule(); - - public static final Model verb = - Schema.object.template() - .type(Verb.class, Verb.Builder.class) - .get(); - - public static final Model objectType = - Schema.object.template() - .type(ObjectType.class, ObjectType.Builder.class) - .get(); - - public void apply(Builder builder) { - builder.map("verb", verb); - builder.map("objectType", objectType); - } - - public void apply( - IO.Builder builder, - Schema schema) { - ExtAdapter base = new ExtAdapter(schema); - builder.adapter(Verb.class, base); - builder.adapter(ObjectType.class, base); - } - -} diff --git a/typext/src/main/java/com/ibm/common/activitystreams/ext/ObjectType.java b/typext/src/main/java/com/ibm/common/activitystreams/ext/ObjectType.java deleted file mode 100644 index c877ad2..0000000 --- a/typext/src/main/java/com/ibm/common/activitystreams/ext/ObjectType.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.ibm.common.activitystreams.ext; - -import com.ibm.common.activitystreams.ASObject; - -public final class ObjectType - extends ASObject { - - public static final class Builder - extends ASObject.AbstractBuilder { - - Builder() { - objectType("objectType"); - } - - public ObjectType get() { - return new ObjectType(this); - } - - } - - private ObjectType(Builder builder) { - super(builder); - } -} diff --git a/typext/src/main/java/com/ibm/common/activitystreams/ext/Verb.java b/typext/src/main/java/com/ibm/common/activitystreams/ext/Verb.java deleted file mode 100644 index f0262b0..0000000 --- a/typext/src/main/java/com/ibm/common/activitystreams/ext/Verb.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.ibm.common.activitystreams.ext; - -import com.ibm.common.activitystreams.ASObject; - -public final class Verb - extends ASObject { - - public static final class Builder - extends ASObject.AbstractBuilder { - - Builder() { - objectType("verb"); - } - - public Verb get() { - return new Verb(this); - } - - } - - private Verb(Builder builder) { - super(builder); - } - -} diff --git a/typext/src/main/java/com/ibm/common/activitystreams/registry/CachingResolutionStrategy.java b/typext/src/main/java/com/ibm/common/activitystreams/registry/CachingResolutionStrategy.java deleted file mode 100644 index 09eba1a..0000000 --- a/typext/src/main/java/com/ibm/common/activitystreams/registry/CachingResolutionStrategy.java +++ /dev/null @@ -1,128 +0,0 @@ -package com.ibm.common.activitystreams.registry; - -import static com.google.common.base.Throwables.propagate; - -import java.util.concurrent.Callable; -import java.util.concurrent.TimeUnit; - -import com.google.common.base.Supplier; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import com.ibm.common.activitystreams.Makers; -import com.ibm.common.activitystreams.TypeValue; -import com.ibm.common.activitystreams.ValueType; - -public abstract class CachingResolutionStrategy - implements ResolutionStrategy { - - @SuppressWarnings("unchecked") - public static abstract class AbstractBuilder - > - implements Supplier { - - private boolean silentfail = false; - private final CacheBuilder cache = - CacheBuilder.newBuilder() - .expireAfterAccess(10, TimeUnit.MINUTES) - .expireAfterWrite(10, TimeUnit.MINUTES) - .maximumSize(100) - .initialCapacity(50); - - public B silentfail() { - this.silentfail = true; - return (B)this; - } - - public B customizeCache(Receiver> receiver) { - if (receiver != null) - receiver.receive(cache); - return (B)this; - } - - } - - private final LoadingCache cache; - private final boolean silentfail; - - protected LoadingCache cache() { - return cache; - } - - CachingResolutionStrategy(AbstractBuilder builder) { - this.cache = initCache(builder); - this.silentfail = builder.silentfail; - } - - protected boolean silentfail() { - return silentfail; - } - - private LoadingCache initCache(AbstractBuilder builder) { - return builder.cache.build(loader()); - } - - public Callable resolverFor(TypeValue tv) { - return new Resolver(tv); - } - - protected abstract CacheLoader loader(); - - public final class Resolver - implements Callable { - - private final TypeValue input; - - Resolver(TypeValue input) { - this.input = input; - } - - public TypeValue call() throws Exception { - try { - if (input == null) return null; - switch(input.valueType()) { - case OBJECT: - return input; - case SIMPLE: - return cache.get(input); - default: - throw new IllegalArgumentException(); - } - } catch (Throwable t) { - if (silentfail()) - return input; - else throw propagate(t); - } - } - - } - - public Receiver preloader() { - return new CachePreloader(cache()); - } - - private static final class CachePreloader - implements Receiver { - - private final LoadingCache cache; - - CachePreloader(LoadingCache cache) { - this.cache = cache; - } - - public void receive(final TypeValue t) { - if (t.valueType() == ValueType.OBJECT && t.id() != null) { - final TypeValue tv = Makers.type(t.id()); - cache.invalidate(tv); - try { - cache.get(tv, new Callable() { - public TypeValue call() { - return t; - } - }); - } catch (Throwable e) {} - } - } - - } -} diff --git a/typext/src/main/java/com/ibm/common/activitystreams/registry/ClasspathPreloader.java b/typext/src/main/java/com/ibm/common/activitystreams/registry/ClasspathPreloader.java deleted file mode 100644 index 13776e8..0000000 --- a/typext/src/main/java/com/ibm/common/activitystreams/registry/ClasspathPreloader.java +++ /dev/null @@ -1,111 +0,0 @@ -package com.ibm.common.activitystreams.registry; - -import java.io.InputStream; -import java.io.ObjectInputStream; -import java.net.URL; -import java.util.Enumeration; - -import com.google.common.base.Charsets; -import com.google.common.base.Function; -import com.google.common.base.Supplier; -import com.google.common.base.Throwables; -import com.google.common.collect.ImmutableList; -import com.google.common.hash.BloomFilter; -import com.google.common.hash.Funnels; -import com.ibm.common.activitystreams.ASObject; -import com.ibm.common.activitystreams.Collection; -import com.ibm.common.activitystreams.IO; -import com.ibm.common.activitystreams.TypeValue; - -public final class ClasspathPreloader - implements PreloadStrategy { - - public static final class Builder - implements Supplier { - - private ClassLoader loader = - Thread.currentThread().getContextClassLoader(); - private boolean avoidDuplicates = false; - - public Builder avoidDuplicates() { - this.avoidDuplicates = true; - return this; - } - - public Builder classLoader(ClassLoader loader) { - this.loader = loader != null ? - loader : Thread.currentThread().getContextClassLoader(); - return this; - } - - public ClasspathPreloader get() { - return new ClasspathPreloader(this); - } - - } - - private final ClassLoader loader; - private final boolean avoidDuplicates; - - private ClasspathPreloader(Builder builder) { - this.loader = builder.loader; - this.avoidDuplicates = builder.avoidDuplicates; - } - - public void load(IO io, Receiver receiver) { - - final BloomFilter filter = - avoidDuplicates ? - BloomFilter.create(Funnels.stringFunnel(Charsets.UTF_8), 1000) : null; - - try { - for (InputStream in : streams.apply(loader.getResources("typeValues.bin"))) { - try { - ObjectInputStream oin = new ObjectInputStream(in); - Collection col = (Collection) oin.readObject(); - load(col, receiver, filter); - } catch (Throwable t) {} - } - - for (InputStream in : streams.apply(loader.getResources("typeValues.json"))) { - try { - load(io.readAsCollection(in), receiver, filter); - } catch (Throwable t) {} - } - - } catch (Throwable t) { - throw Throwables.propagate(t); - } - - } - - private void load( - Collection col, - Receiver receiver, - BloomFilter filter) { - if (col != null && receiver != null) - for (ASObject obj : col.items()) - if (obj.id() != null && (filter == null || filter.put(obj.id()))) { - try { - receiver.receive(obj); - } catch (Throwable t) {} - } - } - - private static Function,Iterable> streams = - new Function,Iterable> () { - public Iterable apply(Enumeration input) { - ImmutableList.Builder list = - ImmutableList.builder(); - while(input.hasMoreElements()) { - try { - list.add(input.nextElement().openStream()); - } catch (Throwable t) {} - } - return list.build(); - } - }; - - public static final PreloadStrategy instance = - new Builder().get(); -} diff --git a/typext/src/main/java/com/ibm/common/activitystreams/registry/DefaultResolutionStrategy.java b/typext/src/main/java/com/ibm/common/activitystreams/registry/DefaultResolutionStrategy.java deleted file mode 100644 index 77ffab0..0000000 --- a/typext/src/main/java/com/ibm/common/activitystreams/registry/DefaultResolutionStrategy.java +++ /dev/null @@ -1,201 +0,0 @@ -package com.ibm.common.activitystreams.registry; - -import static com.google.common.util.concurrent.MoreExecutors.platformThreadFactory; -import static com.google.common.base.Throwables.propagate; - -import java.util.Set; -import java.util.concurrent.Callable; - -import com.google.common.base.Objects; -import com.google.common.cache.CacheLoader; -import com.google.common.collect.ImmutableSet; -import com.ibm.common.activitystreams.ASObject; -import com.ibm.common.activitystreams.Collection; -import com.ibm.common.activitystreams.Makers; -import com.ibm.common.activitystreams.TypeValue; - -public final class DefaultResolutionStrategy - extends CachingResolutionStrategy { - - public static Builder make() { - return new Builder(); - } - - public static DefaultResolutionStrategy makeDefault() { - return make().get(); - } - - public static final class Builder - extends CachingResolutionStrategy.AbstractBuilder { - - private boolean proactive = false; - private final HttpFetch.Builder fetcherBuilder = - new HttpFetch.Builder(); - private final ImmutableSet.Builder proactiveTypes = - ImmutableSet.builder() - .add("verb") - .add("objectType"); - - public Builder customizeFetcher(Receiver receiver) { - if (receiver != null) - receiver.receive(fetcherBuilder); - return this; - } - - /** - * Tells the loader to proactively cache additional typevalue - * identifiers that happen to be discovered when attempting to - * resolve a given typevalue. - * @return - */ - public Builder proactiveCaching() { - this.proactive = true; - return this; - } - - /** - * Specifies additional objectType identifiers to watch for when - * proactiveCaching is enabled. - * @param typeValueId - * @return - */ - public Builder typeValueObjectType(String typeValueId) { - proactiveTypes.add(typeValueId); - return this; - } - - public DefaultResolutionStrategy get() { - return new DefaultResolutionStrategy(this); - } - - } - - private final boolean proactiveCaching; - private final ImmutableSet proactiveTypes; - private final HttpFetch fetcher; - - private DefaultResolutionStrategy(Builder builder) { - super(builder); - this.proactiveCaching = builder.proactive; - this.proactiveTypes = builder.proactiveTypes.build(); - this.fetcher = initFetcher(builder); - ensureAlwaysShutdown(this); - } - - private HttpFetch initFetcher(Builder builder) { - return builder.fetcherBuilder.get(); - } - - @Override - protected CacheLoader loader() { - return new DefaultCacheLoader(); - } - - private final class DefaultCacheLoader - extends CacheLoader { - - @Override - public TypeValue load(TypeValue key) throws Exception { - try { - if (key == null) - throw new IllegalArgumentException(); - switch(key.valueType()) { - case OBJECT: - return key; // type is already resolved - case SIMPLE: - String id = key.id(); - ASObject obj = fetcher.fetch(id); // attempt to fetch an object - ImmutableSet.Builder additional = - ImmutableSet.builder(); - if (obj instanceof Collection) { - Collection col = (Collection) obj; - ASObject matching = - processItems( - col.items(), - id, - proactiveCaching, - proactiveTypes, - additional); - if (matching != null) - return matching; - } else if (obj.has("items")) { - Iterable items = - obj.>get("items"); - ASObject matching = - processItems( - items, - id, - proactiveCaching, - proactiveTypes, - additional); - if (matching != null) - return matching; - } else if (Objects.equal(id, obj.id())) { - return obj; - } - default: - break; - } - } catch (Throwable t) { - if (silentfail()) - return key; - else propagate(t); - } - throw new UncacheableResponseException(); - } - } - - private ASObject processItems( - Iterable items, - String lookingFor, - boolean proactive, - Set proactiveTypes, - ImmutableSet.Builder additional) { - ASObject matching = null; - for (final ASObject obj : items) { - if (Objects.equal(lookingFor, obj.id())) { - matching = obj; - if (!proactive) break; - } else if (proactive) { - TypeValue objectType = obj.objectType(); - String id = obj.id(); - if (objectType != null && id != null && !Objects.equal(lookingFor,id)) { - String otid = objectType.id(); - if (proactiveTypes.contains(otid)) { - try { - cache().get( - Makers.type(id), - new Callable() { - public TypeValue call() throws Exception { - return obj; - } - }); - } catch (Throwable t) {} - } - } - } - } - return matching; - } - - private static void ensureAlwaysShutdown( - final ResolutionStrategy strategy) { - Thread shutdownThread = - platformThreadFactory() - .newThread(new Runnable() { - public void run() { - try { - strategy.shutdown(); - } catch (Throwable t) {} - } - }); - Runtime.getRuntime() - .addShutdownHook(shutdownThread); - } - - public void shutdown() { - try { - fetcher.shutdown(); - } catch (Throwable t) {} - } -} diff --git a/typext/src/main/java/com/ibm/common/activitystreams/registry/HttpFetch.java b/typext/src/main/java/com/ibm/common/activitystreams/registry/HttpFetch.java deleted file mode 100644 index 813fb41..0000000 --- a/typext/src/main/java/com/ibm/common/activitystreams/registry/HttpFetch.java +++ /dev/null @@ -1,241 +0,0 @@ -package com.ibm.common.activitystreams.registry; - -import static com.google.common.base.Throwables.propagate; - -import java.io.InputStream; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -import org.apache.http.Header; -import org.apache.http.HttpEntity; -import org.apache.http.HttpHost; -import org.apache.http.HttpResponse; -import org.apache.http.StatusLine; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.config.ConnectionConfig; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.config.SocketConfig; -import org.apache.http.conn.HttpClientConnectionManager; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.message.BasicHeader; -import org.apache.http.protocol.HttpContext; - -import com.google.common.base.Optional; -import com.google.common.base.Supplier; -import com.google.common.cache.CacheBuilder; -import com.google.common.cache.CacheLoader; -import com.google.common.cache.LoadingCache; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.ibm.common.activitystreams.ASObject; -import com.ibm.common.activitystreams.IO; -import com.ibm.common.activitystreams.ext.ExtModule; - -public final class HttpFetch - extends CacheLoader { - - static final class Builder - implements Supplier { - - private final RegistryBuilder csfr = - RegistryBuilder.create() - .register("http", PlainConnectionSocketFactory.INSTANCE); - private ConnectionConfig defaultConnectionConfig; - private SocketConfig defaultSocketConfig; - private final ImmutableMap.Builder connectionConfigs = - ImmutableMap.builder(); - private final ImmutableMap.Builder socketConfigs = - ImmutableMap.builder(); - private int maxConnectionsPerRoute = 2; - private int maxConnections = 20; - private final ImmutableSet.Builder
defaultHeaders = - ImmutableSet.builder(); - private String userAgent = null; - private IO io = null; - private HttpClientBuilder builder = - HttpClients.custom(); - - private final CacheBuilder cache = - CacheBuilder.newBuilder() - .expireAfterAccess(10, TimeUnit.MINUTES) - .expireAfterWrite(10, TimeUnit.MINUTES) - .maximumSize(50) - .initialCapacity(50); - private HttpClientConnectionManager manager; - - public Builder customizeCache( - Receiver> receiver) { - if (receiver != null) - receiver.receive(cache); - return this; - } - - public Builder customizeClientBuilder( - Receiver receiver) { - receiver.receive(builder); - return this; - } - - public Builder io(IO io) { - this.io = io; - return this; - } - - public Builder useragent(String ua) { - this.userAgent = ua; - return this; - } - - public Builder defaultHeader(String name, String value) { - defaultHeaders.add(new BasicHeader(name,value)); - return this; - } - - public Builder maxConnectionsPerRoute(int max) { - this.maxConnectionsPerRoute = max; - return this; - } - - public Builder maxConnections(int max) { - this.maxConnections = max; - return this; - } - - public Builder connectionConfig(ConnectionConfig config) { - defaultConnectionConfig = config; - return this; - } - - public Builder connectionConfig(HttpHost host, ConnectionConfig config) { - connectionConfigs.put(host,config); - return this; - } - - public Builder socketConfig(SocketConfig config) { - defaultSocketConfig = config; - return this; - } - - public Builder socketConfig(HttpHost host, SocketConfig config) { - socketConfigs.put(host, config); - return this; - } - - public Builder registerConnectionSocketFactory( - String id, - ConnectionSocketFactory csf) { - csfr.register(id, csf); - return this; - } - - public Builder manager(HttpClientConnectionManager manager) { - this.manager = manager; - return this; - } - - public HttpFetch get() { - return new HttpFetch(this); - } - - } - - private final LoadingCache cache; - private final HttpClientConnectionManager manager; - private final IO io; - private final CloseableHttpClient client; - - HttpFetch(Builder builder) { - this.cache = initCache(builder); - this.manager = initManager(builder); - this.io = initIO(builder); - this.client = initClient(builder); - } - - public void shutdown() { - try { - manager.shutdown(); - } catch (Throwable t) {} - } - - private IO initIO(Builder builder) { - if (builder.io != null) - return builder.io; - return IO.makeDefault(ExtModule.instance); - } - - private CloseableHttpClient initClient(Builder builder) { - HttpClientBuilder b = builder.builder; - b.setConnectionManager(manager); - ImmutableSet
headers = - builder.defaultHeaders.build(); - if (!headers.isEmpty()) - b.setDefaultHeaders(headers); - if (builder.userAgent != null) - b.setUserAgent(builder.userAgent); - return b.build(); - } - - private HttpClientConnectionManager initManager(Builder builder) { - if (builder.manager != null) - return builder.manager; - PoolingHttpClientConnectionManager pm = - new PoolingHttpClientConnectionManager(builder.csfr.build()); - for (Map.Entry entry : builder.connectionConfigs.build().entrySet()) - pm.setConnectionConfig(entry.getKey(), entry.getValue()); - if (builder.defaultConnectionConfig != null) - pm.setDefaultConnectionConfig(builder.defaultConnectionConfig); - for (Map.Entry entry : builder.socketConfigs.build().entrySet()) - pm.setSocketConfig(entry.getKey(), entry.getValue()); - if (builder.defaultSocketConfig != null) - pm.setDefaultSocketConfig(builder.defaultSocketConfig); - pm.setDefaultMaxPerRoute(builder.maxConnectionsPerRoute); - pm.setMaxTotal(builder.maxConnections); - return pm; - } - - private LoadingCache initCache(Builder builder) { - return builder.cache.build(this); - } - - public ASObject fetch(String uri) { - try { - return cache.get(uri); - } catch (Throwable t) { - throw propagate(t); - } - } - - @Override - public ASObject load(String key) throws Exception { - HttpContext context = new HttpClientContext(); - HttpGet get = new HttpGet(key); - HttpResponse resp = client.execute(get, context); - StatusLine status = resp.getStatusLine(); - int code = status.getStatusCode(); - if (code >= 200 && code < 300) { - HttpEntity entity = resp.getEntity(); - if (entity != null) { - // attempt parse - Optional parsed = - parse(entity.getContent()); - if (parsed.isPresent()) - return parsed.get(); - } - } - throw new UncacheableResponseException(); - } - - private Optional parse(InputStream in) { - try { - return Optional.of(io.read(in)); - } catch (Throwable t) { - return Optional.absent(); - } - } -} diff --git a/typext/src/main/java/com/ibm/common/activitystreams/registry/NonOpResolutionStrategy.java b/typext/src/main/java/com/ibm/common/activitystreams/registry/NonOpResolutionStrategy.java deleted file mode 100644 index d911b72..0000000 --- a/typext/src/main/java/com/ibm/common/activitystreams/registry/NonOpResolutionStrategy.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.ibm.common.activitystreams.registry; - -import java.util.concurrent.Callable; - -import com.ibm.common.activitystreams.TypeValue; - -class NonOpResolutionStrategy - implements ResolutionStrategy { - - public Callable resolverFor(final TypeValue tv) { - return new Callable() { - public TypeValue call() throws Exception { - return tv; - } - }; - } - - public Receiver preloader() { - return new Receiver() { - public void receive(TypeValue t) {} - }; - } - - public void shutdown() {} -} diff --git a/typext/src/main/java/com/ibm/common/activitystreams/registry/PreloadStrategy.java b/typext/src/main/java/com/ibm/common/activitystreams/registry/PreloadStrategy.java deleted file mode 100644 index a141f04..0000000 --- a/typext/src/main/java/com/ibm/common/activitystreams/registry/PreloadStrategy.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.ibm.common.activitystreams.registry; - -import com.ibm.common.activitystreams.IO; -import com.ibm.common.activitystreams.TypeValue; - -/** - * Preloads TypeValue instances. - */ -public interface PreloadStrategy { - - void load(IO io, Receiver receiver); - -} diff --git a/typext/src/main/java/com/ibm/common/activitystreams/registry/Receiver.java b/typext/src/main/java/com/ibm/common/activitystreams/registry/Receiver.java deleted file mode 100644 index af61a02..0000000 --- a/typext/src/main/java/com/ibm/common/activitystreams/registry/Receiver.java +++ /dev/null @@ -1,7 +0,0 @@ -package com.ibm.common.activitystreams.registry; - -public interface Receiver { - - void receive(T t); - -} diff --git a/typext/src/main/java/com/ibm/common/activitystreams/registry/ResolutionStrategy.java b/typext/src/main/java/com/ibm/common/activitystreams/registry/ResolutionStrategy.java deleted file mode 100644 index d3c3412..0000000 --- a/typext/src/main/java/com/ibm/common/activitystreams/registry/ResolutionStrategy.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.ibm.common.activitystreams.registry; - -import java.util.concurrent.Callable; - -import com.ibm.common.activitystreams.TypeValue; - -/** - * Implements a strategy for resolving TypeValue identifiers. - */ -public interface ResolutionStrategy { - - /** - * Returns the Receiver instance that is used to - * process preloaded TypeValue instances - * @return Receiver<TypeValue> - */ - Receiver preloader(); - - /** - * Returns a Callable that implements TypeValue resolution - * for the given TypeValue. - */ - Callable resolverFor(TypeValue tv); - - /** - * Shutdown and cleanup any resources - */ - void shutdown(); - - public static final ResolutionStrategy nonop = - new NonOpResolutionStrategy(); -} diff --git a/typext/src/main/java/com/ibm/common/activitystreams/registry/TypeValueRegistry.java b/typext/src/main/java/com/ibm/common/activitystreams/registry/TypeValueRegistry.java deleted file mode 100644 index 1cbf9e8..0000000 --- a/typext/src/main/java/com/ibm/common/activitystreams/registry/TypeValueRegistry.java +++ /dev/null @@ -1,386 +0,0 @@ -package com.ibm.common.activitystreams.registry; - -import static com.google.common.base.Throwables.propagate; -import static com.google.common.util.concurrent.Futures.immediateFuture; -import static com.google.common.util.concurrent.Futures.immediateCancelledFuture; -import static com.google.common.util.concurrent.Futures.addCallback; -import static com.google.common.util.concurrent.MoreExecutors.getExitingExecutorService; -import static com.google.common.util.concurrent.MoreExecutors.listeningDecorator; -import static java.util.concurrent.Executors.newFixedThreadPool; - -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Future; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; - -import com.google.common.base.Function; -import com.google.common.base.Supplier; -import com.google.common.util.concurrent.FutureCallback; -import com.google.common.util.concurrent.ListenableFuture; -import com.google.common.util.concurrent.ListeningExecutorService; -import com.google.common.util.concurrent.Monitor; -import com.ibm.common.activitystreams.IO; -import com.ibm.common.activitystreams.Makers; -import com.ibm.common.activitystreams.TypeValue; -import com.ibm.common.activitystreams.ValueType; -import com.ibm.common.activitystreams.ext.ExtModule; - -/** - * Maintains a registry of resolved TypeValues. If a given TypeValue - * is not currently known, an attempt will be made to resolve the - * value based on the ResolutionStrategy. - */ -public final class TypeValueRegistry - implements Function> { - - /** - * Return a new TypeValueRegistry.Builder - * @return Builder - */ - public static Builder make () { - return new Builder(); - } - - /** - * Create and return a default TypeValueRegistry instance - * @return TypeValueRegistry - */ - public static TypeValueRegistry makeDefault() { - return make().get(); - } - - /** - * Create an return a default silent TypeValueRegistry instance. - * Errors encountered during the resolve process will be silenced, - * causing the process to abort and the original "simple" TypeValue - * to be returned - * @return TypeValueRegistry - */ - public static TypeValueRegistry makeDefaultSilent() { - return make() - .resolver(DefaultResolutionStrategy.make().silentfail().get()) - .get(); - } - - /** - * Create a default TypeValueRegistry instance using the - * given Activity Streams IO object - * @param io - * @return TypeValueRegistry - */ - public static TypeValueRegistry makeDefault(final IO io) { - return make() - .io(io) - .resolver( - DefaultResolutionStrategy - .make() - .customizeFetcher( - new Receiver() { - public void receive(HttpFetch.Builder builder) { - builder.io(io); - } - }) - .get()) - .get(); - } - - /** - * Create a default silent TypeValueRegistry instance using - * the given Activity Streams IO object - * @param io - * @return TypeValueRegistry - */ - public static TypeValueRegistry makeDefaultSilent(final IO io) { - return make() - .io(io) - .resolver( - DefaultResolutionStrategy.make() - .silentfail() - .customizeFetcher( - new Receiver() { - public void receive(HttpFetch.Builder builder) { - builder.io(io); - }}) - .get()) - .get(); - } - - public static enum Status { - LOADING, - READY, - ERROR - } - - public static final class Builder - implements Supplier { - - private ExecutorService executor; - private PreloadStrategy preloader = - ClasspathPreloader.instance; - private ResolutionStrategy strategy = - DefaultResolutionStrategy.makeDefault(); - private IO io; - - /** - * Set the IO object used - * @param io - * @return Builder - */ - public Builder io(IO io) { - this.io = io; - return this; - } - - /** - * Set the ExecutorService used - * @param executor - * @return Builder - */ - public Builder executor(ExecutorService executor) { - this.executor = executor; - return this; - } - - /** - * Set the PreloadStrategy to be used. By default the - * ClasspathPreloader is used. - * @param strategy - * @return Builder - */ - public Builder preloader(PreloadStrategy strategy) { - this.preloader = strategy != null ? - strategy : ClasspathPreloader.instance; - return this; - } - - /** - * Set the ResolutionStrategy to use. By default, the - * DefaultResolutionStrategy is used. - * @param strategy - * @return Builder - */ - public Builder resolver(ResolutionStrategy strategy) { - this.strategy = strategy != null ? - strategy : - DefaultResolutionStrategy.makeDefault(); - return this; - } - - public TypeValueRegistry get() { - return new TypeValueRegistry(this); - } - - } - - private final ResolutionStrategy strategy; - private final ListeningExecutorService executor; - private Status readyStatus = Status.LOADING; - private Throwable loadError = null; - private final ListenableFuture loader; - private final IO io; - - private final Monitor monitor = new Monitor(); - private final Monitor.Guard ready = - new Monitor.Guard(monitor) { - @Override - public boolean isSatisfied() { - return readyStatus != Status.LOADING; - } - }; - - private TypeValueRegistry(Builder builder) { - this.strategy = builder.strategy; - this.io = initIO(builder); - this.executor = initExecutor(builder); - this.loader = preload(builder); - } - - private IO initIO(Builder builder) { - if (builder.io != null) - return builder.io; - return IO.makeDefault(ExtModule.instance); - } - - private ListenableFuture preload(Builder builder) { - final PreloadStrategy strategy = builder.preloader; - final Receiver receiver = this.strategy.preloader(); - ListenableFuture future = - executor.submit(new Runnable() { - public void run() { - strategy.load(io,receiver); - } - }); - addCallback( - future, - new FutureCallback() { - public void onSuccess(Object result) { - monitor.enter(); - try { - readyStatus = Status.READY; - } finally { - monitor.leave(); - } - } - public void onFailure(Throwable t) { - monitor.enter(); - try { - readyStatus = Status.ERROR; - loadError = t; - } finally { - monitor.leave(); - } - } - }); - return future; - } - - public Status readyStatus() { - return readyStatus; - } - - public Throwable loadError() { - return loadError; - } - - /** - * Block indefinitely until the preload process has completed - * @throws InterruptedException - * @throws ExecutionException - */ - public void waitForPreloader() - throws InterruptedException, - ExecutionException { - loader.get(); - } - - /** - * Block up to the given period of time waiting for the preload - * process to complete - * @param duration - * @param unit - * @throws InterruptedException - * @throws ExecutionException - * @throws TimeoutException - */ - public void waitForPreloader(long duration, TimeUnit unit) - throws InterruptedException, - ExecutionException, - TimeoutException { - loader.get(duration,unit); - } - - private ListeningExecutorService initExecutor( - Builder builder) { - if (builder.executor != null) - return listeningDecorator(builder.executor); - return listeningDecorator( - getExitingExecutorService( - (ThreadPoolExecutor)newFixedThreadPool(1))); - } - - /** - * Resolve the given ID without waiting for the preloader to finish - * @param id - * @return Future<TypeValue> - */ - public FutureresolveNoWait(String id) { - return resolveNoWait(Makers.type(id)); - } - - /** - * Resolve the given ID. Will wait for the preload process to complete - * before returning - * @param id - * @return Future<TypeValue> - */ - public Futureresolve(String id) { - return resolve(Makers.type(id)); - } - - /** - * Resolve the given ID. Will wait the specified length of time for the - * preload process to complete before returning - * @param id - * @param duration - * @param unit - * @return Future<TypeValue> - */ - public Futureresolve(String id, long duration, TimeUnit unit) { - return resolve(Makers.type(id),duration,unit); - } - - /** - * Resolve the given ID without waiting for the preload process to complete - * @param tv - * @return Future<TypeValue> - */ - public FutureresolveNoWait(TypeValue tv) { - try { - if (tv == null) return immediateCancelledFuture(); - return tv.valueType() == ValueType.OBJECT || isToken(tv) ? - immediateFuture(tv) : - executor.submit(strategy.resolverFor(tv)); - } catch (Throwable t) { - throw propagate(t); - } - } - - /** - * Resolve the given ID. Will block indefinitely until the preload process - * is complete - * @param tv - * @return Future<TypeValue> - */ - public Future resolve(TypeValue tv) { - try { - if (tv == null) return immediateCancelledFuture(); - if (tv.valueType() == ValueType.OBJECT || isToken(tv)) - return immediateFuture(tv); - monitor.enterWhen(ready); - return executor.submit(strategy.resolverFor(tv)); - } catch (Throwable t) { - throw propagate(t); - } finally { - monitor.leave(); - } - } - - /** - * Resolve the given ID. Will block for the given period of time until - * the preload process is complete - * @param tv - * @param timeout - * @param unit - * @return Future<TypeValue> - */ - public Future resolve( - TypeValue tv, - long timeout, - TimeUnit unit) { - try { - if (tv == null) return immediateCancelledFuture(); - if (tv.valueType() == ValueType.OBJECT || isToken(tv)) - return immediateFuture(tv); - if (monitor.enterWhen(ready, timeout, unit)) { - return executor.submit(strategy.resolverFor(tv)); - } else throw new IllegalStateException(); - } catch (Throwable t) { - throw propagate(t); - } finally { - monitor.leave(); - } - } - - private boolean isToken(TypeValue value) { - String id = value.id(); - return id != null ? - id.matches("[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\.\\^\\_\\`\\|\\~]+") : - false; - } - - public Future apply(TypeValue input) { - return resolve(input); - } -} diff --git a/typext/src/main/java/com/ibm/common/activitystreams/registry/UncacheableResponseException.java b/typext/src/main/java/com/ibm/common/activitystreams/registry/UncacheableResponseException.java deleted file mode 100644 index 3358ac2..0000000 --- a/typext/src/main/java/com/ibm/common/activitystreams/registry/UncacheableResponseException.java +++ /dev/null @@ -1,5 +0,0 @@ -package com.ibm.common.activitystreams.registry; - -public final class UncacheableResponseException extends RuntimeException { - private static final long serialVersionUID = -8868045836116771952L; -} \ No newline at end of file diff --git a/typext/src/main/kotlin/com/ibm/common/activitystreams/ext/ExtAdapter.kt b/typext/src/main/kotlin/com/ibm/common/activitystreams/ext/ExtAdapter.kt new file mode 100644 index 0000000..beb572c --- /dev/null +++ b/typext/src/main/kotlin/com/ibm/common/activitystreams/ext/ExtAdapter.kt @@ -0,0 +1,68 @@ +/** + * Copyright 2013 OpenSocial Foundation + * Copyright 2013 International Business Machines Corporation + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * + * Utility library for working with Activity Streams Actions + * Requires underscorejs. + * + * @author James M Snell (jasnell@us.ibm.com) + */ +package com.ibm.common.activitystreams.ext + +import com.google.common.collect.ImmutableSet +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.i.ASObjectAdapter +import com.ibm.common.activitystreams.i.Model +import com.ibm.common.activitystreams.i.Schema +import java.lang.reflect.Type + +class ExtAdapter + (schema: Schema) : ASObjectAdapter(schema) { + override fun knowsType(type: Type?): Boolean { + if (super.knowsType(type)) return true + return knownTypes.contains(type) + } + + override fun builderFor(type: Type): ASObject.AbstractBuilder<*, *>? { + if (super.knowsType(type)) return super.builderFor(type) + return if (type === Verb::class.java) { + ExtMakers.verb() + } else if (type === ObjectType::class.java) { + ExtMakers.objectType() + } else null + } + + override fun modelFor(type: Type): Model? { + if (super.knowsType(type)) return super.modelFor(type) + return if (type === Verb::class.java) { + schema().forObjectClassOrType( + Verb.Builder::class.java, + "verb" + ) + } else if (type === ObjectType::class.java) { + schema().forObjectClassOrType( + ObjectType.Builder::class.java, + "objectType" + ) + } else null + } + + companion object { + private val knownTypes: ImmutableSet = ImmutableSet.of( + Verb::class.java, + ObjectType::class.java + ) + } +} diff --git a/typext/src/main/kotlin/com/ibm/common/activitystreams/ext/ExtMakers.kt b/typext/src/main/kotlin/com/ibm/common/activitystreams/ext/ExtMakers.kt new file mode 100644 index 0000000..e5c2e16 --- /dev/null +++ b/typext/src/main/kotlin/com/ibm/common/activitystreams/ext/ExtMakers.kt @@ -0,0 +1,19 @@ +package com.ibm.common.activitystreams.ext + +object ExtMakers { + fun verb(): Verb.Builder { + return Verb.Builder() + } + + fun verb(id: String?): Verb.Builder? { + return verb().id(id) + } + + fun objectType(): ObjectType.Builder { + return ObjectType.Builder() + } + + fun objectType(id: String?): ObjectType.Builder? { + return objectType().id(id) + } +} diff --git a/typext/src/main/kotlin/com/ibm/common/activitystreams/ext/ExtModule.kt b/typext/src/main/kotlin/com/ibm/common/activitystreams/ext/ExtModule.kt new file mode 100644 index 0000000..bc49c6c --- /dev/null +++ b/typext/src/main/kotlin/com/ibm/common/activitystreams/ext/ExtModule.kt @@ -0,0 +1,35 @@ +package com.ibm.common.activitystreams.ext + +import com.ibm.common.activitystreams.IO +import com.ibm.common.activitystreams.i.Model +import com.ibm.common.activitystreams.i.Schema +import com.ibm.common.activitystreams.util.Module + +class ExtModule : Module { + override fun apply(builder: Schema.Builder) { + builder.map("verb", verb) + builder.map("objectType", objectType) + } + + override fun apply( + builder: IO.Builder, + schema: Schema + ) { + val base = ExtAdapter(schema) + builder.adapter(Verb::class.java, base) + builder.adapter(ObjectType::class.java, base) + } + + companion object { + @JvmField + var instance: Module = ExtModule() + + val verb: Model = Schema.`object`.template() + .type(Verb::class.java, Verb.Builder::class.java) + .get() + + val objectType: Model = Schema.`object`.template() + .type(ObjectType::class.java, ObjectType.Builder::class.java) + .get() + } +} diff --git a/typext/src/main/kotlin/com/ibm/common/activitystreams/ext/ObjectType.kt b/typext/src/main/kotlin/com/ibm/common/activitystreams/ext/ObjectType.kt new file mode 100644 index 0000000..5be3fa6 --- /dev/null +++ b/typext/src/main/kotlin/com/ibm/common/activitystreams/ext/ObjectType.kt @@ -0,0 +1,18 @@ +package com.ibm.common.activitystreams.ext + +import com.ibm.common.activitystreams.ASObject + +class ObjectType +private constructor(builder: Builder) : ASObject(builder) { + class Builder + internal constructor() : + AbstractBuilder() { + init { + objectType("objectType") + } + + override fun get(): ObjectType { + return ObjectType(this) + } + } +} diff --git a/typext/src/main/kotlin/com/ibm/common/activitystreams/ext/Verb.kt b/typext/src/main/kotlin/com/ibm/common/activitystreams/ext/Verb.kt new file mode 100644 index 0000000..accc7f9 --- /dev/null +++ b/typext/src/main/kotlin/com/ibm/common/activitystreams/ext/Verb.kt @@ -0,0 +1,17 @@ +package com.ibm.common.activitystreams.ext + +import com.ibm.common.activitystreams.ASObject + +class Verb +private constructor(builder: Builder) : ASObject(builder) { + class Builder + internal constructor() : AbstractBuilder() { + init { + objectType("verb") + } + + override fun get(): Verb { + return Verb(this) + } + } +} diff --git a/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/CachingResolutionStrategy.kt b/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/CachingResolutionStrategy.kt new file mode 100644 index 0000000..f1b3ead --- /dev/null +++ b/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/CachingResolutionStrategy.kt @@ -0,0 +1,100 @@ +package com.ibm.common.activitystreams.registry + +import com.google.common.base.Supplier +import com.google.common.base.Throwables +import com.google.common.cache.CacheBuilder +import com.google.common.cache.CacheLoader +import com.google.common.cache.LoadingCache +import com.ibm.common.activitystreams.Makers.type +import com.ibm.common.activitystreams.TypeValue +import com.ibm.common.activitystreams.ValueType +import java.util.concurrent.Callable +import java.util.concurrent.TimeUnit + +abstract class CachingResolutionStrategy +internal constructor(builder: AbstractBuilder<*, *>) : + ResolutionStrategy { + abstract class AbstractBuilder + > + : Supplier { + var silentfail: Boolean = false + val cache: CacheBuilder = CacheBuilder.newBuilder() + .expireAfterAccess(10, TimeUnit.MINUTES) + .expireAfterWrite(10, TimeUnit.MINUTES) + .maximumSize(100) + .initialCapacity(50) + + fun silentfail(): B { + this.silentfail = true + return this as B + } + + fun customizeCache(receiver: Receiver?>?): B { + receiver?.receive(cache) + return this as B + } + } + + private val cache: LoadingCache + private val silentfail: Boolean + + protected fun cache(): LoadingCache { + return cache + } + + init { + this.cache = initCache(builder) + this.silentfail = builder.silentfail + } + + protected fun silentfail(): Boolean { + return silentfail + } + + private fun initCache(builder: AbstractBuilder<*, *>): LoadingCache { + return builder.cache.build(loader()) + } + + override fun resolverFor(tv: TypeValue): Callable { + return Resolver(tv) + } + + protected abstract fun loader(): CacheLoader + + inner class Resolver + internal constructor(private val input: TypeValue?) : Callable { + @Throws(Exception::class) + override fun call(): TypeValue? { + try { + if (input == null) return null + return when (input.valueType()) { + ValueType.OBJECT -> input + ValueType.SIMPLE -> cache[input] + else -> throw IllegalArgumentException() + } + } catch (t: Throwable) { + if (silentfail()) return input + else throw Throwables.propagate(t) + } + } + } + + override fun preloader(): Receiver { + return CachePreloader(cache()) + } + + private class CachePreloader + (private val cache: LoadingCache) : + Receiver { + override fun receive(t: TypeValue) { + if (t.valueType() == ValueType.OBJECT && t.id() != null) { + val tv = type(t.id()) + cache.invalidate(tv) + try { + cache[tv, Callable { t }] + } catch (e: Throwable) { + } + } + } + } +} diff --git a/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/ClasspathPreloader.kt b/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/ClasspathPreloader.kt new file mode 100644 index 0000000..c665831 --- /dev/null +++ b/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/ClasspathPreloader.kt @@ -0,0 +1,107 @@ +package com.ibm.common.activitystreams.registry + +import com.google.common.base.Charsets +import com.google.common.base.Function +import com.google.common.base.Supplier +import com.google.common.base.Throwables +import com.google.common.collect.ImmutableList +import com.google.common.hash.BloomFilter +import com.google.common.hash.Funnels +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.Collection +import com.ibm.common.activitystreams.IO +import com.ibm.common.activitystreams.TypeValue +import java.io.InputStream +import java.io.ObjectInputStream +import java.net.URL +import java.util.* + +class ClasspathPreloader +private constructor(builder: Builder) : PreloadStrategy { + class Builder + + : Supplier { + var loader: ClassLoader = Thread.currentThread().contextClassLoader + var avoidDuplicates: Boolean = false + + fun avoidDuplicates(): Builder { + this.avoidDuplicates = true + return this + } + + fun classLoader(loader: ClassLoader?): Builder { + this.loader = loader ?: Thread.currentThread().contextClassLoader + return this + } + + override fun get(): ClasspathPreloader { + return ClasspathPreloader(this) + } + } + + private val loader: ClassLoader + private val avoidDuplicates: Boolean + + override fun load(io: IO, receiver: Receiver) { + val filter = + if (avoidDuplicates) BloomFilter.create(Funnels.stringFunnel(Charsets.UTF_8), 1000) else null + + try { + for (`in` in streams.apply(loader.getResources("typeValues.bin"))!!) { + try { + val oin = ObjectInputStream(`in`) + val col = oin.readObject() as Collection + load(col, receiver, filter) + } catch (t: Throwable) { + } + } + + for (`in` in streams.apply(loader.getResources("typeValues.json"))!!) { + try { + load(io.readAsCollection(`in`), receiver, filter) + } catch (t: Throwable) { + } + } + } catch (t: Throwable) { + throw Throwables.propagate(t) + } + } + + private fun load( + col: Collection?, + receiver: Receiver, + filter: BloomFilter? + ) { + if (col != null && receiver != null) for (obj in col.items()) if (obj.id() != null && (filter == null || filter.put( + obj.id() + )) + ) { + try { + receiver.receive(obj) + } catch (t: Throwable) { + } + } + } + + init { + this.loader = builder.loader + this.avoidDuplicates = builder.avoidDuplicates + } + + companion object { + private val streams: Function, Iterable> = + Function, Iterable> { input -> + val list = + ImmutableList.builder() + while (input?.hasMoreElements() == true) { + try { + list.add(input.nextElement().openStream()) + } catch (t: Throwable) { + } + } + list.build() + } + + val instance: PreloadStrategy = Builder().get() + } +} diff --git a/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/DefaultResolutionStrategy.kt b/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/DefaultResolutionStrategy.kt new file mode 100644 index 0000000..a3e4288 --- /dev/null +++ b/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/DefaultResolutionStrategy.kt @@ -0,0 +1,186 @@ +package com.ibm.common.activitystreams.registry + +import com.google.common.base.Objects +import com.google.common.base.Throwables +import com.google.common.cache.CacheLoader +import com.google.common.collect.ImmutableSet +import com.google.common.util.concurrent.MoreExecutors +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.Collection +import com.ibm.common.activitystreams.Makers.type +import com.ibm.common.activitystreams.TypeValue +import com.ibm.common.activitystreams.ValueType +import java.util.concurrent.Callable + +class DefaultResolutionStrategy +private constructor(builder: Builder) : + CachingResolutionStrategy(builder) { + class Builder + + : AbstractBuilder() { + var proactive: Boolean = false + val fetcherBuilder = HttpFetch.Builder() + val proactiveTypes: ImmutableSet.Builder = ImmutableSet.builder() + .add("verb") + .add("objectType") + + fun customizeFetcher(receiver: Receiver): Builder { + receiver.receive(fetcherBuilder) + return this + } + + /** + * Tells the loader to proactively cache additional typevalue + * identifiers that happen to be discovered when attempting to + * resolve a given typevalue. + * @return + */ + fun proactiveCaching(): Builder { + this.proactive = true + return this + } + + /** + * Specifies additional objectType identifiers to watch for when + * proactiveCaching is enabled. + * @param typeValueId + * @return + */ + fun typeValueObjectType(typeValueId: String?): Builder { + proactiveTypes.add(typeValueId) + return this + } + + override fun get(): DefaultResolutionStrategy { + return DefaultResolutionStrategy(this) + } + } + + private val proactiveCaching = builder.proactive + private val proactiveTypes: ImmutableSet = builder.proactiveTypes.build() + private val fetcher: HttpFetch + + init { + this.fetcher = initFetcher(builder) + ensureAlwaysShutdown(this) + } + + private fun initFetcher(builder: Builder): HttpFetch { + return builder.fetcherBuilder.get() + } + + override fun loader(): CacheLoader { + return DefaultCacheLoader() + } + + private inner class DefaultCacheLoader + + : CacheLoader() { + @Throws(Exception::class) + override fun load(key: TypeValue): TypeValue { + try { + when (key.valueType()) { + ValueType.OBJECT -> return key // type is already resolved + ValueType.SIMPLE -> { + val id = key.id() + val obj = fetcher.fetch(id) // attempt to fetch an object + val additional = + ImmutableSet.builder() + if (obj is Collection) { + val matching = + processItems( + obj.items(), + id, + proactiveCaching, + proactiveTypes, + additional + ) + if (matching != null) return matching + } else if (obj!!.has("items")) { + val items = + obj.get>("items") + val matching = + processItems( + items!!, + id, + proactiveCaching, + proactiveTypes, + additional + ) + if (matching != null) return matching + } else if (Objects.equal(id, obj.id())) { + return obj + } + } + + else -> {} + } + } catch (t: Throwable) { + if (silentfail()) return key + else Throwables.propagate(t) + } + throw UncacheableResponseException + } + } + + private fun processItems( + items: Iterable, + lookingFor: String?, + proactive: Boolean, + proactiveTypes: Set, + additional: ImmutableSet.Builder + ): ASObject? { + var matching: ASObject? = null + for (obj in items) { + if (Objects.equal(lookingFor, obj.id())) { + matching = obj + if (!proactive) break + } else if (proactive) { + val objectType = obj.objectType() + val id = obj.id() + if (objectType != null && id != null && !Objects.equal(lookingFor, id)) { + val otid = objectType.id() + if (proactiveTypes.contains(otid)) { + try { + cache()[type(id), Callable { obj }] + } catch (t: Throwable) { + } + } + } + } + } + return matching + } + + override fun shutdown() { + try { + fetcher.shutdown() + } catch (t: Throwable) { + } + } + + companion object { + fun make(): Builder { + return Builder() + } + + fun makeDefault(): DefaultResolutionStrategy { + return make().get() + } + + private fun ensureAlwaysShutdown( + strategy: ResolutionStrategy + ) { + val shutdownThread = + MoreExecutors.platformThreadFactory() + .newThread { + try { + strategy.shutdown() + } catch (t: Throwable) { + } + } + Runtime.getRuntime() + .addShutdownHook(shutdownThread) + } + } +} diff --git a/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/HttpFetch.kt b/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/HttpFetch.kt new file mode 100644 index 0000000..eee9cf1 --- /dev/null +++ b/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/HttpFetch.kt @@ -0,0 +1,229 @@ +package com.ibm.common.activitystreams.registry + +import com.google.common.base.Optional +import com.google.common.base.Supplier +import com.google.common.base.Throwables +import com.google.common.cache.CacheBuilder +import com.google.common.cache.CacheLoader +import com.google.common.cache.LoadingCache +import com.google.common.collect.ImmutableMap +import com.google.common.collect.ImmutableSet +import com.ibm.common.activitystreams.ASObject +import com.ibm.common.activitystreams.IO +import com.ibm.common.activitystreams.IO.Companion.makeDefault +import com.ibm.common.activitystreams.ext.ExtModule +import org.apache.http.Header +import org.apache.http.HttpHost +import org.apache.http.HttpResponse +import org.apache.http.client.methods.HttpGet +import org.apache.http.client.protocol.HttpClientContext +import org.apache.http.config.ConnectionConfig +import org.apache.http.config.RegistryBuilder +import org.apache.http.config.SocketConfig +import org.apache.http.conn.HttpClientConnectionManager +import org.apache.http.conn.socket.ConnectionSocketFactory +import org.apache.http.conn.socket.PlainConnectionSocketFactory +import org.apache.http.impl.client.CloseableHttpClient +import org.apache.http.impl.client.HttpClientBuilder +import org.apache.http.impl.client.HttpClients +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager +import org.apache.http.message.BasicHeader +import org.apache.http.protocol.HttpContext +import java.io.InputStream +import java.util.concurrent.TimeUnit + +class HttpFetch +internal constructor(builder: Builder) : + CacheLoader() { + class Builder + + : Supplier { + val csfr: RegistryBuilder = RegistryBuilder.create() + .register("http", PlainConnectionSocketFactory.INSTANCE) + var defaultConnectionConfig: ConnectionConfig? = null + var defaultSocketConfig: SocketConfig? = null + val connectionConfigs: ImmutableMap.Builder = ImmutableMap.builder() + val socketConfigs: ImmutableMap.Builder = ImmutableMap.builder() + var maxConnectionsPerRoute: Int = 2 + var maxConnections: Int = 20 + val defaultHeaders: ImmutableSet.Builder
= ImmutableSet.builder() + var userAgent: String? = null + var io: IO? = null + val builder: HttpClientBuilder = HttpClients.custom() + + val cache: CacheBuilder = CacheBuilder.newBuilder() + .expireAfterAccess(10, TimeUnit.MINUTES) + .expireAfterWrite(10, TimeUnit.MINUTES) + .maximumSize(50) + .initialCapacity(50) + var manager: HttpClientConnectionManager? = null + + fun customizeCache( + receiver: Receiver?>? + ): Builder { + receiver?.receive(cache) + return this + } + + fun customizeClientBuilder( + receiver: Receiver + ): Builder { + receiver.receive(builder) + return this + } + + fun io(io: IO?): Builder { + this.io = io + return this + } + + fun useragent(ua: String?): Builder { + this.userAgent = ua + return this + } + + fun defaultHeader(name: String, value: String?): Builder { + defaultHeaders.add(BasicHeader(name, value)) + return this + } + + fun maxConnectionsPerRoute(max: Int): Builder { + this.maxConnectionsPerRoute = max + return this + } + + fun maxConnections(max: Int): Builder { + this.maxConnections = max + return this + } + + fun connectionConfig(config: ConnectionConfig?): Builder { + defaultConnectionConfig = config + return this + } + + fun connectionConfig(host: HttpHost, config: ConnectionConfig): Builder { + connectionConfigs.put(host, config) + return this + } + + fun socketConfig(config: SocketConfig?): Builder { + defaultSocketConfig = config + return this + } + + fun socketConfig(host: HttpHost, config: SocketConfig): Builder { + socketConfigs.put(host, config) + return this + } + + fun registerConnectionSocketFactory( + id: String, + csf: ConnectionSocketFactory + ): Builder { + csfr.register(id, csf) + return this + } + + fun manager(manager: HttpClientConnectionManager?): Builder { + this.manager = manager + return this + } + + override fun get(): HttpFetch { + return HttpFetch(this) + } + } + + private val cache: LoadingCache + private val manager: HttpClientConnectionManager + private val io: IO + private val client: CloseableHttpClient + + init { + this.cache = initCache(builder) + this.manager = initManager(builder) + this.io = initIO(builder) + this.client = initClient(builder) + } + + fun shutdown() { + try { + manager.shutdown() + } catch (t: Throwable) { + } + } + + private fun initIO(builder: Builder): IO { + if (builder.io != null) return builder.io!! + return makeDefault(ExtModule.Companion.instance) + } + + private fun initClient(builder: Builder): CloseableHttpClient { + val b = builder.builder + b.setConnectionManager(manager) + val headers = + builder.defaultHeaders.build() + if (!headers.isEmpty()) b.setDefaultHeaders(headers) + if (builder.userAgent != null) b.setUserAgent(builder.userAgent) + return b.build() + } + + private fun initManager(builder: Builder): HttpClientConnectionManager { + if (builder.manager != null) return builder.manager!! + val pm = + PoolingHttpClientConnectionManager(builder.csfr.build()) + for ((key, value) in builder.connectionConfigs.build()) pm.setConnectionConfig( + key, + value + ) + if (builder.defaultConnectionConfig != null) pm.defaultConnectionConfig = builder.defaultConnectionConfig + for ((key, value) in builder.socketConfigs.build()) pm.setSocketConfig( + key, + value + ) + if (builder.defaultSocketConfig != null) pm.defaultSocketConfig = builder.defaultSocketConfig + pm.defaultMaxPerRoute = builder.maxConnectionsPerRoute + pm.maxTotal = builder.maxConnections + return pm + } + + private fun initCache(builder: Builder): LoadingCache { + return builder.cache.build(this) + } + + fun fetch(uri: String?): ASObject { + try { + return cache[uri] + } catch (t: Throwable) { + throw Throwables.propagate(t) + } + } + + @Throws(Exception::class) + override fun load(key: String?): ASObject { + val context: HttpContext = HttpClientContext() + val get = HttpGet(key) + val resp: HttpResponse = client.execute(get, context) + val status = resp.statusLine + val code = status.statusCode + if (code >= 200 && code < 300) { + val entity = resp.entity + if (entity != null) { + // attempt parse + val parsed = + parse(entity.content) + if (parsed.isPresent) return parsed.get() + } + } + throw UncacheableResponseException + } + + private fun parse(`in`: InputStream): Optional { + return try { + Optional.of(io.read(`in`)) + } catch (t: Throwable) { + Optional.absent() + } + } +} diff --git a/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/NonOpResolutionStrategy.kt b/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/NonOpResolutionStrategy.kt new file mode 100644 index 0000000..ceef44f --- /dev/null +++ b/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/NonOpResolutionStrategy.kt @@ -0,0 +1,18 @@ +package com.ibm.common.activitystreams.registry + +import com.ibm.common.activitystreams.TypeValue +import java.util.concurrent.Callable + +internal class NonOpResolutionStrategy + + : ResolutionStrategy { + override fun resolverFor(tv: TypeValue): Callable { + return Callable { tv } + } + + override fun preloader(): Receiver { + return Receiver { } + } + + override fun shutdown() {} +} diff --git a/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/PreloadStrategy.kt b/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/PreloadStrategy.kt new file mode 100644 index 0000000..d8c36f2 --- /dev/null +++ b/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/PreloadStrategy.kt @@ -0,0 +1,11 @@ +package com.ibm.common.activitystreams.registry + +import com.ibm.common.activitystreams.IO +import com.ibm.common.activitystreams.TypeValue + +/** + * Preloads TypeValue instances. + */ +interface PreloadStrategy { + fun load(io: IO, receiver: Receiver) +} diff --git a/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/Receiver.kt b/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/Receiver.kt new file mode 100644 index 0000000..fffb5ae --- /dev/null +++ b/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/Receiver.kt @@ -0,0 +1,5 @@ +package com.ibm.common.activitystreams.registry + +fun interface Receiver { + fun receive(t: T) +} diff --git a/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/ResolutionStrategy.kt b/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/ResolutionStrategy.kt new file mode 100644 index 0000000..e2c66e5 --- /dev/null +++ b/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/ResolutionStrategy.kt @@ -0,0 +1,31 @@ +package com.ibm.common.activitystreams.registry + +import com.ibm.common.activitystreams.TypeValue +import java.util.concurrent.Callable + +/** + * Implements a strategy for resolving TypeValue identifiers. + */ +interface ResolutionStrategy { + /** + * Returns the Receiver instance that is used to + * process preloaded TypeValue instances + * @return Receiver<TypeValue> + */ + fun preloader(): Receiver + + /** + * Returns a Callable that implements TypeValue resolution + * for the given TypeValue. + */ + fun resolverFor(tv: TypeValue): Callable + + /** + * Shutdown and cleanup any resources + */ + fun shutdown() + + companion object { + val nonop: ResolutionStrategy = NonOpResolutionStrategy() + } +} diff --git a/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/TypeValueRegistry.kt b/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/TypeValueRegistry.kt new file mode 100644 index 0000000..8d0c0f3 --- /dev/null +++ b/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/TypeValueRegistry.kt @@ -0,0 +1,363 @@ +package com.ibm.common.activitystreams.registry + +import com.google.common.base.Function +import com.google.common.base.Supplier +import com.google.common.base.Throwables +import com.google.common.util.concurrent.* +import com.ibm.common.activitystreams.IO +import com.ibm.common.activitystreams.Makers.type +import com.ibm.common.activitystreams.TypeValue +import com.ibm.common.activitystreams.ValueType +import com.ibm.common.activitystreams.ext.ExtModule +import java.util.concurrent.* + +/** + * Maintains a registry of resolved TypeValues. If a given TypeValue + * is not currently known, an attempt will be made to resolve the + * value based on the ResolutionStrategy. + */ +class TypeValueRegistry +private constructor(builder: Builder) : + Function> { + enum class Status { + LOADING, + READY, + ERROR + } + + class Builder + + : Supplier { + var executor: ExecutorService? = null + var preloader: PreloadStrategy = ClasspathPreloader.Companion.instance + var strategy: ResolutionStrategy = DefaultResolutionStrategy.Companion.makeDefault() + var io: IO? = null + + /** + * Set the IO object used + * @param io + * @return Builder + */ + fun io(io: IO?): Builder { + this.io = io + return this + } + + /** + * Set the ExecutorService used + * @param executor + * @return Builder + */ + fun executor(executor: ExecutorService?): Builder { + this.executor = executor + return this + } + + /** + * Set the PreloadStrategy to be used. By default the + * ClasspathPreloader is used. + * @param strategy + * @return Builder + */ + fun preloader(strategy: PreloadStrategy?): Builder { + this.preloader = strategy ?: ClasspathPreloader.Companion.instance + return this + } + + /** + * Set the ResolutionStrategy to use. By default, the + * DefaultResolutionStrategy is used. + * @param strategy + * @return Builder + */ + fun resolver(strategy: ResolutionStrategy?): Builder { + this.strategy = strategy + ?: DefaultResolutionStrategy.Companion.makeDefault() + return this + } + + override fun get(): TypeValueRegistry { + return TypeValueRegistry(this) + } + } + + private val strategy: ResolutionStrategy + private val executor: ListeningExecutorService + private var readyStatus = Status.LOADING + private var loadError: Throwable? = null + private val loader: ListenableFuture<*> + private val io: IO + + private val monitor = Monitor() + private val ready: Monitor.Guard = object : Monitor.Guard(monitor) { + override fun isSatisfied(): Boolean { + return readyStatus != Status.LOADING + } + } + + init { + this.strategy = builder.strategy + this.io = initIO(builder) + this.executor = initExecutor(builder) + this.loader = preload(builder) + } + + private fun initIO(builder: Builder): IO { + if (builder.io != null) return builder.io!! + return IO.makeDefault(ExtModule.Companion.instance) + } + + private fun preload(builder: Builder): ListenableFuture<*> { + val strategy = builder.preloader + val receiver = this.strategy.preloader() + val future = + executor.submit { strategy.load(io, receiver) } + Futures.addCallback( + future, + object : FutureCallback { + override fun onSuccess(result: Any?) { + monitor.enter() + try { + readyStatus = Status.READY + } finally { + monitor.leave() + } + } + + override fun onFailure(t: Throwable) { + monitor.enter() + try { + readyStatus = Status.ERROR + loadError = t + } finally { + monitor.leave() + } + } + }) + return future + } + + fun readyStatus(): Status { + return readyStatus + } + + fun loadError(): Throwable? { + return loadError + } + + /** + * Block indefinitely until the preload process has completed + * @throws InterruptedException + * @throws ExecutionException + */ + @Throws(InterruptedException::class, ExecutionException::class) + fun waitForPreloader() { + loader.get() + } + + /** + * Block up to the given period of time waiting for the preload + * process to complete + * @param duration + * @param unit + * @throws InterruptedException + * @throws ExecutionException + * @throws TimeoutException + */ + @Throws( + InterruptedException::class, + ExecutionException::class, + TimeoutException::class + ) + fun waitForPreloader(duration: Long, unit: TimeUnit) { + loader[duration, unit] + } + + private fun initExecutor( + builder: Builder + ): ListeningExecutorService { + if (builder.executor != null) return MoreExecutors.listeningDecorator(builder.executor) + return MoreExecutors.listeningDecorator( + MoreExecutors.getExitingExecutorService( + Executors.newFixedThreadPool(1) as ThreadPoolExecutor + ) + ) + } + + /** + * Resolve the given ID without waiting for the preloader to finish + * @param id + * @return Future<TypeValue> + */ + fun resolveNoWait(id: String?): Future { + return resolveNoWait(type(id)) + } + + /** + * Resolve the given ID. Will wait for the preload process to complete + * before returning + * @param id + * @return Future<TypeValue> + */ + fun resolve(id: String?): Future { + return resolve(type(id)) + } + + /** + * Resolve the given ID. Will wait the specified length of time for the + * preload process to complete before returning + * @param id + * @param duration + * @param unit + * @return Future<TypeValue> + */ + fun resolve(id: String?, duration: Long, unit: TimeUnit): Future { + return resolve(type(id), duration, unit) + } + + /** + * Resolve the given ID without waiting for the preload process to complete + * @param tv + * @return Future<TypeValue> + */ + fun resolveNoWait(tv: TypeValue?): Future { + try { + if (tv == null) return Futures.immediateCancelledFuture() + return if (tv.valueType() == ValueType.OBJECT || isToken(tv)) Futures.immediateFuture(tv) else executor.submit( + strategy.resolverFor(tv) + ) + } catch (t: Throwable) { + throw Throwables.propagate(t) + } + } + + /** + * Resolve the given ID. Will block indefinitely until the preload process + * is complete + * @param tv + * @return Future<TypeValue> + */ + fun resolve(tv: TypeValue?): Future { + try { + if (tv == null) return Futures.immediateCancelledFuture() + if (tv.valueType() == ValueType.OBJECT || isToken(tv)) return Futures.immediateFuture(tv) + monitor.enterWhen(ready) + return executor.submit(strategy.resolverFor(tv)) + } catch (t: Throwable) { + throw Throwables.propagate(t) + } finally { + monitor.leave() + } + } + + /** + * Resolve the given ID. Will block for the given period of time until + * the preload process is complete + * @param tv + * @param timeout + * @param unit + * @return Future<TypeValue> + */ + fun resolve( + tv: TypeValue?, + timeout: Long, + unit: TimeUnit + ): Future { + try { + if (tv == null) return Futures.immediateCancelledFuture() + if (tv.valueType() == ValueType.OBJECT || isToken(tv)) return Futures.immediateFuture(tv) + if (monitor.enterWhen(ready, timeout, unit)) { + return executor.submit(strategy.resolverFor(tv)) + } else throw IllegalStateException() + } catch (t: Throwable) { + throw Throwables.propagate(t) + } finally { + monitor.leave() + } + } + + private fun isToken(value: TypeValue): Boolean { + val id = value.id() + return id?.matches("[A-Za-z0-9\\!\\#\\$\\%\\&\\'\\*\\+\\-\\.\\^\\_\\`\\|\\~]+".toRegex()) ?: false + } + + override fun apply(input: TypeValue?): Future { + return resolve(input) + } + + companion object { + /** + * Return a new TypeValueRegistry.Builder + * @return Builder + */ + fun make(): Builder { + return Builder() + } + + /** + * Create and return a default TypeValueRegistry instance + * @return TypeValueRegistry + */ + fun makeDefault(): TypeValueRegistry { + return make().get() + } + + /** + * Create an return a default silent TypeValueRegistry instance. + * Errors encountered during the resolve process will be silenced, + * causing the process to abort and the original "simple" TypeValue + * to be returned + * @return TypeValueRegistry + */ + fun makeDefaultSilent(): TypeValueRegistry { + return make() + .resolver(DefaultResolutionStrategy.Companion.make().silentfail()!!.get()) + .get() + } + + /** + * Create a default TypeValueRegistry instance using the + * given Activity Streams IO object + * @param io + * @return TypeValueRegistry + */ + fun makeDefault(io: IO?): TypeValueRegistry { + return make() + .io(io) + .resolver( + DefaultResolutionStrategy.Companion.make() + .customizeFetcher { builder -> + builder.io( + io + ) + } + .get() + ) + .get() + } + + /** + * Create a default silent TypeValueRegistry instance using + * the given Activity Streams IO object + * @param io + * @return TypeValueRegistry + */ + @JvmStatic + fun makeDefaultSilent(io: IO?): TypeValueRegistry { + return make() + .io(io) + .resolver( + DefaultResolutionStrategy.Companion.make() + .silentfail() + .customizeFetcher( + Receiver { builder -> + builder.io( + io + ) + }) + .get() + ) + .get() + } + } +} diff --git a/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/UncacheableResponseException.kt b/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/UncacheableResponseException.kt new file mode 100644 index 0000000..b23b253 --- /dev/null +++ b/typext/src/main/kotlin/com/ibm/common/activitystreams/registry/UncacheableResponseException.kt @@ -0,0 +1,5 @@ +package com.ibm.common.activitystreams.registry + +object UncacheableResponseException : RuntimeException() { + private const val serialVersionUID = -8868045836116771952L +} \ No newline at end of file