diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3197301 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +/build/ +/nbproject/private/ \ No newline at end of file diff --git a/README.md b/README.md index fe697c7..0d3d9fa 100644 --- a/README.md +++ b/README.md @@ -1 +1,66 @@ -# kavenegar-java \ No newline at end of file +#Java SDK +# Kavenegar RESTful API Document +If you need to future information about API document Please visit RESTful Document + +## Installation +

+First of all, You need to make an account on Kavenegar from Here +

+

+After that you just need to pick API-KEY up from My Account section. +Here You can download the Java SDK Here or just pull it. +Anyway there is good tutorial about Pull request +

+ +## Usage +Well, There is an example to Send SMS by Java. + +```java + +try { + KavenegarApi api= new KavenegarApi(""); + SendResult Result = api.Send("SenderLine", "Your Receptor", "خدمات پیام کوتاه کاوه نگار"); +} +catch (HttpException ex) +{ // در صورتی که خروجی وب سرویس 200 نباشد این خطارخ می دهد. + System.out.print("HttpException : " + ex.getMessage()); +} +catch (ApiException ex) +{ // در صورتی که خروجی وب سرویس 200 نباشد این خطارخ می دهد. + System.out.print("ApiException : " + ex.getMessage()); +} + +``` + +#Contribution +Bug fixes, docs, and enhancements welcome! Please let us know support@kavenegar.com + + + +## Persian tutorial / راهنمای فارسی +###راهنما +در صورتی که مایل هستید راهنمای فارسی کیت توسعه کاوه نگار را مطالعه کنید به سفحه +کد ارسال پیامک +مراجعه کنید + +###مستندات +

+برای مطالعه مستندات کار با +وب سرویس اس ام اس +کاوه نگار به سفحه مستنداتمراجعه کنید +

+###معرفی وب سرویس کاوه نگار +

+برای مشاهده ویژگی های + +وب سرویس پیامک + +کاوه نگار به صفحه وب سرویس مراجعه نمائید +

+### ایجاد حساب کاربری +

+و بالاخره اگر در استفاده از سرویس کاوه نگار مشکلی داشتید یا پیشنهاد همکاری بود لطفا حتما به ما اطلاع دهید +
+support@kavenegar.com + +

