com.hkm.root.Tasks.upload_data.java Source code

Java tutorial

Introduction

Here is the source code for com.hkm.root.Tasks.upload_data.java

Source

/*
 * Terms and conditions
 *
 * Preamble: This Agreement, signed on Jul 2, 2014 [hereinafter: Effective Date] governs the relationship between HKm, a private person, (hereinafter: Licensee) and HKM, a private person whose principal place of business is 945 Battery St, San Francisco, CA 94111, CA, United States (Hereinafter: Licensor). This Agreement sets the terms, rights, restrictions and obligations on using [OneCall] (hereinafter: The Software) created and owned by Licensor, as detailed herein
 * License Grant: Licensor hereby grants Licensee a Sublicensable, Assignable, Commercial with terms, Including the rights to create but not distribute derivative works, Non-exclusive license, all with accordance with the terms set forth and other legal restrictions set forth in 3rd party software used while running Software.
 * Limited: Licensee may use Software for the purpose of:
 * Running Software on Licensees Website[s] and Server[s];
 * Allowing 3rd Parties to run Software on Licensees Website[s] and Server[s];
 * Publishing Softwares output to Licensee and 3rd Parties;
 * Distribute verbatim copies of Softwares output (including compiled binaries);
 * Modify Software to suit Licensees needs and specifications.
 * Binary Restricted: Licensee may sublicense Software as a part of a larger work containing more than Software, distributed solely in Object or Binary form under a personal, non-sublicensable, limited license. Such redistribution shall be limited to unlimited codebases.
 * Assignable: Licensee may assign his rights and duties under this license as long as the party who Licensee assigns the license accepts the license in full, and provides Licensor with a written confirmation of Assignment
 * Commercial use allowed with restrictions: by agreements and terms granted by the author.
 * Including the Right to Create Derivative Works: Licensee may create derivative works based on Software, including amending Softwares source code, modifying it, integrating it into a larger work or removing portions of Software, as long as no distribution of the derivative works is made
 * With Attribution Requirements:
 * Licensor shall retain full title in Trademarks, and any trademarks and tradenames contained, including Software's names, logos, and all other intellectual property. Unless specifically stated in this license, no license shall be made to use, associate or affiliate Software with Licensee in any manner. Licensee may not use Softwares name, tradename, trademarks or logo when distributing derivative works of software to 3rd parties.
 * If Software is covered by Patents, Licensor grants Licensee a non-exclusive, worldwide, royalty-free patent license under Licensor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of Software.
 * Licensee hereby acknowledges that Software contains Licensors trade secrets and other proprietary information that has not been disclosed to the public domain. Licensee shall not disclose, reveal, make available or convey to any 3rd party portions of Software, including Softwares know-how, means of operations, algorithms, and any other proprietary information (hereinafter: Confidential Information). Licensees obligations shall remain in effect as long as Confidential Information does not (i) enter into the public domain by any voluntary act made by Licensor; or (ii) Licensee is ordered by a definite court order, or any other legal authority, to disclose Confidential Information; or (iii) Confidential Information was independently developed by a 3rd Party who was not exposed to the Software. Licensee shall require any 3rd party who sublicenses Software to sign a non-disclosure agreement no less restrictive than this license.
 * Term & Termination: The Term of this license shall be until terminated. Licensor may terminate this Agreement, including Licensees license in the case where Licensee :
 * became insolvent or otherwise entered into any liquidation process; or
 * exported The Software to any jurisdiction where licensor may not enforce his rights under this agreements in; or
 * Licensee was in breach of any of this license's terms and conditions and such breach was not cured, immediately upon notification; or
 * Licensee in breach of any of the terms of clause 2 to this license; or
 * Licensee otherwise entered into any arrangement which caused Licensor to be unable to enforce his rights under this License.
 * Payment: In consideration of the License granted under clause 2, Licensee shall pay Licensor a fee, via Credit-Card, PayPal or any other mean which Licensor may deem adequate. Failure to perform payment shall construe as material breach of this Agreement.
 * Upgrades, Updates and Fixes: Licensor may provide Licensee, from time to time, with Upgrades, Updates or Fixes, as detailed herein and according to his sole discretion. Licensee hereby warrants to keep The Software up-to-date and install all relevant updates and fixes, and may, at his sole discretion, purchase upgrades, according to the rates set by Licensor. Licensor shall provide any update or Fix free of charge; however, nothing in this Agreement shall require Licensor to provide Updates or Fixes.
 * Upgrades: for the purpose of this license, an Upgrade shall be a material amendment in The Software, which contains new features and or major performance improvements and shall be marked as a new version number. For example, should Licensee purchase The Software under version 1.X.X, an upgrade shall commence under number 2.0.0.
 * Updates: for the purpose of this license, an update shall be a minor amendment in The Software, which may contain new features or minor improvements and shall be marked as a new sub-version number. For example, should Licensee purchase The Software under version 1.1.X, an upgrade shall commence under number 1.2.0.
 * Fix: for the purpose of this license, a fix shall be a minor amendment in The Software, intended to remove bugs or alter minor features which impair the The Software's functionality. A fix shall be marked as a new sub-sub-version number. For example, should Licensee purchase Software under version 1.1.1, an upgrade shall commence under number 1.1.2.
 * Support: Software is provided under an AS-IS basis and without any support, updates or maintenance. Nothing in this Agreement shall require Licensor to provide Licensee with support or fixes to any bug, failure, mis-performance or other defect in The Software.
 * Bug Notification: Licensee may provide Licensor of details regarding any bug, defect or failure in The Software promptly and with no delay from such event; Licensee shall comply with Licensor's request for information regarding bugs, defects or failures and furnish him with information, screenshots and try to reproduce such bugs, defects or failures.
 * Feature Request: Licensee may request additional features in Software, provided, however, that (i) Licensee shall waive any claim or right in such feature should feature be developed by Licensor; (ii) Licensee shall be prohibited from developing the feature, or disclose such feature request, or feature, to any 3rd party directly competing with Licensor or any 3rd party which may be, following the development of such feature, in direct competition with Licensor; (iii) Licensee warrants that feature does not infringe any 3rd party patent, trademark, trade-secret or any other intellectual property right; and (iv) Licensee developed, envisioned or created the feature solely by himself.
 * Liability:  To the extent permitted under Law, The Software is provided under an AS-IS basis. Licensor shall never, and without any limit, be liable for any damage, cost, expense or any other payment incurred by Licensee as a result of Softwares actions, failure, bugs and/or any other interaction between The Software  and Licensees end-equipment, computers, other software or any 3rd party, end-equipment, computer or services.  Moreover, Licensor shall never be liable for any defect in source code written by Licensee when relying on The Software or using The Softwares source code.
 * Warranty:
 * Intellectual Property: Licensor hereby warrants that The Software does not violate or infringe any 3rd party claims in regards to intellectual property, patents and/or trademarks and that to the best of its knowledge no legal action has been taken against it for any infringement or violation of any 3rd party intellectual property rights.
 * No-Warranty: The Software is provided without any warranty; Licensor hereby disclaims any warranty that The Software shall be error free, without defects or code which may cause damage to Licensees computers or to Licensee, and that Software shall be functional. Licensee shall be solely liable to any damage, defect or loss incurred as a result of operating software and undertake the risks contained in running The Software on Licenses Server[s] and Website[s].
 * Prior Inspection: Licensee hereby states that he inspected The Software thoroughly and found it satisfactory and adequate to his needs, that it does not interfere with his regular operation and that it does meet the standards and scope of his computer systems and architecture. Licensee found that The Software interacts with his development, website and server environment and that it does not infringe any of End User License Agreement of any software Licensee may use in performing his services. Licensee hereby waives any claims regarding The Software's incompatibility, performance, results and features, and warrants that he inspected the The Software.
 * No Refunds: Licensee warrants that he inspected The Software according to clause 7(c) and that it is adequate to his needs. Accordingly, as The Software is intangible goods, Licensee shall not be, ever, entitled to any refund, rebate, compensation or restitution for any reason whatsoever, even if The Software contains material flaws.
 * Indemnification: Licensee hereby warrants to hold Licensor harmless and indemnify Licensor for any lawsuit brought against it in regards to Licensees use of The Software in means that violate, breach or otherwise circumvent this license, Licensor's intellectual property rights or Licensor's title in The Software. Licensor shall promptly notify Licensee in case of such legal action and request Licensees consent prior to any settlement in relation to such lawsuit or claim.
 * Governing Law, Jurisdiction: Licensee hereby agrees not to initiate class-action lawsuits against Licensor in relation to this license and to compensate Licensor for any legal fees, cost or attorney fees should any claim brought by Licensee against Licensor be denied, in part or in full.
 */

