提交 c51a7be6 编写于 作者: 楼国栋

Merge branch 'feature/huawei_push' into 'wrdp'

集成华为推送服务

See merge request o2oa/o2oa!5442
{
"enable": false,
"enable": true,
"appKey": "9aca7cc20fe0cc987cd913ca",
"masterSecret": "96ee7e2e0daffd51bac57815",
"huaweiPushEnable": false,
"huaweiPushConfig": {
"appId": "100016851",
"appSecret": "b3ad9287e8d1d16d0aad8fde66e59118"
},
"###enable": "是否启用.###",
"###appKey": "极光推送应用的AppKey###",
"###masterSecret": "极光推送应用的Master Secret###"
"###masterSecret": "极光推送应用的Master Secret###",
"###huaweiPushEnable": "是否启用华为推送###",
"###huaweiPushConfig": "华为推送配置###"
}
\ No newline at end of file
package com.x.base.core.project.config;
import com.x.base.core.project.annotation.FieldDescribe;
import com.x.base.core.project.bean.NameValuePair;
import com.x.base.core.project.connection.HttpConnection;
import com.x.base.core.project.gson.GsonPropertyObject;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class HuaweiPushConfig extends ConfigObject {
private static final String O2_app_id_default = "100016851";
private static final String O2_app_secret_default = "b3ad9287e8d1d16d0aad8fde66e59118";
// 获取accesssToken的url
private static final String huawei_get_token_url = "https://oauth-login.cloud.huawei.com/oauth2/v3/token";
// 华为推送消息接口url
private static final String huawei_push_message_url = "https://push-api.cloud.huawei.com/v1/{0}/messages:send";
public static HuaweiPushConfig defaultInstance() {
return new HuaweiPushConfig();
}
public HuaweiPushConfig() {
this.appId = O2_app_id_default;
this.appSecret = O2_app_secret_default;
}
@FieldDescribe("华为推送应用的appId")
private String appId;
@FieldDescribe("华为推送应用的appSecret")
private String appSecret;
public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId;
}
public String getAppSecret() {
return appSecret;
}
public void setAppSecret(String appSecret) {
this.appSecret = appSecret;
}
// accessToken 有一段时间可以通用,缓存下来
private static String cacheAccessToken;
private static Date cacheAccessTokenDate;
/**
* 推送消息的url
* @return
*/
public String getPushUrl() {
return MessageFormat.format(huawei_push_message_url, this.getAppId());
}
/**
* 华为accessToken 获取
* @return
* @throws Exception
*/
public String accessToken() throws Exception {
if ((StringUtils.isNotEmpty(cacheAccessToken) && (null != cacheAccessTokenDate))
&& (cacheAccessTokenDate.after(new Date()))) {
return cacheAccessToken;
} else {
List<NameValuePair> heads = new ArrayList<>();
heads.add(new NameValuePair("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8"));
HuaweiAccessTokenResp resp = HttpConnection.postAsObject(huawei_get_token_url, heads, this.createRequestBody(), HuaweiAccessTokenResp.class);
cacheAccessToken = resp.getAccess_token();
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MINUTE, 90);
cacheAccessTokenDate = cal.getTime();
return cacheAccessToken;
}
}
private String createRequestBody() {
return MessageFormat.format("grant_type=client_credentials&client_secret={0}&client_id={1}", this.getAppSecret(), this.getAppId());
}
public static class HuaweiAccessTokenResp extends GsonPropertyObject {
private String access_token;
private Integer expires_in;
private String token_type;
public String getAccess_token() {
return access_token;
}
public void setAccess_token(String access_token) {
this.access_token = access_token;
}
public Integer getExpires_in() {
return expires_in;
}
public void setExpires_in(Integer expires_in) {
this.expires_in = expires_in;
}
public String getToken_type() {
return token_type;
}
public void setToken_type(String token_type) {
this.token_type = token_type;
}
}
}
......@@ -13,9 +13,11 @@ public class JpushConfig extends ConfigObject {
return new JpushConfig();
}
public JpushConfig() {
this.enable = false;
this.enable = true;
this.appKey = O2_app_key_default;
this.masterSecret = O2_master_secret_default;
this.huaweiPushEnable = false;
this.huaweiPushConfig = HuaweiPushConfig.defaultInstance();
}
......@@ -25,6 +27,12 @@ public class JpushConfig extends ConfigObject {
private String appKey;
@FieldDescribe("极光推送应用的Master Secret")
private String masterSecret;
@FieldDescribe("是否开启华为推送")
private Boolean huaweiPushEnable;
@FieldDescribe("华为推送的配置")
private HuaweiPushConfig huaweiPushConfig;
public Boolean getEnable() {
return BooleanUtils.isTrue(this.enable);
......@@ -49,4 +57,20 @@ public class JpushConfig extends ConfigObject {
public void setMasterSecret(String masterSecret) {
this.masterSecret = masterSecret;
}
public Boolean getHuaweiPushEnable() {
return huaweiPushEnable;
}
public void setHuaweiPushEnable(Boolean huaweiPushEnable) {
this.huaweiPushEnable = huaweiPushEnable;
}
public HuaweiPushConfig getHuaweiPushConfig() {
return huaweiPushConfig;
}
public void setHuaweiPushConfig(HuaweiPushConfig huaweiPushConfig) {
this.huaweiPushConfig = huaweiPushConfig;
}
}
......@@ -6,8 +6,7 @@ import com.x.base.core.project.annotation.ModuleType;
@Module(type = ModuleType.ASSEMBLE, category = ModuleCategory.OFFICIAL, name = "极光推送服务模块",
packageName = "com.x.jpush.assemble.control",
containerEntities = { "com.x.jpush.core.entity.SampleEntityClassName" },
storeJars = { "x_organization_core_entity", "x_organization_core_express" },
customJars = { "x_jpush_core_entity" })
containerEntities = { "com.x.jpush.core.entity.SampleEntityClassName","com.x.jpush.core.entity.PushDevice" },
storeJars = { "x_organization_core_entity", "x_organization_core_express", "x_jpush_core_entity" })
public class x_jpush_assemble_control extends Deployable {
}
......@@ -11,6 +11,8 @@ import javax.persistence.criteria.Root;
import com.x.base.core.project.exception.ExceptionWhen;
import com.x.jpush.assemble.control.AbstractFactory;
import com.x.jpush.assemble.control.Business;
import com.x.jpush.core.entity.PushDevice;
import com.x.jpush.core.entity.PushDevice_;
import com.x.jpush.core.entity.SampleEntityClassName;
import com.x.jpush.core.entity.SampleEntityClassName_;
......@@ -63,6 +65,78 @@ public class SampleEntityClassNameFactory extends AbstractFactory {
cq.orderBy( cb.desc( root.get( SampleEntityClassName_.updateTime ) ) );
return em.createQuery(cq).setMaxResults(maxCount).getResultList();
}
/**
* 根据unique 查询设备
* @param unique
* @return
* @throws Exception
*/
public PushDevice findDeviceByUnique(String unique) throws Exception {
EntityManager em = this.entityManagerContainer().get(PushDevice.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<PushDevice> query = cb.createQuery(PushDevice.class);
Root<PushDevice> root = query.from(PushDevice.class);
Predicate p = cb.equal(root.get(PushDevice_.unique), unique);
query.select(root).where(p);
List<PushDevice> list = em.createQuery(query).getResultList();
if (list != null && !list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* 设备是否存在
* @param unique md5(deviceType+deviceId+pushType+person)
* @return
* @throws Exception
*/
public boolean existDeviceUnique(String unique) throws Exception {
EntityManager em = this.entityManagerContainer().get(PushDevice.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<PushDevice> query = cb.createQuery(PushDevice.class);
Root<PushDevice> root = query.from(PushDevice.class);
Predicate p = cb.equal(root.get(PushDevice_.unique), unique);
query.select(root).where(p);
List<PushDevice> list = em.createQuery(query).getResultList();
if (list != null && !list.isEmpty()) {
return true;
}
return false;
}
/**
* 查询用户的极光推送的设备列表
* @param person
* @return
* @throws Exception
*/
public List<PushDevice> listJpushDevice(String person) throws Exception {
return listDevice(person, PushDevice.PUSH_TYPE_JPUSH);
}
/**
* 查询用户的华为推送的设备列表
* @param person
* @return
* @throws Exception
*/
public List<PushDevice> listHuaweiDevice(String person) throws Exception {
return listDevice(person, PushDevice.PUSH_TYPE_HUAWEI);
}
private List<PushDevice> listDevice(String person, String pushType) throws Exception {
EntityManager em = this.entityManagerContainer().get(PushDevice.class);
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<PushDevice> query = cb.createQuery(PushDevice.class);
Root<PushDevice> root = query.from(PushDevice.class);
Predicate p = cb.equal(root.get(PushDevice_.person), person);
p = cb.and(p, cb.equal(root.get(PushDevice_.pushType), pushType));
query.select(root).where(p);
return em.createQuery(query).getResultList();
}
}
\ No newline at end of file
/*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.x.jpush.assemble.control.huawei;
import java.util.Collection;
import java.util.Map;
/**
* A tool for processing collections
*/
public class CollectionUtils {
public CollectionUtils() {
}
public static boolean isEmpty(Collection<?> collection) {
return collection == null || collection.isEmpty();
}
public static boolean isEmpty(Map<?, ?> map) {
return map == null || map.isEmpty();
}
}
/*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.x.jpush.assemble.control.huawei;
/**
* A tool for validating the parameters
*/
public class ValidatorUtils {
public static void checkArgument(boolean expression) {
if (!expression) {
throw new IllegalArgumentException();
}
}
public static void checkArgument(boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalArgumentException(String.valueOf(errorMessage));
}
}
public static void checkState(boolean expression, Object errorMessage) {
if (!expression) {
throw new IllegalStateException(String.valueOf(errorMessage));
}
}
}
/*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.x.jpush.assemble.control.huawei.android;
import com.google.gson.annotations.SerializedName;
import com.x.jpush.assemble.control.huawei.ValidatorUtils;
import com.x.jpush.assemble.control.huawei.model.Notification;
import com.x.jpush.assemble.control.huawei.model.Urgency;
import org.apache.commons.lang3.StringUtils;
public class AndroidConfig {
private static final String TTL_PATTERN = "\\d+|\\d+[sS]|\\d+.\\d{1,9}|\\d+.\\d{1,9}[sS]";
@SerializedName( "collapse_key")
private Integer collapseKey;
@SerializedName( "urgency")
private String urgency;
@SerializedName( "category")
private String category;
@SerializedName( "ttl")
private String ttl;
@SerializedName( "bi_tag")
private String biTag;
@SerializedName( "fast_app_target")
private Integer fastAppTargetType;
@SerializedName( "data")
private String data;
@SerializedName( "notification")
private AndroidNotification notification;
public AndroidConfig(Builder builder) {
this.collapseKey = builder.collapseKey;
this.urgency = builder.urgency;
this.category = builder.category;
if (null != builder.ttl) {
this.ttl = builder.ttl;
} else {
this.ttl = null;
}
this.biTag = builder.biTag;
this.fastAppTargetType = builder.fastAppTargetType;
this.data = builder.data;
this.notification = builder.notification;
}
/**
* check androidConfig's parameters
*
* @param notification whcic is in message
*/
public void check(Notification notification) {
if (this.collapseKey != null) {
ValidatorUtils.checkArgument((this.collapseKey >= -1 && this.collapseKey <= 100), "Collapse Key should be [-1, 100]");
}
if (this.urgency != null) {
ValidatorUtils.checkArgument(StringUtils.equals(this.urgency, Urgency.HIGH.getValue())
|| StringUtils.equals(this.urgency, Urgency.NORMAL.getValue()),
"urgency shouid be [HIGH, NORMAL]");
}
if (StringUtils.isNotEmpty(this.ttl)) {
ValidatorUtils.checkArgument(this.ttl.matches(AndroidConfig.TTL_PATTERN), "The TTL's format is wrong");
}
if (this.fastAppTargetType != null) {
ValidatorUtils.checkArgument(this.fastAppTargetType == 1 || this.fastAppTargetType == 2, "Invalid fast app target type[one of 1 or 2]");
}
if (null != this.notification) {
this.notification.check(notification);
}
}
/**
* getter
*/
public Integer getCollapseKey() {
return collapseKey;
}
public String getTtl() {
return ttl;
}
public String getCategory() {
return category;
}
public String getBiTag() {
return biTag;
}
public Integer getFastAppTargetType() {
return fastAppTargetType;
}
public AndroidNotification getNotification() {
return notification;
}
public String getUrgency() {
return urgency;
}
public String getData() {
return data;
}
/**
* builder
*/
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Integer collapseKey;
private String urgency;
private String category;
private String ttl;
private String biTag;
private Integer fastAppTargetType;
private String data;
private AndroidNotification notification;
private Builder() {
}
public Builder setCollapseKey(Integer collapseKey) {
this.collapseKey = collapseKey;
return this;
}
public Builder setUrgency(String urgency) {
this.urgency = urgency;
return this;
}
public Builder setCategory(String category) {
this.category = category;
return this;
}
/**
* time-to-live
*/
public Builder setTtl(String ttl) {
this.ttl = ttl;
return this;
}
public Builder setBiTag(String biTag) {
this.biTag = biTag;
return this;
}
public Builder setFastAppTargetType(Integer fastAppTargetType) {
this.fastAppTargetType = fastAppTargetType;
return this;
}
public Builder setData(String data) {
this.data = data;
return this;
}
public Builder setNotification(AndroidNotification notification) {
this.notification = notification;
return this;
}
public AndroidConfig build() {
return new AndroidConfig(this);
}
}
}
/*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.x.jpush.assemble.control.huawei.android;
import com.google.gson.annotations.SerializedName;
import com.x.jpush.assemble.control.huawei.ValidatorUtils;
public class BadgeNotification {
@SerializedName("add_num")
private Integer addNum;
@SerializedName("class")
private String badgeClass;
@SerializedName("set_num")
private Integer setNum;
public Integer getAddNum() {
return addNum;
}
public String getBadgeClass() {
return badgeClass;
}
public Integer getSetNum() {
return setNum;
}
public BadgeNotification(Integer addNum, String badgeClass) {
this.addNum = builder().addNum;
this.badgeClass = badgeClass;
}
public BadgeNotification(Builder builder) {
this.addNum = builder.addNum;
this.badgeClass = builder.badgeClass;
this.setNum = builder.setNum;
}
public void check() {
if (this.addNum != null) {
ValidatorUtils.checkArgument(this.addNum.intValue() > 0 && this.addNum.intValue() < 100, "add_num should locate between 0 and 100");
}
if (this.setNum != null) {
ValidatorUtils.checkArgument(this.setNum.intValue() >= 0 && this.setNum.intValue() < 100, "set_num should locate between 0 and 100");
}
}
/**
* builder
*/
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Integer addNum;
private String badgeClass;
private Integer setNum;
public Builder setAddNum(Integer addNum) {
this.addNum = addNum;
return this;
}
public Builder setSetNum(Integer setNum) {
this.setNum = setNum;
return this;
}
public Builder setBadgeClass(String badgeClass) {
this.badgeClass = badgeClass;
return this;
}
public BadgeNotification build() {
return new BadgeNotification(this);
}
}
}
/*
* Copyright (c) Huawei Technologies Co., Ltd. 2019-2029. All rights reserved.
*/
package com.x.jpush.assemble.control.huawei.android;
import com.x.jpush.assemble.control.huawei.ValidatorUtils;
import org.apache.commons.lang3.StringUtils;
/**
* 功能描述
*
* @author l00282963
* @since 2020-01-19
*/
public class Button {
private String name;
private Integer action_type;
private Integer intent_type;
private String intent;
private String data;
public String getName() {
return name;
}
public Integer getAction_type() {
return action_type;
}
public Integer getIntent_type() {
return intent_type;
}
public String getIntent() {
return intent;
}
public String getData() {
return data;
}
public Button(Builder builder) {
this.name = builder.name;
this.action_type = builder.actionType;
this.intent_type = builder.intentType;
this.intent = builder.intent;
this.data = builder.data;
}
public void check() {
if (this.action_type != null && this.action_type == 4) {
ValidatorUtils.checkArgument(StringUtils.isNotEmpty(this.data), "data is needed when actionType is 4");
}
}
/**
* builder
*/
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String name;
private Integer actionType;
private Integer intentType;
private String intent;
private String data;
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setActionType(Integer actionType) {
this.actionType = actionType;
return this;
}
public Builder setIntentType(Integer intentType) {
this.intentType = intentType;
return this;
}
public Builder setIntent(String intent) {
this.intent = intent;
return this;
}
public Builder setData(String data) {
this.data = data;
return this;
}
public Button build() {
return new Button(this);
}
}
}
/*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.x.jpush.assemble.control.huawei.android;
import com.x.jpush.assemble.control.huawei.ValidatorUtils;
import org.apache.commons.lang3.StringUtils;
public class ClickAction {
private static final String PATTERN = "^https.*";
private Integer type;
private String intent;
private String url;
private String rich_resource;
private String action;
private ClickAction(Builder builder) {
this.type = builder.type;
switch (this.type) {
case 1:
this.intent = builder.intent;
this.action = builder.action;
break;
case 2:
this.url = builder.url;
break;
case 4:
this.rich_resource = builder.richResource;
break;
}
}
/**
* check clickAction's parameters
*/
public void check() {
boolean isTrue = this.type == 1 ||
this.type == 2 ||
this.type == 3 ||
this.type == 4;
ValidatorUtils.checkArgument(isTrue, "click type should be one of 1: customize action, 2: open url, 3: open app, 4: open rich media");
switch (this.type) {
case 1:
ValidatorUtils.checkArgument(StringUtils.isNotEmpty(this.intent) || StringUtils.isNotEmpty(this.action), "intent or action is required when click type=1");
break;
case 2:
ValidatorUtils.checkArgument(StringUtils.isNotEmpty(this.url), "url is required when click type=2");
ValidatorUtils.checkArgument(this.url.matches(PATTERN), "url must start with https");
break;
case 4:
ValidatorUtils.checkArgument(StringUtils.isNotEmpty(this.rich_resource), "richResource is required when click type=4");
ValidatorUtils.checkArgument(this.rich_resource.matches(PATTERN), "richResource must start with https");
break;
}
}
/**
* getter
*/
public int getType() {
return type;
}
public String getIntent() {
return intent;
}
public String getUrl() {
return url;
}
public String getRich_resource() {
return rich_resource;
}
public String getAction() {
return action;
}
/**
* builder
*/
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Integer type;
private String intent;
private String url;
private String richResource;
private String action;
private Builder() {
}
public Builder setType(Integer type) {
this.type = type;
return this;
}
public Builder setIntent(String intent) {
this.intent = intent;
return this;
}
public Builder setUrl(String url) {
this.url = url;
return this;
}
public Builder setRichResource(String richResource) {
this.richResource = richResource;
return this;
}
public Builder setAction(String action) {
this.action = action;
return this;
}
public ClickAction build() {
return new ClickAction(this);
}
}
}
/*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.x.jpush.assemble.control.huawei.android;
import com.x.jpush.assemble.control.huawei.ValidatorUtils;
public class Color {
private final float zero = -0.000001f;
private final float one = 1.000001f;
private Float alpha = new Float(1.0);
private Float red = new Float(0.0);
private Float green = new Float(0.0);
private Float blue = new Float(0.0);
public Color(Builder builder) {
this.alpha = builder.alpha;
this.red = builder.red;
this.green = builder.green;
this.blue = builder.blue;
}
public double getAlpha() {
return alpha;
}
public Float getRed() {
return red;
}
public Float getGreen() {
return green;
}
public Float getBlue() {
return blue;
}
public void check() {
ValidatorUtils.checkArgument(this.alpha > zero && this.alpha < one, "Alpha shoube locate between [0,1]");
ValidatorUtils.checkArgument(this.red > zero && this.red < one, "Red shoube locate between [0,1]");
ValidatorUtils.checkArgument(this.green > zero && this.green < one, "Green shoube locate between [0,1]");
ValidatorUtils.checkArgument(this.blue > zero && this.blue < one, "Blue shoube locate between [0,1]");
}
/**
* builder
*/
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Float alpha = new Float(1.0);
private Float red = new Float(0.0);
private Float green = new Float(0.0);
private Float blue = new Float(0.0);
public Builder setAlpha(Float alpha) {
this.alpha = alpha;
return this;
}
public Builder setRed(Float red) {
this.red = red;
return this;
}
public Builder setGreen(Float green) {
this.green = green;
return this;
}
public Builder setBlue(Float blue) {
this.blue = blue;
return this;
}
public Color build() {
return new Color(this);
}
}
}
/*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.x.jpush.assemble.control.huawei.android;
import com.x.jpush.assemble.control.huawei.ValidatorUtils;
public class LightSettings {
private static final String LIGTH_DURATION_PATTERN = "\\d+|\\d+[sS]|\\d+.\\d{1,9}|\\d+.\\d{1,9}[sS]";
private Color color;
private String light_on_duration;
private String light_off_duration;
public LightSettings(Builder builder) {
this.color = builder.color;
this.light_on_duration = builder.lightOnDuration;
this.light_off_duration = builder.lightOffDuration;
}
public Color getColor() {
return color;
}
public String getLight_on_duration() {
return light_on_duration;
}
public String getLight_off_duration() {
return light_off_duration;
}
/**
* 参数校验
*/
public void check() {
ValidatorUtils.checkArgument(this.color != null, "color must be selected when light_settings is set");
if (this.color != null) {
this.color.check();
}
ValidatorUtils.checkArgument(this.light_on_duration != null, "light_on_duration must be selected when light_settings is set");
ValidatorUtils.checkArgument(this.light_off_duration != null, "light_off_duration must be selected when light_settings is set");
ValidatorUtils.checkArgument(this.light_on_duration.matches(LIGTH_DURATION_PATTERN), "light_on_duration format is wrong");
ValidatorUtils.checkArgument(this.light_off_duration.matches(LIGTH_DURATION_PATTERN), "light_off_duration format is wrong");
}
/**
* builder
*/
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Color color;
private String lightOnDuration;
private String lightOffDuration;
public Builder setColor(Color color) {
this.color = color;
return this;
}
public Builder setLightOnDuration(String lightOnDuration) {
this.lightOnDuration = lightOnDuration;
return this;
}
public Builder setLightOffDuration(String lightOffDuration) {
this.lightOffDuration = lightOffDuration;
return this;
}
public LightSettings build() {
return new LightSettings(this);
}
}
}
/*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.x.jpush.assemble.control.huawei.apns;
import com.google.gson.annotations.SerializedName;
import com.x.jpush.assemble.control.huawei.CollectionUtils;
import com.x.jpush.assemble.control.huawei.ValidatorUtils;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
public class Alert {
@SerializedName( "title")
private String title;
@SerializedName( "body")
private String body;
@SerializedName( "title-loc-key")
private String titleLocKey;
@SerializedName( "title-loc-args")
private List<String> titleLocArgs = new ArrayList<String>();
@SerializedName( "action-loc-key")
private String actionLocKey;
@SerializedName( "loc-key")
private String locKey;
@SerializedName( "loc-args")
private List<String> locArgs = new ArrayList<String>();
@SerializedName( "launch-image")
private String launchImage;
public String getTitle() {
return title;
}
public String getBody() {
return body;
}
public String getTitleLocKey() {
return titleLocKey;
}
public List<String> getTitleLocArgs() {
return titleLocArgs;
}
public String getActionLocKey() {
return actionLocKey;
}
public String getLocKey() {
return locKey;
}
public List<String> getLocArgs() {
return locArgs;
}
public String getLaunchImage() {
return launchImage;
}
private Alert(Builder builder) {
this.title = builder.title;
this.body = builder.body;
this.titleLocKey = builder.titleLocKey;
if (!CollectionUtils.isEmpty(builder.titleLocArgs)) {
this.titleLocArgs.addAll(builder.titleLocArgs);
} else {
this.titleLocArgs = null;
}
this.actionLocKey = builder.actionLocKey;
this.locKey = builder.locKey;
if (!CollectionUtils.isEmpty(builder.locArgs)) {
this.locArgs.addAll(builder.locArgs);
} else {
this.locArgs = null;
}
this.launchImage = builder.launchImage;
}
public void check() {
if (!CollectionUtils.isEmpty(this.locArgs)) {
ValidatorUtils.checkArgument(StringUtils.isNotEmpty(this.locKey), "locKey is required when specifying locArgs");
}
if (!CollectionUtils.isEmpty(this.titleLocArgs)) {
ValidatorUtils.checkArgument(StringUtils.isNotEmpty(this.titleLocKey), "titleLocKey is required when specifying titleLocArgs");
}
}
/**
* builder
*
* @return
*/
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String title;
private String body;
private String titleLocKey;
private List<String> titleLocArgs = new ArrayList<String>();
private String actionLocKey;
private String locKey;
private List<String> locArgs = new ArrayList<String>();
private String launchImage;
public Builder setTitle(String title) {
this.title = title;
return this;
}
public Builder setBody(String body) {
this.body = body;
return this;
}
public Builder setTitleLocKey(String titleLocKey) {
this.titleLocKey = titleLocKey;
return this;
}
public Builder setAddAllTitleLocArgs(List<String> titleLocArgs) {
this.titleLocArgs.addAll(titleLocArgs);
return this;
}
public Builder setAddTitleLocArg(String titleLocArg) {
this.titleLocArgs.add(titleLocArg);
return this;
}
public Builder setActionLocKey(String actionLocKey) {
this.actionLocKey = actionLocKey;
return this;
}
public Builder setLocKey(String locKey) {
this.locKey = locKey;
return this;
}
public Builder AddAllLocArgs(List<String> locArgs) {
this.locArgs.addAll(locArgs);
return this;
}
public Builder AddLocArg(String locArg) {
this.locArgs.add(locArg);
return this;
}
public Builder setLaunchImage(String launchImage) {
this.launchImage = launchImage;
return this;
}
public Alert build() {
return new Alert(this);
}
}
}
/*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.x.jpush.assemble.control.huawei.apns;
import com.google.gson.annotations.SerializedName;
import com.x.jpush.assemble.control.huawei.CollectionUtils;
import java.util.HashMap;
import java.util.Map;
public class ApnsConfig {
@SerializedName( "hms_options")
private ApnsHmsOptions hmsOptions;
@SerializedName( "headers")
private ApnsHeaders apnsHeaders;
@SerializedName( "payload")
private Map<String, Object> payload = new HashMap<>();
public void check() {
if (this.hmsOptions != null) {
this.hmsOptions.check();
}
if (this.apnsHeaders != null) {
this.apnsHeaders.check();
}
if (this.payload != null) {
if (this.payload.get("aps") != null) {
Aps aps = (Aps) this.payload.get("aps");
aps.check();
}
}
}
public ApnsConfig(Builder builder) {
this.hmsOptions = builder.hmsOptions;
this.apnsHeaders = builder.apnsHeaders;
if (!CollectionUtils.isEmpty(builder.payload) || builder.aps != null) {
if (!CollectionUtils.isEmpty(builder.payload)) {
this.payload.putAll(builder.payload);
}
if (builder.aps != null) {
this.payload.put("aps", builder.aps);
}
} else {
this.payload = null;
}
}
public ApnsHmsOptions getHmsOptions() {
return hmsOptions;
}
public Map<String, Object> getPayload() {
return payload;
}
public ApnsHeaders getApnsHeaders() {
return apnsHeaders;
}
/**
* builder
*/
public static Builder builder() {
return new Builder();
}
public static class Builder {
private ApnsHmsOptions hmsOptions;
private Map<String, Object> payload = new HashMap<>();
private ApnsHeaders apnsHeaders;
private Aps aps;
public Builder setHmsOptions(ApnsHmsOptions hmsOptions) {
this.hmsOptions = hmsOptions;
return this;
}
public Builder addPayload(String key, Object value) {
this.payload.put(key, value);
return this;
}
public Builder addAllPayload(Map<String, Object> map) {
this.payload.putAll(map);
return this;
}
public Builder setApnsHeaders(ApnsHeaders apnsHeaders) {
this.apnsHeaders = apnsHeaders;
return this;
}
public Builder addPayloadAps(Aps aps) {
this.aps = aps;
return this;
}
public Builder addPayload(Aps aps) {
this.aps = aps;
return this;
}
public ApnsConfig build() {
return new ApnsConfig(this);
}
}
}
/*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.x.jpush.assemble.control.huawei.apns;
import com.google.gson.annotations.SerializedName;
import com.x.jpush.assemble.control.huawei.ValidatorUtils;
public class ApnsHeaders {
private static final String AUTHORIZATION_PATTERN = "^bearer*";
private static final String APN_ID_PATTERN = "[0-9a-z]{8}(-[0-9a-z]{4}){3}-[0-9a-z]{12}";
private static final int SEND_IMMEDIATELY = 10;
private static final int SEND_BY_GROUP = 5;
@SerializedName( "authorization")
private String authorization;
@SerializedName( "apns-id")
private String apnsId;
@SerializedName( "apns-expiration")
private Long apnsExpiration;
@SerializedName( "apns-priority")
private String apnsPriority;
@SerializedName( "apns-topic")
private String apnsTopic;
@SerializedName( "apns-collapse-id")
private String apnsCollapseId;
public String getAuthorization() {
return authorization;
}
public String getApnsId() {
return apnsId;
}
public Long getApnsExpiration() {
return apnsExpiration;
}
public String getApnsPriority() {
return apnsPriority;
}
public String getApnsTopic() {
return apnsTopic;
}
public String getApnsCollapseId() {
return apnsCollapseId;
}
public void check() {
if (this.authorization != null) {
ValidatorUtils.checkArgument(this.authorization.matches(AUTHORIZATION_PATTERN), "authorization must start with bearer");
}
if (this.apnsId != null) {
ValidatorUtils.checkArgument(this.apnsId.matches(APN_ID_PATTERN), "apns-id format error");
}
if (this.apnsPriority != null) {
ValidatorUtils.checkArgument(Integer.parseInt(this.apnsPriority) == SEND_BY_GROUP ||
Integer.parseInt(this.apnsPriority) == SEND_IMMEDIATELY, "apns-priority should be SEND_BY_GROUP:5 or SEND_IMMEDIATELY:10");
}
if (this.apnsCollapseId != null) {
ValidatorUtils.checkArgument(this.apnsCollapseId.getBytes().length < 64, "Number of apnsCollapseId bytes should be less than 64");
}
}
private ApnsHeaders(Builder builder) {
this.authorization = builder.authorization;
this.apnsId = builder.apnsId;
this.apnsExpiration = builder.apnsExpiration;
this.apnsPriority = builder.apnsPriority;
this.apnsTopic = builder.apnsTopic;
this.apnsCollapseId = builder.apnsCollapseId;
}
/**
* builder
*/
public static Builder builder() {
return new Builder();
}
public static class Builder {
private String authorization;
private String apnsId;
private Long apnsExpiration;
private String apnsPriority;
private String apnsTopic;
private String apnsCollapseId;
public Builder setAuthorization(String authorization) {
this.authorization = authorization;
return this;
}
public Builder setApnsId(String apnsId) {
this.apnsId = apnsId;
return this;
}
public Builder setApnsExpiration(Long apnsExpiration) {
this.apnsExpiration = apnsExpiration;
return this;
}
public Builder setApnsPriority(String apnsPriority) {
this.apnsPriority = apnsPriority;
return this;
}
public Builder setApnsTopic(String apnsTopic) {
this.apnsTopic = apnsTopic;
return this;
}
public Builder setApnsCollapseId(String apnsCollapseId) {
this.apnsCollapseId = apnsCollapseId;
return this;
}
public ApnsHeaders build() {
return new ApnsHeaders(this);
}
}
}
/*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.x.jpush.assemble.control.huawei.apns;
import com.google.gson.annotations.SerializedName;
import com.x.jpush.assemble.control.huawei.ValidatorUtils;
public class ApnsHmsOptions {
private static final int TEST_USER = 1;
private static final int FORMAL_USER = 1;
private static final int VOIP_USER = 1;
@SerializedName( "target_user_type")
private Integer targetUserType;
public Integer getTargetUserType() {
return targetUserType;
}
private ApnsHmsOptions(Builder builder){
this.targetUserType = builder.targetUserType;
}
public void check(){
if (targetUserType != null) {
ValidatorUtils.checkArgument(this.targetUserType.intValue() == TEST_USER
|| this.targetUserType.intValue() == FORMAL_USER
|| this.targetUserType.intValue() == VOIP_USER,
"targetUserType should be [TEST_USER: 1, FORMAL_USER: 2, VOIP_USER: 3]");
}
}
/**
* builder
*/
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Integer targetUserType;
public Builder setTargetUserType(Integer targetUserType) {
this.targetUserType = targetUserType;
return this;
}
public ApnsHmsOptions build(){
return new ApnsHmsOptions(this);
}
}
}
/*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.x.jpush.assemble.control.huawei.apns;
import com.google.gson.annotations.SerializedName;
import com.x.jpush.assemble.control.huawei.ValidatorUtils;
public class Aps {
@SerializedName( "alert")
private Object alert;
@SerializedName( "badge")
private Integer badge;
@SerializedName( "sound")
private String sound;
@SerializedName( "content-available")
private Integer contentAvailable;
@SerializedName( "category")
private String category;
@SerializedName( "thread-id")
private String threadId;
public Object getAlert() {
return alert;
}
public Integer getBadge() {
return badge;
}
public String getSound() {
return sound;
}
public Integer getContentAvailable() {
return contentAvailable;
}
public String getCategory() {
return category;
}
public String getThreadId() {
return threadId;
}
public void check() {
if (this.alert != null) {
if(this.alert instanceof Alert){
((Alert) this.alert).check();
}else{
ValidatorUtils.checkArgument((this.alert instanceof String), "Alter should be Dictionary or String");
}
}
}
private Aps(Builder builder) {
this.alert = builder.alert;
this.badge = builder.badge;
this.sound = builder.sound;
this.contentAvailable = builder.contentAvailable;
this.category = builder.category;
this.threadId = builder.threadId;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
private Object alert;
private Integer badge;
private String sound;
private Integer contentAvailable;
private String category;
private String threadId;
public Builder setAlert(Object alert) {
this.alert = alert;
return this;
}
public Builder setBadge(Integer badge) {
this.badge = badge;
return this;
}
public Builder setSound(String sound) {
this.sound = sound;
return this;
}
public Builder setContentAvailable(Integer contentAvailable) {
this.contentAvailable = contentAvailable;
return this;
}
public Builder setCategory(String category) {
this.category = category;
return this;
}
public Builder setThreadId(String threadId) {
this.threadId = threadId;
return this;
}
public Aps build() {
return new Aps(this);
}
}
}
/*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.x.jpush.assemble.control.huawei.model;
public enum Importance {
/**
* LOW
*/
LOW("LOW"),
/**
* NORMAL
*/
NORMAL("NORMAL"),
/**
* HIGH
*/
HIGH("HIGH");
private String value;
private Importance(String value) {
this.value = value;
}
/**
* Gets value *
*
* @return the value
*/
public String getValue() {
return value;
}
}
/*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.x.jpush.assemble.control.huawei.model;
import com.google.common.base.Strings;
import com.google.common.primitives.Booleans;
import com.google.gson.annotations.SerializedName;
import com.x.jpush.assemble.control.huawei.CollectionUtils;
import com.x.jpush.assemble.control.huawei.ValidatorUtils;
import com.x.jpush.assemble.control.huawei.android.AndroidConfig;
import com.x.jpush.assemble.control.huawei.apns.ApnsConfig;
import org.apache.commons.lang3.StringUtils;
import java.util.ArrayList;
import java.util.List;
public class Message {
@SerializedName( "data")
private String data;
@SerializedName( "notification")
private Notification notification;
@SerializedName( "android")
private AndroidConfig androidConfig;
@SerializedName( "apns")
private ApnsConfig apns;
@SerializedName( "token")
private List<String> token = new ArrayList<>();
@SerializedName( "topic")
private String topic;
@SerializedName( "condition")
private String condition;
private Message(Builder builder) {
this.data = builder.data;
this.notification = builder.notification;
this.androidConfig = builder.androidConfig;
this.apns = builder.apns;
if (!CollectionUtils.isEmpty(builder.token)) {
this.token.addAll(builder.token);
} else {
this.token = null;
}
this.topic = builder.topic;
this.condition = builder.condition;
/** check after message is created */
check();
}
/**
* check message's parameters
*/
public void check() {
int count = Booleans.countTrue(
!CollectionUtils.isEmpty(this.token),
!Strings.isNullOrEmpty(this.topic),
!Strings.isNullOrEmpty(this.condition)
);
ValidatorUtils.checkArgument(count == 1, "Exactly one of token, topic or condition must be specified");
boolean isEmptyData = StringUtils.isEmpty(data);
if (this.notification != null) {
this.notification.check();
}
if (this.apns != null) {
this.apns.check();
}
if (null != this.androidConfig) {
this.androidConfig.check(this.notification);
}
}
/**
* getter
*/
public String getData() {
return data;
}
public Notification getNotification() {
return notification;
}
public AndroidConfig getAndroidConfig() {
return androidConfig;
}
public ApnsConfig getApns() {
return apns;
}
public List<String> getToken() {
return token;
}
public String getTopic() {
return topic;
}
public String getCondition() {
return condition;
}
/**
* builder
*
* @return
*/
public static Builder builder() {
return new Builder();
}
/**
* push message builder
*/
public static class Builder {
private String data;
private Notification notification;
private AndroidConfig androidConfig;
private ApnsConfig apns;
private List<String> token = new ArrayList<>();
private String topic;
private String condition;
private Builder() {
}
public Builder setData(String data) {
this.data = data;
return this;
}
public Builder setNotification(Notification notification) {
this.notification = notification;
return this;
}
public Builder setAndroidConfig(AndroidConfig androidConfig) {
this.androidConfig = androidConfig;
return this;
}
public Builder setApns(ApnsConfig apns) {
this.apns = apns;
return this;
}
public Builder addToken(String token) {
this.token.add(token);
return this;
}
public Builder addAllToken(List<String> tokens) {
this.token.addAll(tokens);
return this;
}
public Builder setTopic(String topic) {
this.topic = topic;
return this;
}
public Builder setCondition(String condition) {
this.condition = condition;
return this;
}
public Message build() {
return new Message(this);
}
}
}
/*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.x.jpush.assemble.control.huawei.model;
import com.google.gson.annotations.SerializedName;
import com.x.jpush.assemble.control.huawei.ValidatorUtils;
import java.util.Locale;
public class Notification {
@SerializedName("title")
private String title;
@SerializedName("body")
private String body;
@SerializedName("image")
private String image;
public Notification() {
}
public Notification(String title, String body) {
this.title = title;
this.body = body;
}
public Notification(String title, String body, String image) {
this.title = title;
this.body = body;
this.image = image;
}
public Notification(Builder builder) {
this.title = builder.title;
this.body = builder.body;
this.image = builder.image;
}
public void check() {
if (this.image != null) {
ValidatorUtils.checkArgument(this.image.toLowerCase(Locale.getDefault()).trim().startsWith("https"), "image's url should start with HTTPS");
}
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
/**
* builder
*
* @return
*/
public static Builder builder() {
return new Builder();
}
/**
* push message builder
*/
public static class Builder {
private String title;
private String body;
private String image;
public Builder setTitle(String title) {
this.title = title;
return this;
}
public Builder setBody(String body) {
this.body = body;
return this;
}
public Builder setImage(String image) {
this.image = image;
return this;
}
public Notification build() {
return new Notification(this);
}
}
}
/*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.x.jpush.assemble.control.huawei.model;
public enum TopicOperation {
SUBSCRIBE("subscribe"),
UNSUBSCRIBE("unsubscribe"),
LIST("list");
private String value;
private TopicOperation(String value) {
this.value = value;
}
/**
* Gets value *
*
* @return the value
*/
public String getValue() {
return value;
}
}
/*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.x.jpush.assemble.control.huawei.model;
public enum Urgency {
HIGH("HIGH"),
NORMAL("NORMAL");
private String value;
private Urgency(String value) {
this.value = value;
}
/**
* Gets value *
*
* @return the value
*/
public String getValue() {
return value;
}
}
\ No newline at end of file
/*
* Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.x.jpush.assemble.control.huawei.model;
public enum Visibility {
VISIBILITY_UNSPECIFIED("VISIBILITY_UNSPECIFIED"),
PRIVATE("PRIVATE"),
PUBLIC("PUBLIC"),
SECRET("SECRET");
private String value;
private Visibility(String value) {
this.value = value;
}
/**
* Gets value *
*
* @return the value
*/
public String getValue() {
return value;
}
}
......@@ -3,20 +3,20 @@ package com.x.jpush.assemble.control.jaxrs.device;
import com.google.gson.JsonElement;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.entity.annotation.CheckPersistType;
import com.x.base.core.project.annotation.FieldDescribe;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WrapBoolean;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ListTools;
import com.x.jpush.assemble.control.Business;
import com.x.jpush.assemble.control.jaxrs.sample.BaseAction;
import com.x.jpush.assemble.control.jaxrs.sample.ExceptionSampleEntityClassFind;
import com.x.jpush.core.entity.PushDevice;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
public class ActionBind extends BaseAction {
......@@ -27,44 +27,62 @@ public class ActionBind extends BaseAction {
ActionResult<Wo> result = new ActionResult<>();
Wo wraps = new Wo();
if (jsonElement == null) {
Exception exception = new ExceptionDeviceParameterEmpty();
result.error(exception);
return result;
throw new ExceptionDeviceParameterEmpty();
}
Wi wi = convertToWrapIn(jsonElement, Wi.class);
if (wi.getDeviceName() == null || wi.getDeviceType() == null || wi.getDeviceName().equals("") || wi.getDeviceType().equals("")) {
Exception exception = new ExceptionDeviceParameterEmpty();
result.error(exception);
return result;
if (StringUtils.isEmpty(wi.getDeviceName()) || StringUtils.isEmpty(wi.getDeviceType()) ) {
throw new ExceptionDeviceParameterEmpty();
}
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
Business business = new Business(emc);
List<String> deviceList = business.organization().personAttribute()
.listAttributeWithPersonWithName(effectivePerson.getDistinguishedName(), ActionListAll.DEVICE_PERSON_ATTR_KEY);
String device = wi.getDeviceName()+"_"+wi.getDeviceType().toLowerCase();
if(ListTools.isNotEmpty( deviceList ) ){
if (deviceList.contains(device)) {
wraps.setValue(false);
result.setMessage("当前设备已存在!");
}else {
deviceList.add(device);
wraps.setValue(business.organization().personAttribute()
.setWithPersonWithName(effectivePerson.getDistinguishedName(), ActionListAll.DEVICE_PERSON_ATTR_KEY, deviceList));
}
}else {
deviceList = new ArrayList<>();
deviceList.add(device);
wraps.setValue(business.organization().personAttribute()
.setWithPersonWithName(effectivePerson.getDistinguishedName(), ActionListAll.DEVICE_PERSON_ATTR_KEY, deviceList));
String pushType = wi.getPushType();
if (StringUtils.isEmpty(pushType)) {
pushType = PushDevice.PUSH_TYPE_JPUSH; //默认极光推送
}
String person = effectivePerson.getDistinguishedName();
String unique = deviceUnique(wi.getDeviceType(), wi.getDeviceName(), pushType, person);
if (business.sampleEntityClassNameFactory().existDeviceUnique(unique)) {
wraps.setValue(true);
result.setMessage("当前设备已存在!");
} else {
PushDevice pushDevice = new PushDevice();
pushDevice.setDeviceId(wi.getDeviceName());
pushDevice.setDeviceType(wi.getDeviceType());
pushDevice.setPerson(person);
pushDevice.setPushType(pushType);
pushDevice.setUnique(unique);
emc.beginTransaction(PushDevice.class);
emc.persist(pushDevice, CheckPersistType.all);
emc.commit();
wraps.setValue(true);
}
// 以前存放在个人属性中, 现在切换到数据库
// List<String> deviceList = business.organization().personAttribute()
// .listAttributeWithPersonWithName(effectivePerson.getDistinguishedName(), ActionListAll.DEVICE_PERSON_ATTR_KEY);
// String device = wi.getDeviceName()+"_"+wi.getDeviceType().toLowerCase();
// if(ListTools.isNotEmpty( deviceList ) ){
// if (deviceList.contains(device)) {
// wraps.setValue(false);
// result.setMessage("当前设备已存在!");
// }else {
// deviceList.add(device);
// wraps.setValue(business.organization().personAttribute()
// .setWithPersonWithName(effectivePerson.getDistinguishedName(), ActionListAll.DEVICE_PERSON_ATTR_KEY, deviceList));
// }
// }else {
// deviceList = new ArrayList<>();
// deviceList.add(device);
// wraps.setValue(business.organization().personAttribute()
// .setWithPersonWithName(effectivePerson.getDistinguishedName(), ActionListAll.DEVICE_PERSON_ATTR_KEY, deviceList));
// }
result.setData(wraps);
} catch (Exception e) {
Exception exception = new ExceptionSampleEntityClassFind( e, "系统在绑定设备时发生异常!" );
result.error( exception );
logger.error(e);
throw new ExceptionSampleEntityClassFind( e, "系统在绑定设备时发生异常!" );
}
logger.info("action 'ActionBind' execute completed!");
return result;
}
......@@ -76,6 +94,16 @@ public class ActionBind extends BaseAction {
private String deviceName;
@FieldDescribe("设备类型deviceType:ios|android")
private String deviceType;
@FieldDescribe("推送通道类型:jpush|huawei")
private String pushType;
public String getPushType() {
return pushType;
}
public void setPushType(String pushType) {
this.pushType = pushType;
}
public String getDeviceName() {
return deviceName;
......
......@@ -7,43 +7,46 @@ import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WrapBoolean;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ListTools;
import com.x.jpush.assemble.control.Business;
import com.x.jpush.assemble.control.jaxrs.sample.BaseAction;
import com.x.jpush.assemble.control.jaxrs.sample.ExceptionSampleEntityClassFind;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
public class ActionCheck extends BaseAction {
private Logger logger = LoggerFactory.getLogger( ActionCheck.class );
protected ActionResult<Wo> execute(HttpServletRequest request, EffectivePerson effectivePerson, String deviceName, String deviceType) throws Exception {
protected ActionResult<Wo> execute(HttpServletRequest request, EffectivePerson effectivePerson, String deviceName, String deviceType, String pushType) throws Exception {
logger.info("execute action 'ActionCheck'......");
ActionResult<Wo> result = new ActionResult<>();
Wo wraps = new Wo();
if (deviceName == null || deviceType == null || deviceName.equals("") || deviceType.equals("")) {
Exception exception = new ExceptionDeviceParameterEmpty();
result.error(exception);
return result;
if (StringUtils.isEmpty(deviceName) || StringUtils.isEmpty(deviceType) || StringUtils.isEmpty(pushType)) {
throw new ExceptionDeviceParameterEmpty();
}
deviceType = deviceType.toLowerCase();
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
Business business = new Business(emc);
List<String> deviceList = business.organization().personAttribute()
.listAttributeWithPersonWithName(effectivePerson.getDistinguishedName(), ActionListAll.DEVICE_PERSON_ATTR_KEY);
if( ListTools.isNotEmpty( deviceList ) ){
String device = deviceName+"_"+deviceType;
wraps.setValue(deviceList.contains(device));
String unique = deviceUnique(deviceType, deviceName, pushType, effectivePerson.getDistinguishedName());
if (business.sampleEntityClassNameFactory().existDeviceUnique(unique)) {
wraps.setValue(true);
}else {
wraps.setValue(false);
wraps.setValue(false);
}
// List<String> deviceList = business.organization().personAttribute()
// .listAttributeWithPersonWithName(effectivePerson.getDistinguishedName(), ActionListAll.DEVICE_PERSON_ATTR_KEY);
// if( ListTools.isNotEmpty( deviceList ) ){
// String device = deviceName+"_"+deviceType;
// wraps.setValue(deviceList.contains(device));
// }else {
// wraps.setValue(false);
// }
result.setData(wraps);
} catch (Exception e) {
Exception exception = new ExceptionSampleEntityClassFind( e, "系统在检查绑定设备是否存在时发生异常!" );
result.error( exception );
logger.error(e);
throw new ExceptionSampleEntityClassFind( e, "系统在检查绑定设备是否存在时发生异常!" );
}
logger.info("action 'ActionCheck' execute completed!");
......
package com.x.jpush.assemble.control.jaxrs.device;
import com.x.base.core.project.annotation.FieldDescribe;
import com.x.base.core.project.config.Config;
import com.x.base.core.project.config.HuaweiPushConfig;
import com.x.base.core.project.gson.GsonPropertyObject;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.jpush.assemble.control.jaxrs.sample.BaseAction;
import com.x.jpush.core.entity.PushDevice;
import javax.servlet.http.HttpServletRequest;
/**
* Created by fancyLou on 9/14/21.
* Copyright © 2021 O2. All rights reserved.
*/
public class ActionConfigPushType extends BaseAction {
private Logger logger = LoggerFactory.getLogger(ActionBind.class);
protected ActionResult<Wo> execute(HttpServletRequest request, EffectivePerson effectivePerson) throws Exception {
HuaweiPushConfig config = Config.pushConfig().getHuaweiPushConfig();
ActionResult<Wo> result = new ActionResult<>();
if (config !=null && Config.pushConfig().getHuaweiPushEnable()) {
Wo wo = new Wo();
wo.setPushType(PushDevice.PUSH_TYPE_HUAWEI);
result.setData(wo);
} else {
Wo wo = new Wo();
wo.setPushType(PushDevice.PUSH_TYPE_JPUSH);
result.setData(wo);
}
return result;
}
/**
*
* 向外输出的结果对象包装类
*
*/
public static class Wo extends GsonPropertyObject {
@FieldDescribe("推送通道类型:jpush|huawei")
private String pushType;
public String getPushType() {
return pushType;
}
public void setPushType(String pushType) {
this.pushType = pushType;
}
}
}
......@@ -11,6 +11,8 @@ import com.x.base.core.project.tools.ListTools;
import com.x.jpush.assemble.control.Business;
import com.x.jpush.assemble.control.jaxrs.sample.BaseAction;
import com.x.jpush.assemble.control.jaxrs.sample.ExceptionSampleEntityClassFind;
import com.x.jpush.core.entity.PushDevice;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
......@@ -21,23 +23,42 @@ public class ActionListAll extends BaseAction {
public static final String DEVICE_PERSON_ATTR_KEY = "appBindDeviceList";
protected ActionResult<List<Wo>> execute(HttpServletRequest request, EffectivePerson effectivePerson) throws Exception {
protected ActionResult<List<Wo>> execute(HttpServletRequest request, EffectivePerson effectivePerson, String pushType) throws Exception {
logger.info("execute action 'ActionListAll'......");
ActionResult<List<Wo>> result = new ActionResult<>();
if (StringUtils.isEmpty(pushType)) {
throw new ExceptionDevicePushTypeError();
}
if (!pushType.equals(PushDevice.PUSH_TYPE_JPUSH) && !pushType.equals(PushDevice.PUSH_TYPE_HUAWEI)) {
throw new ExceptionDevicePushTypeError();
}
List<Wo> wraps = null;
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
Business business = new Business(emc);
List<String> deviceList = business.organization().personAttribute()
.listAttributeWithPersonWithName(effectivePerson.getDistinguishedName(), DEVICE_PERSON_ATTR_KEY);
if( ListTools.isNotEmpty( deviceList ) ){
wraps = Wo.copyFromAttributes( deviceList );
result.setCount(Long.parseLong( wraps.size() + "") );
result.setData( wraps );
if (pushType.equals(PushDevice.PUSH_TYPE_JPUSH)) {
List<PushDevice> list = business.sampleEntityClassNameFactory().listJpushDevice(effectivePerson.getDistinguishedName());
wraps = Wo.copyFromPushDeviceList(list);
result.setData(wraps);
result.setCount(Long.parseLong(wraps.size()+""));
} else {
List<PushDevice> list = business.sampleEntityClassNameFactory().listHuaweiDevice(effectivePerson.getDistinguishedName());
wraps = Wo.copyFromPushDeviceList(list);
result.setData(wraps);
result.setCount(Long.parseLong(wraps.size()+""));
}
//
//
// List<String> deviceList = business.organization().personAttribute()
// .listAttributeWithPersonWithName(effectivePerson.getDistinguishedName(), DEVICE_PERSON_ATTR_KEY);
// if( ListTools.isNotEmpty( deviceList ) ){
// wraps = Wo.copyFromAttributes( deviceList );
// result.setCount(Long.parseLong( wraps.size() + "") );
// result.setData( wraps );
// }
} catch (Exception e) {
Exception exception = new ExceptionSampleEntityClassFind( e, "系统在查询绑定设备时发生异常!" );
result.error( exception );
logger.error(e);
throw new ExceptionSampleEntityClassFind( e, "系统在查询绑定设备时发生异常!" );
}
logger.info("action 'ActionListAll' execute completed!");
......@@ -58,6 +79,20 @@ public class ActionListAll extends BaseAction {
private String deviceType;
public static List<Wo> copyFromPushDeviceList(List<PushDevice> list) {
List<Wo> ret = new ArrayList<>();
if (list!=null && !list.isEmpty()) {
for (int i = 0; i < list.size(); i++) {
PushDevice pushDevice = list.get(i);
Wo wo = new Wo();
wo.setDeviceName(pushDevice.getDeviceId());
wo.setDeviceType(pushDevice.getDeviceType());
ret.add(wo);
}
}
return ret;
}
public static List<Wo> copyFromAttributes(List<String> attributes) {
List<Wo> ret = new ArrayList<>();
if (ListTools.isNotEmpty(attributes)) {
......
......@@ -26,9 +26,7 @@ public class ActionRemoveBind extends BaseAction {
ActionResult<Wo> result = new ActionResult<>();
Wo wraps = new Wo();
if (deviceName == null || deviceType == null || deviceName.equals("") || deviceType.equals("")) {
Exception exception = new ExceptionDeviceParameterEmpty();
result.error(exception);
return result;
throw new ExceptionDeviceParameterEmpty();
}
deviceType = deviceType.toLowerCase();
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
......@@ -50,14 +48,14 @@ public class ActionRemoveBind extends BaseAction {
result.setMessage("当前设备不存在,无需解绑!");
}
result.setData(wraps);
logger.info("action 'ActionRemoveBind' execute completed!");
return result;
} catch (Exception e) {
Exception exception = new ExceptionSampleEntityClassFind( e, "系统在设备解除绑定时发生异常!" );
result.error( exception );
logger.error(e);
throw new ExceptionSampleEntityClassFind( e, "系统在设备解除绑定时发生异常!" );
}
logger.info("action 'ActionRemoveBind' execute completed!");
return result;
}
......
package com.x.jpush.assemble.control.jaxrs.device;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.WrapBoolean;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ListTools;
import com.x.jpush.assemble.control.Business;
import com.x.jpush.assemble.control.jaxrs.sample.BaseAction;
import com.x.jpush.assemble.control.jaxrs.sample.ExceptionSampleEntityClassFind;
import com.x.jpush.core.entity.PushDevice;
import org.apache.commons.lang3.StringUtils;
import javax.persistence.EntityManager;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
public class ActionRemoveBindNew extends BaseAction {
private Logger logger = LoggerFactory.getLogger( ActionRemoveBindNew.class );
protected ActionResult<Wo> execute(HttpServletRequest request, EffectivePerson effectivePerson, String deviceName, String deviceType, String pushType) throws Exception {
logger.info("execute action 'ActionRemoveBindNew'......");
ActionResult<Wo> result = new ActionResult<>();
Wo wraps = new Wo();
if (StringUtils.isEmpty(deviceName) || StringUtils.isEmpty(deviceType)) {
throw new ExceptionDeviceParameterEmpty();
}
if (!deviceType.equals(PushDevice.DEVICE_TYPE_ANDROID) && !deviceType.equals(PushDevice.DEVICE_TYPE_IOS)) {
throw new ExceptionDevicePushTypeError();
}
if (StringUtils.isEmpty(pushType)) {
throw new ExceptionDevicePushTypeError();
}
if (!pushType.equals(PushDevice.PUSH_TYPE_JPUSH) && !pushType.equals(PushDevice.PUSH_TYPE_HUAWEI)) {
throw new ExceptionDevicePushTypeError();
}
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
Business business = new Business(emc);
String unique = deviceUnique(deviceType, deviceName, pushType, effectivePerson.getDistinguishedName());
PushDevice pushDevice = business.sampleEntityClassNameFactory().findDeviceByUnique(unique);
if (pushDevice != null) {
EntityManager m = emc.beginTransaction(PushDevice.class);
emc.delete(PushDevice.class, pushDevice.getId());
m.getTransaction().commit();
wraps.setValue(true);
} else {
wraps.setValue(true);
result.setMessage("当前设备不存在,无需解绑!");
}
// List<String> deviceList = business.organization().personAttribute()
// .listAttributeWithPersonWithName(effectivePerson.getDistinguishedName(), ActionListAll.DEVICE_PERSON_ATTR_KEY);
// String device = deviceName+"_"+deviceType.toLowerCase();
// if(ListTools.isNotEmpty( deviceList ) ){
// if (deviceList.contains(device)) {
// deviceList.remove(device);
// wraps.setValue(business.organization().personAttribute()
// .setWithPersonWithName(effectivePerson.getDistinguishedName(), ActionListAll.DEVICE_PERSON_ATTR_KEY, deviceList));
// }else {
// wraps.setValue(true);
// result.setMessage("当前设备不存在,无需解绑!");
// }
// }else {
// wraps.setValue(true);
// result.setMessage("当前设备不存在,无需解绑!");
// }
result.setData(wraps);
} catch (Exception e) {
logger.error(e);
throw new ExceptionSampleEntityClassFind( e, "系统在设备解除绑定时发生异常!" );
}
logger.info("action 'ActionRemoveBindNew' execute completed!");
return result;
}
public static class Wo extends WrapBoolean {
}
}
......@@ -34,13 +34,14 @@ public class DeviceAction extends StandardJaxrsAction {
@JaxrsMethodDescribe(value = "获取当前用户所有绑定设备", action = ActionListAll.class)
@GET
@Path("all")
@Path("list/{pushType}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void listAll(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request) {
public void listAllByPushType(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("推送通道类型:jpush|huawei") @PathParam("pushType") String pushType) {
ActionResult<List<ActionListAll.Wo>> result = new ActionResult<>();
try {
result = new ActionListAll().execute(request, this.effectivePerson(request));
result = new ActionListAll().execute(request, this.effectivePerson(request), pushType);
} catch (Exception e) {
result = new ActionResult<>();
Exception exception = new ExceptionSampleEntityClassFind(e, "获取当前用户所有绑定设备时发生异常!");
......@@ -52,16 +53,17 @@ public class DeviceAction extends StandardJaxrsAction {
@JaxrsMethodDescribe(value = "检查设备是否已经绑定", action = ActionCheck.class)
@GET
@Path("check/{deviceName}/{deviceType}")
@Path("check/{deviceName}/{deviceType}/{pushType}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void checkBind(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("设备号") @PathParam("deviceName") String deviceName,
@JaxrsParameterDescribe("设备类型:android|ios") @PathParam("deviceType") String deviceType) {
@JaxrsParameterDescribe("设备类型:android|ios") @PathParam("deviceType") String deviceType,
@JaxrsParameterDescribe("推送通道类型:jpush|huawei") @PathParam("pushType") String pushType) {
ActionResult<ActionCheck.Wo> result = new ActionResult<>();
try {
result = new ActionCheck().execute(request, this.effectivePerson(request), deviceName, deviceType);
result = new ActionCheck().execute(request, this.effectivePerson(request), deviceName, deviceType, pushType);
} catch (Exception e) {
result = new ActionResult<>();
Exception exception = new ExceptionSampleEntityClassFind(e, "检查设备是否已经绑定时发生异常!");
......@@ -112,4 +114,48 @@ public class DeviceAction extends StandardJaxrsAction {
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "设备解除绑定,新版增加pushType字段", action = ActionRemoveBindNew.class)
@GET
@Path("unbind/new/{deviceName}/{deviceType}/{pushType}")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void removeBindNew(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
@JaxrsParameterDescribe("设备号") @PathParam("deviceName") String deviceName,
@JaxrsParameterDescribe("设备类型:android|ios") @PathParam("deviceType") String deviceType,
@JaxrsParameterDescribe("推送通道类型:jpush|huawei") @PathParam("pushType") String pushType) {
ActionResult<ActionRemoveBindNew.Wo> result = new ActionResult<>();
try {
result = new ActionRemoveBindNew().execute(request, this.effectivePerson(request), deviceName, deviceType, pushType);
} catch (Exception e) {
result = new ActionResult<>();
Exception exception = new ExceptionSampleEntityClassFind(e, "设备解除绑定时发生异常!");
result.error(exception);
logger.error(e, this.effectivePerson(request), request, null);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
@JaxrsMethodDescribe(value = "查询推送通道类型,jpush|huawei", action = ActionConfigPushType.class)
@GET
@Path("config/push/type")
@Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
@Consumes(MediaType.APPLICATION_JSON)
public void configPushType(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request) {
ActionResult<ActionConfigPushType.Wo> result = new ActionResult<>();
try {
result = new ActionConfigPushType().execute(request, this.effectivePerson(request));
} catch (Exception e) {
result = new ActionResult<>();
Exception exception = new ExceptionSampleEntityClassFind(e, "查询推送通道类型发生异常!");
result.error(exception);
logger.error(e, this.effectivePerson(request), request, null);
}
asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
}
}
package com.x.jpush.assemble.control.jaxrs.device;
import com.x.base.core.project.exception.PromptException;
public class ExceptionDevicePushTypeError extends PromptException {
private static final long serialVersionUID = 1859164370743532895L;
public ExceptionDevicePushTypeError() {
super("推送类型不正确,无法进行操作.");
}
}
package com.x.jpush.assemble.control.jaxrs.message;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
......@@ -10,21 +11,29 @@ import com.google.gson.JsonElement;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.project.annotation.FieldDescribe;
import com.x.base.core.project.bean.NameValuePair;
import com.x.base.core.project.config.Config;
import com.x.base.core.project.config.HuaweiPushConfig;
import com.x.base.core.project.connection.HttpConnection;
import com.x.base.core.project.gson.GsonPropertyObject;
import com.x.base.core.project.gson.XGsonBuilder;
import com.x.base.core.project.http.ActionResult;
import com.x.base.core.project.http.EffectivePerson;
import com.x.base.core.project.jaxrs.StandardJaxrsAction;
import com.x.base.core.project.jaxrs.WrapBoolean;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;
import com.x.base.core.project.tools.ListTools;
import com.x.base.core.project.tools.StringTools;
import com.x.jpush.assemble.control.Business;
import com.x.jpush.assemble.control.jaxrs.device.ActionListAll;
import com.x.jpush.assemble.control.huawei.model.Importance;
import com.x.jpush.assemble.control.huawei.model.Urgency;
import com.x.jpush.assemble.control.huawei.model.Visibility;
import com.x.jpush.core.entity.PushDevice;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
public class ActionSendMessage extends StandardJaxrsAction {
......@@ -37,69 +46,252 @@ public class ActionSendMessage extends StandardJaxrsAction {
ActionResult<Wo> result = new ActionResult<>();
Wo wraps = new Wo();
if (jsonElement == null) {
Exception exception = new ExceptionSendMessageEmpty();
result.error(exception);
return result;
throw new ExceptionSendMessageEmpty();
}
Wi wi = convertToWrapIn(jsonElement, Wi.class);
if (wi.getPerson() == null || wi.getPerson().equals("") || wi.getMessage() == null || wi.getMessage().equals("")) {
Exception exception = new ExceptionSendMessageEmpty();
result.error(exception);
return result;
throw new ExceptionSendMessageEmpty();
}
try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
Business business = new Business(emc);
logger.info("person:"+ wi.getPerson());
List<String> deviceList = business.organization().personAttribute()
.listAttributeWithPersonWithName(wi.getPerson(), ActionListAll.DEVICE_PERSON_ATTR_KEY);
if(ListTools.isNotEmpty( deviceList ) ){
List<String> jiguangDeviceList = new ArrayList<>();
for (int i = 0; i < deviceList.size(); i++) {
String deviceId = "";
try {
String[] split = deviceList.get(i).split("_");
deviceId = split[0];
logger.info("device Id:" + deviceId);
}catch (Exception e){
logger.error(e);
}
if (deviceId != null && !deviceId.isEmpty()) {
jiguangDeviceList.add(deviceId);
}
}
if(ListTools.isNotEmpty( jiguangDeviceList ) ) {
PushPayload pushPayload = PushPayload.newBuilder()
.setPlatform(Platform.all())
.setAudience(Audience.registrationId(jiguangDeviceList))
.setNotification(Notification.alert(wi.getMessage()))
.setOptions(Options.newBuilder().setApnsProduction(true).build()).build();
PushResult pushResult = business.sampleEntityClassNameFactory().jpushClient().sendPush(pushPayload);
logger.info("发送结果:{}.", pushResult);
HuaweiPushConfig config = Config.pushConfig().getHuaweiPushConfig();
if (config !=null && Config.pushConfig().getHuaweiPushEnable()) { // 华为推送通道
logger.info("华为推送通道启用中,消息发送到华为");
List<PushDevice> pushDeviceList = business.sampleEntityClassNameFactory().listHuaweiDevice(wi.getPerson());
if (pushDeviceList !=null && !pushDeviceList.isEmpty()) {
send2HuaweiPush(pushDeviceList, wi.getMessage());
wraps.setValue(true);
result.setData(wraps);
}else {
ExceptionSendMessageDeviceEmpty empty = new ExceptionSendMessageDeviceEmpty();
result.error( empty );
throw new ExceptionSendMessageDeviceEmpty();
}
}else {
ExceptionSendMessageDeviceEmpty empty = new ExceptionSendMessageDeviceEmpty();
result.error( empty );
} else {
logger.info("极光推送通道启用中,消息发送到极光推送");
List<PushDevice> pushDeviceList = business.sampleEntityClassNameFactory().listJpushDevice(wi.getPerson());
if (pushDeviceList !=null && !pushDeviceList.isEmpty()) {
send2Jpush(pushDeviceList, wi.getMessage(), business.sampleEntityClassNameFactory().jpushClient());
wraps.setValue(true);
result.setData(wraps);
}else {
throw new ExceptionSendMessageDeviceEmpty();
}
}
// List<String> deviceList = business.organization().personAttribute()
// .listAttributeWithPersonWithName(wi.getPerson(), ActionListAll.DEVICE_PERSON_ATTR_KEY);
// if(ListTools.isNotEmpty( deviceList ) ){
// List<String> jiguangDeviceList = new ArrayList<>();
// for (int i = 0; i < deviceList.size(); i++) {
// String deviceId = "";
// try {
// String[] split = deviceList.get(i).split("_");
// deviceId = split[0];
// logger.info("device Id:" + deviceId);
// }catch (Exception e){
// logger.error(e);
// }
// if (deviceId != null && !deviceId.isEmpty()) {
// jiguangDeviceList.add(deviceId);
// }
// }
// if(ListTools.isNotEmpty( jiguangDeviceList ) ) {
// //send
// wraps.setValue(true);
// result.setData(wraps);
// }else {
// ExceptionSendMessageDeviceEmpty empty = new ExceptionSendMessageDeviceEmpty();
// result.error( empty );
// }
//
// }else {
// ExceptionSendMessageDeviceEmpty empty = new ExceptionSendMessageDeviceEmpty();
// result.error( empty );
// }
} catch (Exception e) {
Exception exception = new ExceptionSendMessage( e, "系统发送极光消息时异常!" );
result.error( exception );
logger.error(e);
throw new ExceptionSendMessage( e, "系统发送推送消息时异常!" );
// result.error( exception );
}
logger.info("action 'ActionSendMessage' execute completed!");
return result;
}
/**
* 华为推送消息
* @param pushDeviceList
* @param message
* @throws Exception
*/
private void send2HuaweiPush(List<PushDevice> pushDeviceList, String message) throws Exception {
logger.info("开始发送华为推送消息, "+message);
List<String> iosList = pushDeviceList.stream().filter((p)-> p.getDeviceType().equals(PushDevice.DEVICE_TYPE_IOS)).map(PushDevice::getDeviceId).collect(Collectors.toList());
List<String> androidList = pushDeviceList.stream().filter((p)-> p.getDeviceType().equals(PushDevice.DEVICE_TYPE_ANDROID)).map(PushDevice::getDeviceId).collect(Collectors.toList());
if (!iosList.isEmpty()) {
com.x.jpush.assemble.control.huawei.model.Message m = iosMessage(iosList, message);
sendHuaweiMessage(m);
} else {
logger.info("没有ios设备需要发送消息");
}
if (!androidList.isEmpty()) {
com.x.jpush.assemble.control.huawei.model.Message m = androidMessage(androidList, message);
sendHuaweiMessage(m);
} else {
logger.info("没有Android 设备需要发送消息");
}
}
private void sendHuaweiMessage(com.x.jpush.assemble.control.huawei.model.Message msg) throws Exception {
HashMap<String, Object> sendBody = new HashMap<>();
sendBody.put("validate_only", false);
sendBody.put("message", msg);
List<NameValuePair> heads = new ArrayList<>();
String url = Config.pushConfig().getHuaweiPushConfig().getPushUrl();
logger.info("华为推送地址:"+url);
String accessToken = Config.pushConfig().getHuaweiPushConfig().accessToken();
logger.info("华为推送accessToken :"+accessToken);
heads.add(new NameValuePair("Authorization", "Bearer " + accessToken));
String body = XGsonBuilder.instance().toJson(sendBody);
logger.info("发送消息:"+body);
HuaweiSendResponse result = HttpConnection.postAsObject(url, heads, body, HuaweiSendResponse.class);
logger.info("华为消息发送完成,code:" + result.getCode() + ", msg:"+ result.getMsg() + ", requestId: "+result.getRequestId());
}
/**
* 华为Android消息
* @param deviceList
* @param message
* @return
*/
private com.x.jpush.assemble.control.huawei.model.Message androidMessage(List<String> deviceList, String message) {
com.x.jpush.assemble.control.huawei.model.Notification notification
= com.x.jpush.assemble.control.huawei.model.Notification
.builder()
.setTitle(message)
.setBody(message)
.build();
// 添加一条角标
com.x.jpush.assemble.control.huawei.android.BadgeNotification badgeNotification =
com.x.jpush.assemble.control.huawei.android.BadgeNotification.builder()
.setAddNum(1)
.setBadgeClass("net.zoneland.x.bpm.mobile.v1.zoneXBPM.app.o2.launch.LaunchActivity")
.build();
com.x.jpush.assemble.control.huawei.android.ClickAction clickAction =
com.x.jpush.assemble.control.huawei.android.ClickAction.builder()
.setType(3)// 启动应用
.build();
com.x.jpush.assemble.control.huawei.android.AndroidNotification androidNotification
= com.x.jpush.assemble.control.huawei.android.AndroidNotification.builder()
.setTitle(message)
.setBody(message)
.setDefaultSound(true)
.setAutoCancel(false)
.setBadge(badgeNotification)
.setClickAction(clickAction)
.setForegroundShow(true)
.setVisibility(Visibility.PUBLIC.getValue())
.setImportance(Importance.NORMAL.getValue())
.build();
com.x.jpush.assemble.control.huawei.android.AndroidConfig config = com.x.jpush.assemble.control.huawei.android.AndroidConfig
.builder()
.setCollapseKey(-1)
.setUrgency(Urgency.HIGH.getValue())
.setNotification(androidNotification)
.build();
return com.x.jpush.assemble.control.huawei.model.Message.builder()
.addAllToken(deviceList)
.setNotification(notification)
.setAndroidConfig(config)
.build();
}
/**
* 华为ios消息
* @param deviceList
* @param message
* @return
*/
private com.x.jpush.assemble.control.huawei.model.Message iosMessage(List<String> deviceList, String message) {
com.x.jpush.assemble.control.huawei.apns.Alert alert = com.x.jpush.assemble.control.huawei.apns.Alert.builder()
.setTitle(message)
.setBody(message)
.build();
com.x.jpush.assemble.control.huawei.apns.Aps aps = com.x.jpush.assemble.control.huawei.apns.Aps.builder()
.setAlert(alert)
.setBadge(1)
.build();
com.x.jpush.assemble.control.huawei.apns.ApnsHmsOptions apnsHmsOptions = com.x.jpush.assemble.control.huawei.apns.ApnsHmsOptions
.builder()
.setTargetUserType(2)//目标用户类型,取值如下: 1:测试用户 2:正式用户 3:VoIP用户
.build();
com.x.jpush.assemble.control.huawei.apns.ApnsConfig apns = com.x.jpush.assemble.control.huawei.apns.ApnsConfig
.builder()
.addPayloadAps(aps)
.setHmsOptions(apnsHmsOptions)
.build();
return com.x.jpush.assemble.control.huawei.model.Message.builder()
.addAllToken(deviceList)
.setApns(apns)
.build();
}
/**
* 极光推送消息
* @param pushDeviceList
* @param message
* @param client
* @throws Exception
*/
private void send2Jpush(List<PushDevice> pushDeviceList, String message, JPushClient client) throws Exception {
List<String> jiguangDeviceList = pushDeviceList.stream().map(PushDevice::getDeviceId).collect(Collectors.toList());
PushPayload pushPayload = PushPayload.newBuilder()
.setPlatform(Platform.all())
.setAudience(Audience.registrationId(jiguangDeviceList))
.setNotification(Notification.alert(message))
.setOptions(Options.newBuilder().setApnsProduction(true).build()).build();
PushResult pushResult = client.sendPush(pushPayload);
logger.info("发送结果:{}.", pushResult);
}
public static class HuaweiSendResponse {
private String code;
private String msg;
private String requestId;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getRequestId() {
return requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
}
public static class Wi extends GsonPropertyObject {
......
......@@ -40,7 +40,7 @@ public class MessageAction extends StandardJaxrsAction {
result = new ActionSendMessageTest().execute(request, this.effectivePerson(request), jsonElement);
} catch (Exception e) {
result = new ActionResult<>();
Exception exception = new ExceptionSendMessage(e, "绑定设备时发生异常!");
Exception exception = new ExceptionSendMessage(e, "发送测试消息时发生异常!");
result.error(exception);
logger.error(e, this.effectivePerson(request), request, null);
}
......@@ -59,7 +59,7 @@ public class MessageAction extends StandardJaxrsAction {
result = new ActionSendMessage().execute(request, this.effectivePerson(request), jsonElement);
} catch (Exception e) {
result = new ActionResult<>();
Exception exception = new ExceptionSendMessage(e, "绑定设备时发生异常!");
Exception exception = new ExceptionSendMessage(e, "发送消息时发生异常!");
result.error(exception);
logger.error(e, this.effectivePerson(request), request, null);
}
......
package com.x.jpush.assemble.control.jaxrs.sample;
import com.x.base.core.project.jaxrs.StandardJaxrsAction;
import com.x.base.core.project.tools.MD5Tool;
public class BaseAction extends StandardJaxrsAction{
/**
* md5(deviceType+deviceId+pushType+person)
* @return
*/
protected String deviceUnique(String deviceType, String deviceId, String pushType, String person) {
return MD5Tool.getMD5Str(deviceType+deviceId+pushType+person);
}
}
......@@ -7,4 +7,8 @@ public final class PersistenceProperties extends AbstractPersistenceProperties {
public static class SampleEntityClassName {
public static final String table = "SAMPLE_JPUSH_TABLENAME";
}
public static class PushDevice {
public static final String table = "JPUSH_DEVICE";
}
}
\ No newline at end of file
package com.x.jpush.core.entity;
import com.x.base.core.entity.JpaObject;
import com.x.base.core.entity.SliceJpaObject;
import com.x.base.core.entity.annotation.CheckPersist;
import com.x.base.core.entity.annotation.ContainerEntity;
import com.x.base.core.project.annotation.FieldDescribe;
import org.apache.openjpa.persistence.jdbc.Index;
import javax.persistence.*;
/**
* Created by fancyLou on 9/13/21.
* Copyright © 2021 O2. All rights reserved.
*/
@ContainerEntity(dumpSize = 1000, type = ContainerEntity.Type.content, reference = ContainerEntity.Reference.strong)
@Entity
@Table(name = PersistenceProperties.PushDevice.table, uniqueConstraints = {
@UniqueConstraint(name = PersistenceProperties.PushDevice.table + JpaObject.IndexNameMiddle
+ JpaObject.DefaultUniqueConstraintSuffix, columnNames = { JpaObject.IDCOLUMN,
JpaObject.CREATETIMECOLUMN, JpaObject.UPDATETIMECOLUMN, JpaObject.SEQUENCECOLUMN }) })
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class PushDevice extends SliceJpaObject {
private static final String TABLE = PersistenceProperties.PushDevice.table;
private static final long serialVersionUID = 2074606124902551261L;
@Override
public void onPersist() throws Exception {
}
@FieldDescribe("数据库主键,自动生成.")
@Id
@Column(length = length_id, name = ColumnNamePrefix + id_FIELDNAME)
private String id = createId();
@Override
public String getId() {
return id;
}
@Override
public void setId(String id) {
this.id = id;
}
/*
* =============================================================================
* ===== 以下为具体不同的业务及数据表字段要求
* =============================================================================
* =====
*/
private static final String deviceId_FIELDNAME = "deviceId";
@FieldDescribe("设备id,发送推送消息用的设备唯一编码")
@Column(name = ColumnNamePrefix + deviceId_FIELDNAME, length = JpaObject.length_255B)
@Index(name = TABLE + IndexNameMiddle + deviceId_FIELDNAME)
@CheckPersist(allowEmpty = false)
private String deviceId;
//推送通道类型
public static final String DEVICE_TYPE_IOS = "ios";
public static final String DEVICE_TYPE_ANDROID = "android";
private static final String deviceType_FIELDNAME = "deviceType";
@FieldDescribe("设备类型:ios|android")
@Column(name = ColumnNamePrefix + deviceType_FIELDNAME, length = JpaObject.length_16B)
@Index(name = TABLE + IndexNameMiddle + deviceType_FIELDNAME)
@CheckPersist(allowEmpty = false)
private String deviceType;
//推送通道类型
public static final String PUSH_TYPE_JPUSH = "jpush";
public static final String PUSH_TYPE_HUAWEI = "huawei";
private static final String pushType_FIELDNAME = "pushType";
@FieldDescribe("推送通道类型:jpush|huawei")
@Column(name = ColumnNamePrefix + pushType_FIELDNAME, length = JpaObject.length_16B)
@Index(name = TABLE + IndexNameMiddle + pushType_FIELDNAME)
@CheckPersist(allowEmpty = false)
private String pushType;
private static final String person_FIELDNAME = "person";
@FieldDescribe("人员标识")
@Column(name = ColumnNamePrefix + person_FIELDNAME, length = JpaObject.length_255B)
@Index(name = TABLE + IndexNameMiddle + person_FIELDNAME)
@CheckPersist(allowEmpty = false)
private String person;
private static final String unique_FIELDNAME = "unique";
@FieldDescribe("唯一编码,md5(deviceType+deviceId+pushType+person)")
@Column(name = ColumnNamePrefix + unique_FIELDNAME, length = JpaObject.length_255B)
@Index(name = TABLE + IndexNameMiddle + unique_FIELDNAME)
@CheckPersist(allowEmpty = false)
private String unique;
public String getUnique() {
return unique;
}
public void setUnique(String unique) {
this.unique = unique;
}
public String getDeviceId() {
return deviceId;
}
public void setDeviceId(String deviceId) {
this.deviceId = deviceId;
}
public String getDeviceType() {
return deviceType;
}
public void setDeviceType(String deviceType) {
this.deviceType = deviceType;
}
public String getPushType() {
return pushType;
}
public void setPushType(String pushType) {
this.pushType = pushType;
}
public String getPerson() {
return person;
}
public void setPerson(String person) {
this.person = person;
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册