diff --git a/build.xml b/build.xml new file mode 100644 index 0000000..c2b2ff1 --- /dev/null +++ b/build.xml @@ -0,0 +1,73 @@ + + + + + + + + + + + Builds, tests, and runs the project Kavenegar. + + + diff --git a/dist/Kavenegar.jar b/dist/Kavenegar.jar new file mode 100644 index 0000000..740960c Binary files /dev/null and b/dist/Kavenegar.jar differ diff --git a/lib/commons-codec-1.6.jar b/lib/commons-codec-1.6.jar new file mode 100644 index 0000000..ee1bc49 Binary files /dev/null and b/lib/commons-codec-1.6.jar differ diff --git a/lib/commons-io-2.4.jar b/lib/commons-io-2.4.jar new file mode 100644 index 0000000..90035a4 Binary files /dev/null and b/lib/commons-io-2.4.jar differ diff --git a/lib/commons-logging-1.1.1.jar b/lib/commons-logging-1.1.1.jar new file mode 100644 index 0000000..1deef14 Binary files /dev/null and b/lib/commons-logging-1.1.1.jar differ diff --git a/lib/gson-2.2.4.jar b/lib/gson-2.2.4.jar new file mode 100644 index 0000000..75fe27c Binary files /dev/null and b/lib/gson-2.2.4.jar differ diff --git a/lib/httpclient-4.2.1.jar b/lib/httpclient-4.2.1.jar new file mode 100644 index 0000000..0e999fc Binary files /dev/null and b/lib/httpclient-4.2.1.jar differ diff --git a/lib/httpcore-4.2.1.jar b/lib/httpcore-4.2.1.jar new file mode 100644 index 0000000..16d75e1 Binary files /dev/null and b/lib/httpcore-4.2.1.jar differ diff --git a/nbproject/build-impl.xml b/nbproject/build-impl.xml new file mode 100644 index 0000000..8151fa1 --- /dev/null +++ b/nbproject/build-impl.xml @@ -0,0 +1,1419 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set src.dir + Must set test.src.dir + Must set build.dir + Must set dist.dir + Must set build.classes.dir + Must set dist.javadoc.dir + Must set build.test.classes.dir + Must set build.test.results.dir + Must set build.classes.excludes + Must set dist.jar + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + No tests executed. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must set JVM to use for profiling in profiler.info.jvm + Must set profiler agent JVM arguments in profiler.info.jvmargs.agent + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + To run this application from the command line without Ant, try: + + java -jar "${dist.jar.resolved}" + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + Must select one file in the IDE or set run.class + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set debug.class + + + + + Must select one file in the IDE or set debug.class + + + + + Must set fix.includes + + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + Must select one file in the IDE or set profile.class + This target only works when run from inside the NetBeans IDE. + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + This target only works when run from inside the NetBeans IDE. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select one file in the IDE or set run.class + + + + + + Must select some files in the IDE or set test.includes + + + + + Must select one file in the IDE or set run.class + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Must select some files in the IDE or set javac.includes + + + + + + + + + + + + + + + + + + + + Some tests failed; see details above. + + + + + + + + + Must select some files in the IDE or set test.includes + + + + Some tests failed; see details above. + + + + Must select some files in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + Some tests failed; see details above. + + + + + Must select one file in the IDE or set test.class + + + + Must select one file in the IDE or set test.class + Must select some method in the IDE or set test.method + + + + + + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + Must select one file in the IDE or set applet.url + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/nbproject/genfiles.properties b/nbproject/genfiles.properties new file mode 100644 index 0000000..32940c4 --- /dev/null +++ b/nbproject/genfiles.properties @@ -0,0 +1,8 @@ +build.xml.data.CRC32=282b5b18 +build.xml.script.CRC32=43cdb420 +build.xml.stylesheet.CRC32=8064a381@1.75.2.48 +# This file is used by a NetBeans-based IDE to track changes in generated files such as build-impl.xml. +# Do not edit this file. You may delete it but then the IDE will never regenerate such files for you. +nbproject/build-impl.xml.data.CRC32=282b5b18 +nbproject/build-impl.xml.script.CRC32=77a3f63f +nbproject/build-impl.xml.stylesheet.CRC32=05530350@1.79.1.48 diff --git a/nbproject/project.properties b/nbproject/project.properties new file mode 100644 index 0000000..dd753ef --- /dev/null +++ b/nbproject/project.properties @@ -0,0 +1,87 @@ +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=false +annotation.processing.processors.list= +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +application.title=Kavenegar +application.vendor=bgsrb +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# Files in build.classes.dir which should be excluded from distribution jar +dist.archive.excludes= +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/Kavenegar.jar +dist.javadoc.dir=${dist.dir}/javadoc +endorsed.classpath= +excludes= +file.reference.commons-codec-1.6.jar-1=lib\\commons-codec-1.6.jar +file.reference.commons-io-2.4.jar-1=lib\\commons-io-2.4.jar +file.reference.commons-logging-1.1.1.jar-1=lib\\commons-logging-1.1.1.jar +file.reference.gson-2.2.4.jar-1=lib\\gson-2.2.4.jar +file.reference.httpclient-4.2.1.jar-1=lib\\httpclient-4.2.1.jar +file.reference.httpcore-4.2.1.jar-1=lib\\httpcore-4.2.1.jar +includes=** +jar.compress=false +javac.classpath=\ + ${file.reference.commons-codec-1.6.jar-1}:\ + ${file.reference.commons-io-2.4.jar-1}:\ + ${file.reference.commons-logging-1.1.1.jar-1}:\ + ${file.reference.gson-2.2.4.jar-1}:\ + ${file.reference.httpclient-4.2.1.jar-1}:\ + ${file.reference.httpcore-4.2.1.jar-1} +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.external.vm=false +javac.processorpath=\ + ${javac.classpath} +javac.source=1.8 +javac.target=1.8 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +main.class=example.Example +meta.inf.dir=${src.dir}/META-INF +mkdist.disabled=true +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project. +# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value. +# To set system properties for unit tests define test-sys-prop.name=value: +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=src +test.src.dir=test diff --git a/nbproject/project.xml b/nbproject/project.xml new file mode 100644 index 0000000..1b9a531 --- /dev/null +++ b/nbproject/project.xml @@ -0,0 +1,15 @@ + + + org.netbeans.modules.java.j2seproject + + + Kavenegar + + + + + + + + + diff --git a/src/com/kavenegar/KavenegarApi.java b/src/com/kavenegar/KavenegarApi.java new file mode 100644 index 0000000..a092c49 --- /dev/null +++ b/src/com/kavenegar/KavenegarApi.java @@ -0,0 +1,510 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.kavenegar; + +import com.google.gson.JsonArray; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonPrimitive; + +import java.util.ArrayList; +import java.util.List; + +import org.apache.http.HttpResponse; +import org.apache.http.client.HttpClient; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.impl.client.DefaultHttpClient; + + +import com.kavenegar.enums.*; +import com.kavenegar.excepctions.*; +import com.kavenegar.utils.*; +import com.kavenegar.models.*; + +/** + * + * @author Kavenegar + */ +public class KavenegarApi { + + String apikey; + static final String apipath = "https://api.kavenegar.com/v1/%s/%s/%s.%s"; + public KavenegarApi(String _apikey) { + this.apikey = _apikey; + } + + private String getApiPath(String base, String method, String output) { + return String.format(apipath, apikey, base, method, output); + } + + private JsonElement Execute(String path, Object...params) throws BaseException { + UrlEncodedFormEntity parameters; + parameters = ApiHelper.createParams(params); + HttpClient client = new DefaultHttpClient(); + HttpPost post = new HttpPost(path); + post.setEntity(parameters); + HttpResponse response; + try { + response = client.execute(post); + } catch (Exception ex) { + throw new HttpException("Http Request Exception", 0); + } + JsonObject result = ApiHelper.getResult(response); + if (result == null) { + int httpcode = response.getStatusLine().getStatusCode(); + if (httpcode != 200) { + throw new HttpException("Http request exception , code : " + httpcode, httpcode); + } + } else { + JsonObject return_json = result.get("return").getAsJsonObject(); + if (200 == return_json.get("status").getAsInt()) {} else { + throw new ApiException(return_json.get("message").getAsString(), return_json.get("status").getAsInt()); + } + } + return result.get("entries"); + } + + /* + Send + */ + public SendResult Send(String sender, String receptor, String message) throws BaseException { + return Send(sender, receptor, message, MessageType.MobileMemory, 0); + } + public SendResult Send(String sender, String receptor, String message, MessageType type, long date) throws BaseException { + return Send(sender, new String[] { + receptor + }, message, type, date).get(0); + } + public List < SendResult > Send(String sender, String[] receptors, String message) throws BaseException { + return Send(sender, receptors, message, MessageType.MobileMemory, 0); + } + public List < SendResult > Send(String sender, String[] receptors, String message, MessageType type, long date) throws BaseException { + return Send(sender, receptors, message, type, date, null); + } + public SendResult Send(String sender, String receptor, String message, MessageType type, long date, String localid) throws BaseException { + return Send(sender, new String[] { + receptor + }, message, MessageType.MobileMemory, 0, new String[] { + localid + }).get(0); + } + public SendResult Send(String sender, String receptor, String message, String localid) throws BaseException { + return Send(sender, receptor, message, MessageType.MobileMemory, 0, localid); + } + public List < SendResult > Send(String sender, String[] receptor, String message, MessageType type, long date, String[] localid) throws BaseException { + String path = getApiPath("sms", "send", "json"); + JsonArray entry = Execute(path, "sender", sender, "receptor", StringUtils.Join(",", receptor), "message", message, "type", type.getValue(), "date", date, StringUtils.Join(",", localid)).getAsJsonArray(); + List < SendResult > list = new ArrayList < > (); + for (int i = 0; i < entry.size(); i++) { + JsonObject obj = entry.get(i).getAsJsonObject(); + SendResult result = new SendResult(); + result.setCost(obj.get("cost").getAsInt()); + result.setDate(obj.get("date").getAsLong()); + result.setMessageId(obj.get("messageid").getAsLong()); + result.setMessage(obj.get("message").getAsString()); + result.setReceptor(obj.get("receptor").getAsString()); + result.setStatus(obj.get("status").getAsInt()); + result.setStatusText(obj.get("statustext").getAsString()); + list.add(result); + } + return list; + } + + /* + SendArray + */ + public List < SendResult > SendArray(String[] senders, String[] receptors, String[] messages) throws BaseException { + return SendArray(senders, receptors, messages, null); + } + public List < SendResult > SendArray(String[] senders, String[] receptors, String[] messages, String localid) throws BaseException { + MessageType[] types = new MessageType[receptors.length]; + for (int i = 0; i < receptors.length; i++) { + types[i] = MessageType.MobileMemory; + } + String[] localids = new String[receptors.length]; + for (int i = 0; i < receptors.length; i++) { + localids[i] = localid; + } + return SendArray(senders, receptors, messages, types, 0, localids); + } + public List < SendResult > SendArray(String[] senders, String[] receptors, String[] messages, MessageType[] types, long date, String localid) throws BaseException { + String[] localids = new String[receptors.length]; + for (int i = 0; i < receptors.length; i++) { + localids[i] = localid; + } + return SendArray(senders, receptors, messages, types, 0, localids); + } + public List < SendResult > SendArray(String sender, String[] receptors, String[] messages) throws BaseException { + return SendArray(sender, receptors, messages, null); + } + public List < SendResult > SendArray(String sender, String[] receptors, String[] messages, String localid) throws BaseException { + MessageType[] types = new MessageType[receptors.length]; + for (int i = 0; i < types.length; i++) { + types[i] = MessageType.MobileMemory; + } + String[] senders = new String[receptors.length]; + for (int i = 0; i < receptors.length; i++) { + senders[i] = sender; + } + return SendArray(senders, receptors, messages, types, 0, localid); + } + public List < SendResult > SendArray(String sender, String[] receptors, String[] messages, MessageType[] types, long date, String localid) throws BaseException { + String[] senders = new String[receptors.length]; + for (int i = 0; i < receptors.length; i++) { + senders[i] = sender; + } + String[] localids = new String[receptors.length]; + for (int i = 0; i < receptors.length; i++) { + localids[i] = localid; + } + return SendArray(senders, receptors, messages, types, 0, localids); + } + public List < SendResult > SendArray(String[] senders, String[] receptors, String[] messages, MessageType[] type, long date, String[] localids) throws BaseException { + String path = getApiPath("sms", "sendarray", "json"); + JsonArray json_receptors = new JsonArray(); + JsonArray json_senders = new JsonArray(); + JsonArray json_messages = new JsonArray(); + JsonArray json_types = new JsonArray(); + for (int i = 0; i < messages.length; i++) { + json_receptors.add(new JsonPrimitive(receptors[i])); + json_senders.add(new JsonPrimitive(senders[i])); + json_messages.add(new JsonPrimitive(messages[i])); + json_types.add(new JsonPrimitive(type[i].getValue())); + } + JsonArray entry = Execute(path, "sender", json_senders.toString(), "receptor", json_receptors.toString(), "message", json_messages.toString(), "date", date, "type", json_types.toString(), "localids", localids).getAsJsonArray(); + List < SendResult > list = new ArrayList < > (); + for (int i = 0; i < entry.size(); i++) { + JsonObject obj = entry.get(i).getAsJsonObject(); + SendResult result = new SendResult(); + result.setCost(obj.get("cost").getAsInt()); + result.setDate(obj.get("date").getAsLong()); + result.setMessageId(obj.get("messageid").getAsLong()); + result.setMessage(obj.get("message").getAsString()); + result.setReceptor(obj.get("receptor").getAsString()); + result.setStatus(obj.get("status").getAsInt()); + result.setStatusText(obj.get("statustext").getAsString()); + list.add(result); + } + return list; + } + + /* + Status + */ + public List < StatusResult > Status(Long[] messageid) throws BaseException { + String path = getApiPath("sms", "status", "json"); + String id = StringUtils.Join(",", messageid); + JsonArray array = Execute(path, "messageid", id).getAsJsonArray(); + List < StatusResult > list = new ArrayList < > (); + for (int i = 0; i < array.size(); i++) { + StatusResult result = new StatusResult(); + JsonObject entry = array.get(i).getAsJsonObject(); + result.setMessageId(entry.get("messageid").getAsInt()); + result.setStatus(MessageStatus.valueOf(entry.get("status").getAsInt())); + result.setStatusText(entry.get("statustext").getAsString()); + list.add(result); + } + return list; + } + public StatusResult Status(Long messageid) throws BaseException { + return Status(new Long[] { + messageid + }).get(0); + } + + /* + StatusLocalMessageIdResult + */ + public List < StatusLocalMessageIdResult > StatusLocalMessageId(Long[] localids) throws BaseException { + String path = getApiPath("sms", "statuslocalmessageid", "json"); + String id = StringUtils.Join(",", localids); + JsonArray array = Execute(path, "localid", id).getAsJsonArray(); + List < StatusLocalMessageIdResult > list = new ArrayList < > (); + for (int i = 0; i < array.size(); i++) { + StatusLocalMessageIdResult result = new StatusLocalMessageIdResult(); + JsonObject entry = array.get(i).getAsJsonObject(); + result.setMessageId(entry.get("messageid").getAsInt()); + result.setStatus(MessageStatus.valueOf(entry.get("status").getAsInt())); + result.setStatusText(entry.get("statustext").getAsString()); + list.add(result); + } + return list; + } + public StatusLocalMessageIdResult StatusLocalMessageId(Long localid) throws BaseException { + return StatusLocalMessageId(new Long[] { + localid + }).get(0); + } + + /* + Select + */ + public List < SendResult > Select(Long[] ids) throws BaseException { + String path = getApiPath("sms", "select", "json"); + String massageids = StringUtils.Join(",", ids); + JsonArray array = Execute(path, "messageid", massageids).getAsJsonArray(); + List < SendResult > list = new ArrayList < > (); + for (int i = 0; i < array.size(); i++) { + SendResult result = new SendResult(); + JsonObject entry = array.get(i).getAsJsonObject(); + result.setCost(entry.get("cost").getAsInt()); + result.setDate(entry.get("date").getAsLong()); + result.setMessageId(entry.get("messageid").getAsLong()); + result.setMessage(entry.get("message").getAsString()); + result.setReceptor(entry.get("receptor").getAsString()); + result.setStatus(entry.get("status").getAsInt()); + result.setStatusText(entry.get("statustext").getAsString()); + list.add(result); + } + return list; + } + public SendResult Select(long messageid) throws BaseException { + return Select(new Long[] { + messageid + }).get(0); + } + + /* + SelectOutbox + */ + public List < SendResult > SelectOutbox(long startdate) throws BaseException { + return SelectOutbox(startdate, 0, ""); + } + public List < SendResult > SelectOutbox(long startdate, long enddate) throws BaseException { + return SelectOutbox(startdate, enddate, ""); + } + public List < SendResult > SelectOutbox(long startdate, long enddate, String sender) throws BaseException { + String path = getApiPath("sms", "selectoutbox", "json"); + JsonArray array = Execute(path, "startdate", startdate, "enddate", enddate, "sender", sender).getAsJsonArray(); + List < SendResult > list = new ArrayList < > (); + for (int i = 0; i < array.size(); i++) { + SendResult result = new SendResult(); + JsonObject entry = array.get(i).getAsJsonObject(); + result.setCost(entry.get("cost").getAsInt()); + result.setDate(entry.get("date").getAsLong()); + result.setMessageId(entry.get("messageid").getAsLong()); + result.setMessage(entry.get("message").getAsString()); + result.setReceptor(entry.get("receptor").getAsString()); + result.setStatus(entry.get("status").getAsInt()); + result.setStatusText(entry.get("statustext").getAsString()); + list.add(result); + } + return list; + } + + /* + LatestOutbox + */ + public List < SendResult > LatestOutbox() throws BaseException { + long pagesize = 3000; + return LatestOutbox(pagesize, ""); + } + public List < SendResult > LatestOutbox(Long pagesize) throws BaseException { + return LatestOutbox(pagesize, ""); + } + public List < SendResult > LatestOutbox(Long pagesize, String sender) throws BaseException { + String path = getApiPath("sms", "latestoutbox", "json"); + JsonArray array = Execute(path, "pagesize", pagesize, "sender", sender).getAsJsonArray(); + List < SendResult > list = new ArrayList < > (); + for (int i = 0; i < array.size(); i++) { + SendResult result = new SendResult(); + JsonObject entry = array.get(i).getAsJsonObject(); + result.setMessageId(entry.get("messageid").getAsLong()); + result.setMessage(entry.get("message").getAsString()); + result.setSender(entry.get("sender").getAsString()); + result.setReceptor(entry.get("receptor").getAsString()); + result.setStatus(entry.get("status").getAsInt()); + result.setStatusText(entry.get("statustext").getAsString()); + result.setCost(entry.get("cost").getAsInt()); + result.setDate(entry.get("date").getAsLong()); + list.add(result); + } + return list; + } + + /* + CountOutbox + */ + public CountOutboxResult CountOutbox(long startdate) throws BaseException { + return CountOutbox(startdate, 0, 0); + } + public CountOutboxResult CountOutbox(long startdate, long enddate) throws BaseException { + return CountOutbox(startdate, enddate, 0); + } + public CountOutboxResult CountOutbox(long startdate, long enddate, int status) throws BaseException { + String path = getApiPath("sms", "countoutbox", "json"); + JsonObject entry = Execute(path, "startdate", startdate, "enddate", enddate, "status", status).getAsJsonArray().get(0).getAsJsonObject(); + CountOutboxResult result = new CountOutboxResult(); + result.setStartDate(entry.get("startdate").getAsLong()); + result.setEndDate(entry.get("enddate").getAsLong()); + result.setSumPart(entry.get("sumpart").getAsLong()); + result.setSumCount(entry.get("sumcount").getAsLong()); + result.setCost(entry.get("cost").getAsLong()); + return result; + } + + /* + Cancel + */ + public List < StatusResult > Cancel(Long[] messageids) throws BaseException { + String path = getApiPath("sms", "cancel", "json"); + String id = StringUtils.Join(",", messageids); + JsonArray array = Execute(path, "messageid", id).getAsJsonArray(); + List < StatusResult > list = new ArrayList < > (); + for (int i = 0; i < array.size(); i++) { + StatusResult result = new StatusResult(); + JsonObject entry = array.get(i).getAsJsonObject(); + result.setMessageId(entry.get("messageid").getAsInt()); + result.setStatus(MessageStatus.valueOf(entry.get("status").getAsInt())); + result.setStatusText(entry.get("statustext").getAsString()); + } + return list; + } + public StatusResult Cancel(Long messageid) throws BaseException { + return Cancel(new Long[] { + messageid + }).get(0); + } + + /* + Receive + */ + public List < ReciveResult > Receive(String linenumber, int isread) throws BaseException { + String path = getApiPath("sms", "receive", "json"); + JsonElement res = Execute(path, "linenumber", linenumber, "isread", isread); + if (res.isJsonNull()) { + return new ArrayList < > (); + } + JsonArray array = res.getAsJsonArray(); + List < ReciveResult > list = new ArrayList < > (); + for (int i = 0; i < array.size(); i++) { + JsonObject json_obj = array.get(i).getAsJsonObject(); + ReciveResult result = new ReciveResult(); + result.setMessageId(json_obj.get("messageid").getAsInt()); + result.setDate(json_obj.get("date").getAsLong()); + result.setMessage(json_obj.get("message").getAsString()); + result.setSender(json_obj.get("sender").getAsString()); + result.setReceptor(json_obj.get("receptor").getAsString()); + list.add(result); + } + return list; + } + /* + CountInbox + */ + public CountInboxResult CountInbox(long startdate, String linenumber) throws BaseException { + return CountInbox(startdate, 0, linenumber, 0); + } + public CountInboxResult CountInbox(long startdate, long enddate, String linenumber) throws BaseException { + return CountInbox(startdate, enddate, linenumber, 0); + } + public CountInboxResult CountInbox(long startdate, long enddate, String linenumber, int isread) throws BaseException { + String path = getApiPath("sms", "countinbox", "json"); + JsonObject entry = Execute(path, "startdate", startdate, "enddate", enddate, "linenumber", linenumber, "isread", isread).getAsJsonArray().get(0).getAsJsonObject(); + CountInboxResult result = new CountInboxResult(); + result.setStartDate(entry.get("startdate").getAsLong()); + result.setEndDate(entry.get("enddate").getAsLong()); + result.setSumCount(entry.get("sumcount").getAsLong()); + return result; + } + + /* + SendByPostalCode + */ + public List < SendResult > SendByPostalCode(long postalcode, String sender, String message, long mcistartIndex, long mcicount, long mtnstartindex, long mtncount) throws BaseException { + return SendByPostalCode(postalcode, sender, message, mcistartIndex, mcicount, mtnstartindex, mtncount, 0); + } + public List < SendResult > SendByPostalCode(long postalcode, String sender, String message, long mcistartIndex, long mcicount, long mtnstartindex, long mtncount, long date) throws BaseException { + String path = getApiPath("sms", "sendpostalcode", "json"); + JsonArray entry = Execute(path, "postalcode", postalcode, "sender", sender, "message", message, "mcistartIndex", mcistartIndex, "mcicount", mtnstartindex, "mtnstartindex", mtncount, "mtncount", "date", date).getAsJsonArray(); + List < SendResult > list = new ArrayList < > (); + for (int i = 0; i < entry.size(); i++) { + JsonObject obj = entry.get(i).getAsJsonObject(); + SendResult result = new SendResult(); + result.setCost(obj.get("cost").getAsInt()); + result.setDate(obj.get("date").getAsLong()); + result.setMessageId(obj.get("messageid").getAsLong()); + result.setMessage(obj.get("message").getAsString()); + result.setReceptor(obj.get("receptor").getAsString()); + result.setStatus(obj.get("status").getAsInt()); + result.setStatusText(obj.get("statustext").getAsString()); + list.add(result); + } + return list; + } + + + /* + CountPostalCode + */ + public List < CountPostalCodeResult > CountPostalCode(long postalcode) throws BaseException { + String path = getApiPath("sms", "countpostalcode", "json"); + JsonArray array = Execute(path, "postalcode", postalcode).getAsJsonArray(); + List < CountPostalCodeResult > list = new ArrayList < > (); + for (int i = 0; i < array.size(); i++) { + CountPostalCodeResult result = new CountPostalCodeResult(); + JsonObject entry = array.get(i).getAsJsonObject(); + result.setSection(entry.get("section").getAsString()); + result.setValue(entry.get("value").getAsLong()); + list.add(result); + } + return list; + } + + + /* + AccountInfo + */ + public AccountInfoResult AccountInfo() throws BaseException { + String path; + path = getApiPath("account", "info", "json"); + JsonObject entry = Execute(path).getAsJsonObject(); + AccountInfoResult result = new AccountInfoResult(); + result.setRemainCredit(entry.get("remaincredit").getAsLong()); + result.setExpireDate(entry.get("expiredate").getAsLong()); + result.setType(entry.get("type").getAsString()); + return result; + } + + + /* + AccountConfig + */ + public AccountConfigResult AccountConfig(String apilogs, String dailyreport, String debugmode, String defaultsender, int mincreditalarm, String resendfailed) throws BaseException { + String path = getApiPath("account", "config", "json"); + JsonObject entry = Execute(path, "apilogs", dailyreport, "dailyreport", debugmode, "debugmode", debugmode, "defaultsender", defaultsender, "mincreditalarm", mincreditalarm, "mincreditalarm", mincreditalarm).getAsJsonObject(); + AccountConfigResult result = new AccountConfigResult(); + result.setApilogs(entry.get("apilogs").getAsString()); + result.setDailyReport(entry.get("dailyreport").getAsString()); + result.setDebugMode(entry.get("debugmode").getAsString()); + result.setDefaultSender(entry.get("DefaultSender").getAsString()); + result.setResendFailed(entry.get("resendfailed").getAsString()); + result.setMinCreditAlarm(entry.get("Mincreditalarm").getAsInt()); + return result; + } + + /* + VerifyLookup + */ + public SendResult VerifyLookup(String receptor, String token, String token2, String token3, String template) throws BaseException { + String path = getApiPath("verify", "lookup", "json"); + JsonArray array = Execute(path, "receptor", receptor, "token", token, "token2", token2, "token3", token3, "template", template).getAsJsonArray(); + JsonObject entry = array.get(0).getAsJsonObject(); + SendResult result = new SendResult(); + result.setCost(entry.get("cost").getAsInt()); + result.setDate(entry.get("date").getAsLong()); + result.setMessageId(entry.get("messageid").getAsLong()); + result.setMessage(entry.get("message").getAsString()); + result.setReceptor(entry.get("receptor").getAsString()); + result.setStatus(entry.get("status").getAsInt()); + result.setStatusText(entry.get("statustext").getAsString()); + return result; + } + public SendResult VerifyLookup(String receptor, String token, String template) throws BaseException { + return VerifyLookup(receptor, token, "", "", template); + } + +} \ No newline at end of file diff --git a/src/com/kavenegar/enums/MessageStatus.java b/src/com/kavenegar/enums/MessageStatus.java new file mode 100644 index 0000000..cbb3fba --- /dev/null +++ b/src/com/kavenegar/enums/MessageStatus.java @@ -0,0 +1,41 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.kavenegar.enums; + +import com.kavenegar.enums.*; + +/** + * + * @author mohsen + */ +public enum MessageStatus { + Queued(1), + Schulded(2), + SentToCenter(4), + Delivered(10), + Undelivered(11), + Canceled(13), + Filtered(14), + Received(50), + Incorrect(100); + private int value; + + private MessageStatus(int type) { + this.value = type; + } + + public int getValue() { + return value; + } + + public static MessageStatus valueOf(int type) { + for (MessageStatus code : MessageStatus.values()) { + if (type == code.getValue()) { + return code; + } + } + return null; + } +} diff --git a/src/com/kavenegar/enums/MessageType.java b/src/com/kavenegar/enums/MessageType.java new file mode 100644 index 0000000..3c20dba --- /dev/null +++ b/src/com/kavenegar/enums/MessageType.java @@ -0,0 +1,37 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.kavenegar.enums; + +import com.kavenegar.enums.*; + +/** + * + * @author mohsen + */ +public enum MessageType { + + Flash(0), + MobileMemory(1), + SimMemory(2), + AppMemory(3); + private int value; + + private MessageType(int type) { + this.value = type; + } + + public int getValue() { + return value; + } + + public static MessageType valueOf(int type) { + for (MessageType code : MessageType.values()) { + if (type == code.getValue()) { + return code; + } + } + return null; + } +} diff --git a/src/com/kavenegar/enums/MetaData.java b/src/com/kavenegar/enums/MetaData.java new file mode 100644 index 0000000..89265f5 --- /dev/null +++ b/src/com/kavenegar/enums/MetaData.java @@ -0,0 +1,50 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.kavenegar.enums; + +import com.kavenegar.enums.*; + +/** + * + * @author Mohsen + */ +public enum MetaData { + + NotChecked(99), + Approved(100), + InvalidApiKey(101), + ExpiredApiKey(102), + AccountDisabled(103), + NotEnoughCredit(104), + ServerisBusy(105), + UndefinedCommand(106), + RequestFailed(107), + ParametersBroken(108), + InvalidRecp(110), + InvalidSenderNumber(111), + EmptyMessage(112), + RecpIsTooLarge(113), + InvalidDate(114), + MsgIsTooLarge(115), + RecpNotEqualWithMessage(116); + private int value; + + private MetaData(int type) { + this.value = type; + } + + public int getValue() { + return value; + } + + public static MetaData valueOf(int type) { + for (MetaData code : MetaData.values()) { + if (type == code.getValue()) { + return code; + } + } + return null; + } +} diff --git a/src/com/kavenegar/excepctions/ApiException.java b/src/com/kavenegar/excepctions/ApiException.java new file mode 100644 index 0000000..25db991 --- /dev/null +++ b/src/com/kavenegar/excepctions/ApiException.java @@ -0,0 +1,26 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.kavenegar.excepctions; + +import com.kavenegar.excepctions.*; +import com.kavenegar.enums.MetaData; + +/** + * + * @author mohsen + */ +public class ApiException extends BaseException { + + int code; + + public ApiException(String message, int code) { + super(message); + this.code = code; + } + + public MetaData getCode() { + return MetaData.valueOf(code); + } +} diff --git a/src/com/kavenegar/excepctions/BaseException.java b/src/com/kavenegar/excepctions/BaseException.java new file mode 100644 index 0000000..255de9a --- /dev/null +++ b/src/com/kavenegar/excepctions/BaseException.java @@ -0,0 +1,18 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.kavenegar.excepctions; + +import com.kavenegar.excepctions.*; + +/** + * + * @author mohsen + */ +public class BaseException extends RuntimeException { + + public BaseException(String message) { + super(message); + } +} diff --git a/src/com/kavenegar/excepctions/HttpException.java b/src/com/kavenegar/excepctions/HttpException.java new file mode 100644 index 0000000..e7693e5 --- /dev/null +++ b/src/com/kavenegar/excepctions/HttpException.java @@ -0,0 +1,25 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.kavenegar.excepctions; + +import com.kavenegar.excepctions.*; + +/** + * + * @author mohsen + */ +public class HttpException extends BaseException { + + private final int code; + + public HttpException(String message, int code) { + super(message); + this.code = code; + } + + public int getCode() { + return code; + } +} diff --git a/src/com/kavenegar/models/AccountConfigResult.java b/src/com/kavenegar/models/AccountConfigResult.java new file mode 100644 index 0000000..ff36e52 --- /dev/null +++ b/src/com/kavenegar/models/AccountConfigResult.java @@ -0,0 +1,60 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.kavenegar.models; + +import com.kavenegar.models.*; + +/** + * + * @author Kave + */ +public class AccountConfigResult { + + String apilogs; + String dailyreport; + String debugmode; + String defaultsender; + int mincreditalarm; + String resendfailed; + + public String getApilogs() { + return apilogs; + }public void setApilogs(String apilogs) { + this.apilogs=apilogs; + } + + public String getDailyReport() { + return dailyreport; + }public void setDailyReport(String dailyreport) { + this.dailyreport=dailyreport; + } + + public String getDebugMode() { + return debugmode; + }public void setDebugMode(String debugmode) { + this.debugmode=debugmode; + } + + public String getDefaultSender() { + return defaultsender; + }public void setDefaultSender(String defaultsender) { + this.defaultsender=defaultsender; + } + public int getMinCreditAlarm() { + return mincreditalarm; + }public void setMinCreditAlarm(int mincreditalarm) { + this.mincreditalarm=mincreditalarm; + } + + public String getResendFailed() { + return resendfailed; + }public void setResendFailed(String resendfailed) { + this.resendfailed=resendfailed; + } + + + + +} diff --git a/src/com/kavenegar/models/AccountInfoResult.java b/src/com/kavenegar/models/AccountInfoResult.java new file mode 100644 index 0000000..2fe6411 --- /dev/null +++ b/src/com/kavenegar/models/AccountInfoResult.java @@ -0,0 +1,43 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.kavenegar.models; + +import com.kavenegar.models.*; + +/** + * + * @author mohsen + */ +public class AccountInfoResult { + + long remaincredit; + long expiredate; + String type; + + public long getRemainCredit() { + return remaincredit; + } + public void setRemainCredit(long RemainCredit) { + this.remaincredit = RemainCredit; + } + public long getExpireDate() { + return expiredate; + } + + public String getType() { + return type; + } + + + + public void setExpireDate(long expiredate) { + this.expiredate = expiredate; + } + + public void setType(String type) { + this.type = type; + } + +} diff --git a/src/com/kavenegar/models/CountInboxResult.java b/src/com/kavenegar/models/CountInboxResult.java new file mode 100644 index 0000000..87f622e --- /dev/null +++ b/src/com/kavenegar/models/CountInboxResult.java @@ -0,0 +1,38 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.kavenegar.models; + +import com.kavenegar.models.*; + +/** + * + * @author mohsen + */ +public class CountInboxResult { + long startdate; + long enddate; + long sumcount; + + public long getStartDate() { + return startdate; + } + public void setStartDate(long startdate) { + this.startdate = startdate; + } + + public long getEndDate() { + return enddate; + } + public void setEndDate(long enddate) { + this.enddate = enddate; + } + + public long getSumCount() { + return sumcount; + } + public void setSumCount(long sumcount) { + this.sumcount = sumcount; + } +} \ No newline at end of file diff --git a/src/com/kavenegar/models/CountOutboxResult.java b/src/com/kavenegar/models/CountOutboxResult.java new file mode 100644 index 0000000..b0cbf1c --- /dev/null +++ b/src/com/kavenegar/models/CountOutboxResult.java @@ -0,0 +1,29 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.kavenegar.models; + +import com.kavenegar.models.*; + +/** + * + * @author mohsen + */ +public class CountOutboxResult extends CountInboxResult{ + long sumpart; + long cost; + + public long getSumPart() { + return sumpart; + } + public void setSumPart(long sumpart) { + this.sumpart = sumpart; + } + public long getCost() { + return cost; + } + public void setCost(long cost) { + this.cost = cost; + } +} \ No newline at end of file diff --git a/src/com/kavenegar/models/CountPostalCodeResult.java b/src/com/kavenegar/models/CountPostalCodeResult.java new file mode 100644 index 0000000..b3ff4e8 --- /dev/null +++ b/src/com/kavenegar/models/CountPostalCodeResult.java @@ -0,0 +1,30 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.kavenegar.models; + +import com.kavenegar.models.*; + +/** + * + * @author mohsen + */ +public class CountPostalCodeResult{ + String section; + long value; + + public String getSection() { + return section; + } + public void setSection(String section) { + this.section = section; + } + public void setValue(long value) { + this.value = value; + } + public long getValue() { + return value; + } + +} \ No newline at end of file diff --git a/src/com/kavenegar/models/ReciveResult.java b/src/com/kavenegar/models/ReciveResult.java new file mode 100644 index 0000000..1881642 --- /dev/null +++ b/src/com/kavenegar/models/ReciveResult.java @@ -0,0 +1,59 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.kavenegar.models; + +import com.kavenegar.models.*; + +/** + * + * @author mohsen + */ +public class ReciveResult { + long messageid; + String message; + String sender; + String receptor; + long date; + + + + public void setMessageId(long messageid) { + this.messageid = messageid; + } + public long getMessageId() { + return messageid; + } + + public void setMessage(String message) { + this.message = message; + } + public String getMessage() { + return message; + } + + public void setSender(String sender) { + this.sender = sender; + } + public String getSender() { + return sender; + } + + public void setDate(long date) { + this.date = date; + } + public long getDate() { + return date; + } + + public void setReceptor(String receptor) { + this.receptor = receptor; + } + public String getReceptor() { + return receptor; + } + + + +} diff --git a/src/com/kavenegar/models/SendResult.java b/src/com/kavenegar/models/SendResult.java new file mode 100644 index 0000000..39b93e9 --- /dev/null +++ b/src/com/kavenegar/models/SendResult.java @@ -0,0 +1,80 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.kavenegar.models; + +import com.kavenegar.models.*; + +/** + * + * @author mohsen + */ +public class SendResult { + + long messageid; + String message; + int status; + String statustext; + String sender; + String receptor; + long date; + int cost; + + public long getMessageId() { + return messageid; + } + public void setMessageId(long messageid) { + this.messageid = messageid; + } + + public String getMessage() { + return message; + } + public void setMessage(String message) { + this.message = message; + } + + public int getStatus() { + return status; + } + public void setStatus(int status) { + this.status = status; + } + + public String getStatusText() { + return statustext; + } + public void setStatusText(String statustext) { + this.statustext = statustext; + } + + public String getSender() { + return sender; + } + public void setSender(String sender) { + this.sender = sender; + } + + public String getReceptor() { + return receptor; + } + public void setReceptor(String receptor) { + this.receptor = receptor; + } + + public long getDate() { + return date; + } + public void setDate(long date) { + this.date = date; + } + + public int getCost() { + return cost; + } + public void setCost(int cost) { + this.cost = cost; + } + +} \ No newline at end of file diff --git a/src/com/kavenegar/models/StatusLocalMessageIdResult.java b/src/com/kavenegar/models/StatusLocalMessageIdResult.java new file mode 100644 index 0000000..898206c --- /dev/null +++ b/src/com/kavenegar/models/StatusLocalMessageIdResult.java @@ -0,0 +1,23 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.kavenegar.models; + +import com.kavenegar.models.*; + +/** + * + * @author mohsen + */ +public class StatusLocalMessageIdResult extends StatusResult { + long localid; + public long getlocalId() { + return localid; + } + + public void setlocalId(long localid) { + this.localid = localid; + } + +} diff --git a/src/com/kavenegar/models/StatusResult.java b/src/com/kavenegar/models/StatusResult.java new file mode 100644 index 0000000..3d06b0f --- /dev/null +++ b/src/com/kavenegar/models/StatusResult.java @@ -0,0 +1,44 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.kavenegar.models; + +import com.kavenegar.models.*; +import com.kavenegar.enums.MessageStatus; + +/** + * + * @author mohsen + */ +public class StatusResult { + int messageid; + MessageStatus status; + String statustext; + + public int getMessageId() { + return messageid; + } + + public void setMessageId(int messageid) { + this.messageid = messageid; + } + + public MessageStatus getStatus() { + return status; + } + + public void setStatus(MessageStatus status) { + this.status = status; + } + + public String getStatusText() { + return statustext; + } + + public void setStatusText(String statustext) { + this.statustext = statustext; + } + + +} diff --git a/src/com/kavenegar/utils/ApiHelper.java b/src/com/kavenegar/utils/ApiHelper.java new file mode 100644 index 0000000..699ae99 --- /dev/null +++ b/src/com/kavenegar/utils/ApiHelper.java @@ -0,0 +1,73 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.kavenegar.utils; + +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import java.io.InputStream; +import java.util.ArrayList; +import java.util.List; +import org.apache.commons.io.IOUtils; +import org.apache.http.HttpEntity; +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.client.entity.UrlEncodedFormEntity; +import org.apache.http.message.BasicNameValuePair; + +import com.kavenegar.utils.*; + + +public class ApiHelper { + /* + * In Method Stream e barghashi az response ra khande va be json tabdil mikonad + */ + public static JsonObject getResult(HttpResponse response) { + HttpEntity entity = response.getEntity(); + InputStream stream = null; + + try { + stream = entity.getContent(); + Gson gson = new Gson(); + String result = IOUtils.toString(stream, "UTF-8"); + JsonObject json = (JsonObject) gson.fromJson(result, JsonElement.class); + return json; + } catch (Exception ex) { + ex.printStackTrace(); + return null; + } finally { + IOUtils.closeQuietly(stream); + } + } + /* + * In Method Baraye Rahat add Karadane parameter dar HttpPost mibashad + */ + public static UrlEncodedFormEntity createParams(Object... params) { + try { + List formparams = new ArrayList(); + for (int i = 0; i < params.length; i += 2) { + String key = params[i].toString(); + Object value = params[i + 1]; + if (value == null) { + continue; + } + formparams.add(new BasicNameValuePair(key, value.toString())); + } + UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8"); + return entity; + } catch (Exception ex) { + ex.printStackTrace(); + return null; + } + } + /* + * In Method code barghasti az json ra be Enum ( ErrorCode ) tabdil mikonad + */ + public static JsonObject getJsonResult(JsonObject json) { + JsonObject result = (JsonObject) json.get("return"); + return result; + } + +} diff --git a/src/com/kavenegar/utils/DateHelper.java b/src/com/kavenegar/utils/DateHelper.java new file mode 100644 index 0000000..d7382d5 --- /dev/null +++ b/src/com/kavenegar/utils/DateHelper.java @@ -0,0 +1,21 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.kavenegar.utils; + +import com.kavenegar.utils.*; + +/** + * + * @author Mohsen + */ +public class DateHelper { + +// public static long getUnixTime() { +// DateTime dt = new DateTime(); +// dt.plusHours(3); +// dt.plusMinutes(30); +// return dt.getMillis()/1000; +// } +} diff --git a/src/com/kavenegar/utils/EncoderUtil.java b/src/com/kavenegar/utils/EncoderUtil.java new file mode 100644 index 0000000..082d0c9 --- /dev/null +++ b/src/com/kavenegar/utils/EncoderUtil.java @@ -0,0 +1,599 @@ +package com.kavenegar.utils; + +import com.kavenegar.utils.*; +import java.nio.ByteBuffer; +import java.nio.charset.Charset; +import java.util.BitSet; +import java.util.Locale; + +/** + * Stolen from Mime4j project. + */ + +/** + * Static methods for encoding header field values. This includes encoded-words + * as defined in RFC 2047 or + * display-names of an e-mail address, for example. + * + */ +public class EncoderUtil { + public static final Charset US_ASCII = Charset.forName("US-ASCII"); + // This array is a lookup table that translates 6-bit positive integer index + // values into their "Base64 Alphabet" equivalents as specified in Table 1 + // of RFC 2045. + // ANDROID: THIS TABLE IS COPIED FROM BASE64OUTPUTSTREAM + static final byte[] BASE64_TABLE = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', + 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', + 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', + 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' }; + + // Byte used to pad output. + private static final byte BASE64_PAD = '='; + + private static final BitSet Q_REGULAR_CHARS = initChars("=_?"); + + private static final BitSet Q_RESTRICTED_CHARS = initChars("=_?\"#$%&'(),.:;<>@[\\]^`{|}~"); + + private static final int MAX_USED_CHARACTERS = 50; + + private static final String ENC_WORD_PREFIX = "=?"; + private static final String ENC_WORD_SUFFIX = "?="; + + private static final int ENCODED_WORD_MAX_LENGTH = 75; // RFC 2047 + + private static final BitSet TOKEN_CHARS = initChars("()<>@,;:\\\"/[]?="); + + private static final BitSet ATEXT_CHARS = initChars("()<>@.,;:\\\"[]"); + + private static BitSet initChars(String specials) { + BitSet bs = new BitSet(128); + for (char ch = 33; ch < 127; ch++) { + if (specials.indexOf(ch) == -1) { + bs.set(ch); + } + } + return bs; + } + + /** + * Selects one of the two encodings specified in RFC 2047. + */ + public enum Encoding { + /** The B encoding (identical to base64 defined in RFC 2045). */ + B, + /** The Q encoding (similar to quoted-printable defined in RFC 2045). */ + Q + } + + /** + * Indicates the intended usage of an encoded word. + */ + public enum Usage { + /** + * Encoded word is used to replace a 'text' token in any Subject or Comments + * header field. + */ + TEXT_TOKEN, + /** + * Encoded word is used to replace a 'word' entity within a 'phrase', for + * example, one that precedes an address in a From, To, or Cc header. + */ + WORD_ENTITY + } + + private EncoderUtil() { + } + + /** + * Encodes the display-name portion of an address. See RFC 5322 section 3.4 and + * RFC 2047 section 5.3. + * The specified string should not be folded. + * + * @param displayName + * display-name to encode. + * @return encoded display-name. + */ + public static String encodeAddressDisplayName(String displayName) { + // display-name = phrase + // phrase = 1*( encoded-word / word ) + // word = atom / quoted-string + // atom = [CFWS] 1*atext [CFWS] + // CFWS = comment or folding white space + + if (isAtomPhrase(displayName)) { + return displayName; + } else if (hasToBeEncoded(displayName, 0)) { + return encodeEncodedWord(displayName, Usage.WORD_ENTITY); + } else { + return quote(displayName); + } + } + + /** + * Encodes the local part of an address specification as described in RFC 5322 + * section 3.4.1. Leading and trailing CFWS should have been removed before + * calling this method. The specified string should not contain any illegal + * (control or non-ASCII) characters. + * + * @param localPart + * the local part to encode + * @return the encoded local part. + */ + public static String encodeAddressLocalPart(String localPart) { + // local-part = dot-atom / quoted-string + // dot-atom = [CFWS] dot-atom-text [CFWS] + // CFWS = comment or folding white space + + if (isDotAtomText(localPart)) { + return localPart; + } else { + return quote(localPart); + } + } + + /** + * Encodes the specified strings into a header parameter as described in RFC + * 2045 section 5.1 and RFC 2183 section 2. The specified strings should not + * contain any illegal (control or non-ASCII) characters. + * + * @param name + * parameter name. + * @param value + * parameter value. + * @return encoded result. + */ + public static String encodeHeaderParameter(String name, String value) { + name = name.toLowerCase(Locale.US); + + // value := token / quoted-string + if (isToken(value)) { + return name + "=" + value; + } else { + return name + "=" + quote(value); + } + } + + /** + * Shortcut method that encodes the specified text into an encoded-word if the + * text has to be encoded. + * + * @param text + * text to encode. + * @param usage + * whether the encoded-word is to be used to replace a text token or + * a word entity (see RFC 822). + * @param usedCharacters + * number of characters already used up ( + * 0 <= usedCharacters <= 50). + * @return the specified text if encoding is not necessary or an encoded word + * or a sequence of encoded words otherwise. + */ + public static String encodeIfNecessary(String text, Usage usage, int usedCharacters) { + if (hasToBeEncoded(text, usedCharacters)) + return encodeEncodedWord(text, usage, usedCharacters); + else + return text; + } + + /** + * Determines if the specified string has to encoded into an encoded-word. + * Returns true if the text contains characters that don't fall + * into the printable ASCII character set or if the text contains a 'word' + * (sequence of non-whitespace characters) longer than 77 characters + * (including characters already used up in the line). + * + * @param text + * text to analyze. + * @param usedCharacters + * number of characters already used up ( + * 0 <= usedCharacters <= 50). + * @return true if the specified text has to be encoded into an + * encoded-word, false otherwise. + */ + public static boolean hasToBeEncoded(String text, int usedCharacters) { + if (text == null) + throw new IllegalArgumentException(); + if (usedCharacters < 0 || usedCharacters > MAX_USED_CHARACTERS) + throw new IllegalArgumentException(); + + int nonWhiteSpaceCount = usedCharacters; + + for (int idx = 0; idx < text.length(); idx++) { + char ch = text.charAt(idx); + if (ch == '\t' || ch == ' ') { + nonWhiteSpaceCount = 0; + } else { + nonWhiteSpaceCount++; + if (nonWhiteSpaceCount > 77) { + // Line cannot be folded into multiple lines with no more + // than 78 characters each. Encoding as encoded-words makes + // that possible. One character has to be reserved for + // folding white space; that leaves 77 characters. + return true; + } + + if (ch < 32 || ch >= 127) { + // non-printable ascii character has to be encoded + return true; + } + } + } + + return false; + } + + /** + * Encodes the specified text into an encoded word or a sequence of encoded + * words separated by space. The text is separated into a sequence of encoded + * words if it does not fit in a single one. + *