package com.hkm.root.Tasks;

import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;

import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import com.hkm.Application.appWork;
import com.hkm.U.Tool;
import com.hkm.datamodel.PhotoViewData;
import com.hkm.datamodel.SketchMapData;
import com.hkm.datamodel.StandJsonResponse;
import com.squareup.okhttp.Headers;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.UnknownFormatFlagsException;
import java.util.concurrent.TimeUnit;

import static com.hkm.U.Constant.EndPoint.WP_BASE_MAP_ENDPOINT;
import static com.hkm.U.Constant.EndPoint.WP_DATA_ENDPOINT;
import static com.hkm.U.Constant.EndPoint.WP_SIGNATURES_ENDPOINT;
import static com.hkm.U.Constant.EndPoint.WP_WORK_PHOTO_ENDPOINT;
import static com.hkm.U.Content.current_job_task;

/**
 * Created by Hesk on 9/7/2014.
 * <p/>
 * return sample data, parse it on http://www.jsoneditoronline.org/
 * <p/>
 * {"address_tag"
 */
public class upload_data extends AsyncTask<Void, Void, String> {
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    public static final MediaType MEDIA_TYPE_MARKDOWN = MediaType.parse("text/x-markdown; charset=utf-8");
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
    private static final MediaType MEDIA_TYPE_JPG = MediaType.parse("image/jpeg");
    //todo developing this work now
    private static final String IMGUR_CLIENT_ID = "...";
    private static final JsonParser parser = new JsonParser();
    private static final ArrayList<Uri> files = new ArrayList<Uri>();
    public static String TAG = "upload_task_now";
    //private static Gson json;
    private final OkHttpClient client = new OkHttpClient();
    private final String STATUS = "status", RESULT = "result", SUCCESS = "success", FAILURE = "failure",
            MESSAGE = "message";
    private final StandJsonResponse.single_event success_pass_event = new StandJsonResponse.single_event() {
        @Override
        public void onsuccess(long time_stamp) {
            success_events_achieved++;
        }
    };
    private completecb cb;
    private appWork ac;
    private boolean check_maps = true, check_photos = true;
    private int job_id = -1, post_target = -1, success_events_achieved = 0;
    //  private String test_sample = "{\"result\":\"success\",\"code\":1,\"timestamp\":1405503045}";
    private StringBuilder sb = new StringBuilder();

    public upload_data(completecb cb, appWork ac) {
        this.cb = cb;
        this.ac = ac;
        /* final GsonBuilder gb = new GsonBuilder();
         gb.serializeNulls()
            .excludeFieldsWithoutExposeAnnotation()
            .serializeSpecialFloatingPointValues();
         json = gb.create();*/
    }

    @Override
    protected void onPreExecute() {
        Log.i("Async-Example", "onPreExecute Called");
        cb.pre();
    }

    @Override
    protected void onPostExecute(String result) {
        if (result.equalsIgnoreCase("done")) {
            cb.cbsuccess(result);
        } else {
            cb.cbfailure(result);
        }
    }

    @Override
    protected String doInBackground(Void... strings) {
        //todo continue to develop the rest to of the data checking
        String all_done = "";
        try {
            sb = new StringBuilder();
            if (!ac.isNetworkOnline())
                throw new Exception("no network");
            ArrayList<SketchMapData> dmap = current_job_task.getSketchMapList();
            ArrayList<PhotoViewData> hmap = current_job_task.getPhotoList();

            job_id = ac.getRefInt(appWork.TASK_ID);
            if (job_id == -1) {
                throw new Exception("Technical issue: job ID is not found");
            }
            final String t = ac.getRef(appWork.TASK_JSON + job_id);
            final String response = OCokHttpPostData(WP_DATA_ENDPOINT, t);

            if (response.equalsIgnoreCase("")) {
                throw new Exception(response);
            } else {
                success_events_achieved++;
                //final Type listType = new TypeToken<List<String>>() {}.getType();
                //List<String> v = json.fromJson(response, listType);
                final JsonObject jsob = parser.parse(response).getAsJsonObject();
                if (jsob.has(STATUS)) {
                    final String status = jsob.getAsJsonPrimitive(STATUS).getAsString();
                    final String message = jsob.getAsJsonPrimitive(MESSAGE).getAsString();
                    if (status.equalsIgnoreCase(FAILURE)) {
                        throw new Exception(message);
                    } else if (status.equalsIgnoreCase(SUCCESS)) {
                        if (jsob.has(RESULT)) {
                            post_target = jsob.getAsJsonPrimitive(RESULT).getAsInt();
                            /**
                             * IMAGES UPLOAD HERE SKETCHMAPS
                             */
                            files.clear();
                            if (dmap.size() > 0) {
                                for (SketchMapData d : dmap) {
                                    if (d.hasUri()) {
                                        files.add(d.get_draw_map_uri());
                                    }
                                }
                                OCokHttpUpload(files, WP_BASE_MAP_ENDPOINT, MEDIA_TYPE_PNG);
                            }
                            /**
                             * IMAGES UPLOAD HERE PHOTOS
                             */

                            files.clear();
                            if (hmap.size() > 0) {
                                for (PhotoViewData d : hmap) {
                                    files.add(d.uri);
                                }
                                OCokHttpUpload(files, WP_WORK_PHOTO_ENDPOINT, MEDIA_TYPE_JPG);
                            }

                            files.clear();
                            current_job_task.getLRSignatures(files);
                            current_job_task.getCSSignatures(files);
                            if (files.size() > 0) {
                                OCokHttpUpload(files, WP_SIGNATURES_ENDPOINT, MEDIA_TYPE_JPG);
                            }
                        } else
                            throw new Exception(
                                    "return success but the json format is not correct. Please check on the php source of the output method for this error.");
                    } else {
                        throw new Exception(message);
                    }
                }
            }

            all_done = "done";
        } catch (JsonIOException e) {
            all_done = e.getMessage();
        } catch (JsonSyntaxException e) {
            all_done = e.getMessage();
        } catch (JsonParseException e) {
            all_done = e.getMessage();
        } catch (UnknownError e) {
            all_done = e.getMessage();
        } catch (UnknownFormatFlagsException e) {
            all_done = e.getMessage();
        } catch (ClassCastException e) {
            all_done = e.getMessage();
        } catch (UnsupportedOperationException e) {
            all_done = e.getMessage();
        } catch (NullPointerException e) {
            all_done = e.getMessage();
        } catch (RuntimeException e) {
            all_done = e.getMessage();
        } catch (Exception e) {
            all_done = e.getMessage();
        }
        return all_done;
    }