+ * The charset to encode the specified text into a byte array and the encoding + * to use for the encoded-word are detected automatically. + *

+ * This method assumes that zero characters have already been used up in the + * current line. + * + * @param text + * text to encode. + * @param usage + * whether the encoded-word is to be used to replace a text token or + * a word entity (see RFC 822). + * @return the encoded word (or sequence of encoded words if the given text + * does not fit in a single encoded word). + * @see #hasToBeEncoded(String, int) + */ + public static String encodeEncodedWord(String text, Usage usage) { + return encodeEncodedWord(text, usage, 0, null, null); + } + + /** + * Encodes the specified text into an encoded word or a sequence of encoded + * words separated by space. The text is separated into a sequence of encoded + * words if it does not fit in a single one. + *

+ * The charset to encode the specified text into a byte array and the encoding + * to use for the encoded-word are detected automatically. + * + * @param text + * text to encode. + * @param usage + * whether the encoded-word is to be used to replace a text token or + * a word entity (see RFC 822). + * @param usedCharacters + * number of characters already used up ( + * 0 <= usedCharacters <= 50). + * @return the encoded word (or sequence of encoded words if the given text + * does not fit in a single encoded word). + * @see #hasToBeEncoded(String, int) + */ + public static String encodeEncodedWord(String text, Usage usage, int usedCharacters) { + return encodeEncodedWord(text, usage, usedCharacters, null, null); + } + + /** + * Encodes the specified text into an encoded word or a sequence of encoded + * words separated by space. The text is separated into a sequence of encoded + * words if it does not fit in a single one. + * + * @param text + * text to encode. + * @param usage + * whether the encoded-word is to be used to replace a text token or + * a word entity (see RFC 822). + * @param usedCharacters + * number of characters already used up ( + * 0 <= usedCharacters <= 50). + * @param charset + * the Java charset that should be used to encode the specified + * string into a byte array. A suitable charset is detected + * automatically if this parameter is null. + * @param encoding + * the encoding to use for the encoded-word (either B or Q). A + * suitable encoding is automatically chosen if this parameter is + * null. + * @return the encoded word (or sequence of encoded words if the given text + * does not fit in a single encoded word). + * @see #hasToBeEncoded(String, int) + */ + public static String encodeEncodedWord(String text, Usage usage, int usedCharacters, + Charset charset, Encoding encoding) { + if (text == null) + throw new IllegalArgumentException(); + if (usedCharacters < 0 || usedCharacters > MAX_USED_CHARACTERS) + throw new IllegalArgumentException(); + + if (charset == null) + charset = determineCharset(text); + + String mimeCharset = charset.name(); // no canonical names needed + if (mimeCharset == null) { + // cannot happen if charset was originally null + throw new IllegalArgumentException("Unsupported charset"); + } + + byte[] bytes = encode(text, charset); + + if (encoding == null) + encoding = determineEncoding(bytes, usage); + + if (encoding == Encoding.B) { + String prefix = ENC_WORD_PREFIX + mimeCharset + "?B?"; + return encodeB(prefix, text, usedCharacters, charset, bytes); + } else { + String prefix = ENC_WORD_PREFIX + mimeCharset + "?Q?"; + return encodeQ(prefix, text, usage, usedCharacters, charset, bytes); + } + } + + /** + * Encodes the specified byte array using the B encoding defined in RFC 2047. + * + * @param bytes + * byte array to encode. + * @return encoded string. + */ + public static String encodeB(byte[] bytes) { + StringBuilder sb = new StringBuilder(); + + int idx = 0; + final int end = bytes.length; + for (; idx < end - 2; idx += 3) { + int data = (bytes[idx] & 0xff) << 16 | (bytes[idx + 1] & 0xff) << 8 | bytes[idx + 2] & 0xff; + sb.append((char) BASE64_TABLE[data >> 18 & 0x3f]); + sb.append((char) BASE64_TABLE[data >> 12 & 0x3f]); + sb.append((char) BASE64_TABLE[data >> 6 & 0x3f]); + sb.append((char) BASE64_TABLE[data & 0x3f]); + } + + if (idx == end - 2) { + int data = (bytes[idx] & 0xff) << 16 | (bytes[idx + 1] & 0xff) << 8; + sb.append((char) BASE64_TABLE[data >> 18 & 0x3f]); + sb.append((char) BASE64_TABLE[data >> 12 & 0x3f]); + sb.append((char) BASE64_TABLE[data >> 6 & 0x3f]); + sb.append((char) BASE64_PAD); + + } else if (idx == end - 1) { + int data = (bytes[idx] & 0xff) << 16; + sb.append((char) BASE64_TABLE[data >> 18 & 0x3f]); + sb.append((char) BASE64_TABLE[data >> 12 & 0x3f]); + sb.append((char) BASE64_PAD); + sb.append((char) BASE64_PAD); + } + + return sb.toString(); + } + + /** + * Encodes the specified byte array using the Q encoding defined in RFC 2047. + * + * @param bytes + * byte array to encode. + * @param usage + * whether the encoded-word is to be used to replace a text token or + * a word entity (see RFC 822). + * @return encoded string. + */ + public static String encodeQ(byte[] bytes, Usage usage) { + BitSet qChars = usage == Usage.TEXT_TOKEN ? Q_REGULAR_CHARS : Q_RESTRICTED_CHARS; + + StringBuilder sb = new StringBuilder(); + + final int end = bytes.length; + for (int idx = 0; idx < end; idx++) { + int v = bytes[idx] & 0xff; + if (v == 32) { + sb.append('_'); + } else if (!qChars.get(v)) { + sb.append('='); + sb.append(hexDigit(v >>> 4)); + sb.append(hexDigit(v & 0xf)); + } else { + sb.append((char) v); + } + } + + return sb.toString(); + } + + /** + * Tests whether the specified string is a token as defined in RFC 2045 + * section 5.1. + * + * @param str + * string to test. + * @return true if the specified string is a RFC 2045 token, + * false otherwise. + */ + public static boolean isToken(String str) { + // token := 1* + // tspecials := "(" / ")" / "<" / ">" / "@" / "," / ";" / ":" / "\" / + // <"> / "/" / "[" / "]" / "?" / "=" + // CTL := 0.- 31., 127. + + final int length = str.length(); + if (length == 0) + return false; + + for (int idx = 0; idx < length; idx++) { + char ch = str.charAt(idx); + if (!TOKEN_CHARS.get(ch)) + return false; + } + + return true; + } + + private static boolean isAtomPhrase(String str) { + // atom = [CFWS] 1*atext [CFWS] + + boolean containsAText = false; + + final int length = str.length(); + for (int idx = 0; idx < length; idx++) { + char ch = str.charAt(idx); + if (ATEXT_CHARS.get(ch)) { + containsAText = true; + } else if (Character.isWhitespace(ch)) { + return false; + } + } + + return containsAText; + } + + // RFC 5322 section 3.2.3 + private static boolean isDotAtomText(String str) { + // dot-atom-text = 1*atext *("." 1*atext) + // atext = ALPHA / DIGIT / "!" / "#" / "$" / "%" / "&" / "'" / "*" / + // "+" / "-" / "/" / "=" / "?" / "^" / "_" / "`" / "{" / "|" / "}" / "~" + + char prev = '.'; + + final int length = str.length(); + if (length == 0) + return false; + + for (int idx = 0; idx < length; idx++) { + char ch = str.charAt(idx); + + if (ch == '.') { + if (prev == '.' || idx == length - 1) + return false; + } else { + if (!ATEXT_CHARS.get(ch)) + return false; + } + + prev = ch; + } + + return true; + } + + // RFC 5322 section 3.2.4 + private static String quote(String str) { + // quoted-string = [CFWS] DQUOTE *([FWS] qcontent) [FWS] DQUOTE [CFWS] + // qcontent = qtext / quoted-pair + // qtext = %d33 / %d35-91 / %d93-126 + // quoted-pair = ("\" (VCHAR / WSP)) + // VCHAR = %x21-7E + // DQUOTE = %x22 + + String escaped = str.replaceAll("[\\\\\"]", "\\\\$0"); + return "\"" + escaped + "\""; + } + + private static String encodeB(String prefix, String text, int usedCharacters, Charset charset, + byte[] bytes) { + int encodedLength = bEncodedLength(bytes); + + int totalLength = prefix.length() + encodedLength + ENC_WORD_SUFFIX.length(); + if (totalLength <= ENCODED_WORD_MAX_LENGTH - usedCharacters) { + return prefix + encodeB(bytes) + ENC_WORD_SUFFIX; + } else { + int splitOffset = text.offsetByCodePoints(text.length() / 2, -1); + + String part1 = text.substring(0, splitOffset); + byte[] bytes1 = encode(part1, charset); + String word1 = encodeB(prefix, part1, usedCharacters, charset, bytes1); + + String part2 = text.substring(splitOffset); + byte[] bytes2 = encode(part2, charset); + String word2 = encodeB(prefix, part2, 0, charset, bytes2); + + return word1 + " " + word2; + } + } + + private static int bEncodedLength(byte[] bytes) { + return (bytes.length + 2) / 3 * 4; + } + + private static String encodeQ(String prefix, String text, Usage usage, int usedCharacters, + Charset charset, byte[] bytes) { + int encodedLength = qEncodedLength(bytes, usage); + + int totalLength = prefix.length() + encodedLength + ENC_WORD_SUFFIX.length(); + if (totalLength <= ENCODED_WORD_MAX_LENGTH - usedCharacters) { + return prefix + encodeQ(bytes, usage) + ENC_WORD_SUFFIX; + } else { + int splitOffset = text.offsetByCodePoints(text.length() / 2, -1); + + String part1 = text.substring(0, splitOffset); + byte[] bytes1 = encode(part1, charset); + String word1 = encodeQ(prefix, part1, usage, usedCharacters, charset, bytes1); + + String part2 = text.substring(splitOffset); + byte[] bytes2 = encode(part2, charset); + String word2 = encodeQ(prefix, part2, usage, 0, charset, bytes2); + + return word1 + " " + word2; + } + } + + private static int qEncodedLength(byte[] bytes, Usage usage) { + BitSet qChars = usage == Usage.TEXT_TOKEN ? Q_REGULAR_CHARS : Q_RESTRICTED_CHARS; + + int count = 0; + + for (int idx = 0; idx < bytes.length; idx++) { + int v = bytes[idx] & 0xff; + if (v == 32) { + count++; + } else if (!qChars.get(v)) { + count += 3; + } else { + count++; + } + } + + return count; + } + + private static byte[] encode(String text, Charset charset) { + ByteBuffer buffer = charset.encode(text); + byte[] bytes = new byte[buffer.limit()]; + buffer.get(bytes); + return bytes; + } + + private static Charset determineCharset(String text) { + // it is an important property of iso-8859-1 that it directly maps + // unicode code points 0000 to 00ff to byte values 00 to ff. + boolean ascii = true; + final int len = text.length(); + for (int index = 0; index < len; index++) { + char ch = text.charAt(index); + if (ch > 0xff) { + return Charset.forName("UTF-8"); + } + if (ch > 0x7f) { + ascii = false; + } + } + return ascii ? Charset.forName("US-ASCII") : Charset.forName("ISO-8859-1"); + } + + private static Encoding determineEncoding(byte[] bytes, Usage usage) { + if (bytes.length == 0) + return Encoding.Q; + + BitSet qChars = usage == Usage.TEXT_TOKEN ? Q_REGULAR_CHARS : Q_RESTRICTED_CHARS; + + int qEncoded = 0; + for (int i = 0; i < bytes.length; i++) { + int v = bytes[i] & 0xff; + if (v != 32 && !qChars.get(v)) { + qEncoded++; + } + } + + int percentage = qEncoded * 100 / bytes.length; + return percentage > 30 ? Encoding.B : Encoding.Q; + } + + private static char hexDigit(int i) { + return i < 10 ? (char) (i + '0') : (char) (i - 10 + 'A'); + } +} diff --git a/src/com/kavenegar/utils/StringUtils.java b/src/com/kavenegar/utils/StringUtils.java new file mode 100644 index 0000000..5d83a34 --- /dev/null +++ b/src/com/kavenegar/utils/StringUtils.java @@ -0,0 +1,31 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.kavenegar.utils; + +import com.kavenegar.utils.*; + +/** + * + * @author Mohsen + */ +public class StringUtils { + public static String Join(String delimeter,Object[] items) + { + if(items==null) + return ""; + String result = ""; + for(Object obj : items) + { + result+=obj + delimeter; + } + if (result.length() > 0 && result.charAt(result.length()-1)==',') { + result = result.substring(0, result.length()-1); + } + return result; + } + + +} + diff --git a/src/com/kavenegar/utils/Validator.java b/src/com/kavenegar/utils/Validator.java new file mode 100644 index 0000000..fb55d56 --- /dev/null +++ b/src/com/kavenegar/utils/Validator.java @@ -0,0 +1,17 @@ +/* + * To change this template, choose Tools | Templates + * and open the template in the editor. + */ +package com.kavenegar.utils; + +import com.kavenegar.utils.*; + +/** + * + * @author mohsen + */ +public class Validator { + public static void isNumber(){ + + } +}