    protected String OCokHttpPostData(final String url, final String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder().url(url).post(body).build();
        OkHttpClient use_client = client.clone();
        Response response = use_client.newCall(request).execute();
        if (response.isSuccessful()) {
            return response.body().string();
        } else
            throw new IOException("not success on HTTP request.");
    }

    public void OCokHttpUpload(ArrayList<Uri> img_list, final String endpoint, final MediaType typ)
            throws IOException, Exception {
        // Use the imgur image upload API as documented at https://api.imgur.com/endpoints/image
        MultipartBuilder mb = new MultipartBuilder();
        mb.type(MultipartBuilder.FORM);
        for (Uri i : img_list) {
            final File file_location = i.toString().startsWith("file:")
                    ? new File(i.toString().replace("file:///", ""))
                    : new File(Tool.getRealPathFromURI(ac, i));
            final RequestBody content_data = RequestBody.create(typ, file_location);
            final String disposition = String.format(Locale.getDefault(), "form-data; name=\"%s\"; filename=\"%s\"",
                    "target-" + post_target, file_location.getName());
            final String disposition_alt = String.format(Locale.getDefault(), "file; filename=\"%s\"",
                    file_location.getName());
            mb.addPart(Headers.of("Content-Disposition", disposition_alt, "Content-Transfer-Encoding", "binary"),
                    content_data);
        }

        RequestBody requestBody = mb.build();
        Request requestBuild = new Request.Builder().url(endpoint + "?pid=" + job_id + "&target=" + post_target)
                .post(requestBody).tag("post_image").build();
        execute_upload(requestBuild);
    }

    public void execute_upload(Request requestBuild) throws IOException, Exception {
        // executes generic request
        OkHttpClient use_client = client.clone();
        use_client.setWriteTimeout(10, TimeUnit.SECONDS);
        Response response = use_client.newCall(requestBuild).execute();
        if (!response.isSuccessful()) {
            throw new IOException("Unexpected code " + response);
        } else {
            if (!response.body().string().isEmpty()) {
                success_events_achieved++;
                // sb.append(response.body().string());
                System.out.println(response.body().string());
                // StandJsonResponse sp = new StandJsonResponse();
                // sp.fromString(response.body().string()).setSingleSuccessAction(success_pass_event).run();
            } else {
                throw new Exception("response body is empty");
            }
        }
    }
}