com.nextgis.maplib.util.NetworkUtil Java Examples

The following examples show how to use com.nextgis.maplib.util.NetworkUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CreateFromQMSLayerDialog.java    From android_maplibui with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void onPostExecute(HttpResponse response)
{
    super.onPostExecute(response);

    if (response.isOk()) {
        try {
            new JSONObject(response.getResponseBody());
            createLayer(response.getResponseBody());
        } catch (JSONException ignored) {
            Toast.makeText(mContext, R.string.qms_unavailable, Toast.LENGTH_SHORT).show();
        }

    } else {
        Toast.makeText(
                mContext, NetworkUtil.getError(mContext, response.getResponseCode()),
                Toast.LENGTH_SHORT).show();
    }

    mChecked.remove(mLayerId);

    if (mChecked.size() == 0)
        mGroupLayer.save();
}
 
Example #2
Source File: NGWVectorLayer.java    From android_maplib with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected HttpResponse sendFeatureAttachOnServer(JSONObject result, long featureId, AttachItem attach) throws JSONException, IOException {
    // add attachment to row
    JSONObject postJsonData = new JSONObject();
    JSONArray uploadMetaArray = result.getJSONArray("upload_meta");
    postJsonData.put("file_upload", uploadMetaArray.get(0));
    postJsonData.put("description", attach.getDescription());
    String postload = postJsonData.toString();
    if (Constants.DEBUG_MODE) {
        Log.d(Constants.TAG, "postload: " + postload);
    }

    // get account data
    AccountUtil.AccountData accountData = AccountUtil.getAccountData(mContext, mAccountName);

    // upload file
    String url = NGWUtil.getFeatureAttachmentUrl(accountData.url, mRemoteId, featureId);

    // update record in NGW
    return NetworkUtil.post(url, postload, accountData.login, accountData.password, false);
}
 
Example #3
Source File: NGWLookupTable.java    From android_maplib with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected void fillFromNGW(Map<String, String> dataMap, IProgressor progressor) throws IOException, NGException, JSONException {
    if (!mNet.isNetworkAvailable()) { //return tile from cache
        throw new NGException(getContext().getString(R.string.error_network_unavailable));
    }

    if(null != progressor){
        progressor.setMessage(getContext().getString(R.string.message_loading));
    }

    Log.d(Constants.TAG, "download layer " + getName());
    HttpResponse response =
            NetworkUtil.get(NGWUtil.getResourceUrl(mCacheUrl, mRemoteId), mCacheLogin,
                    mCachePassword, false);
    if (!response.isOk()) {
        throw new NGException(NetworkUtil.getError(mContext, response.getResponseCode()));
    }
    JSONObject geoJSONObject = new JSONObject(response.getResponseBody());
    JSONObject lookupTable = geoJSONObject.getJSONObject("lookup_table");
    JSONObject itemsObject = lookupTable.getJSONObject("items");
    for (Iterator<String> iter = itemsObject.keys(); iter.hasNext(); ) {
        String key = iter.next();
        String value = itemsObject.getString(key);
        dataMap.put(key, value);
    }
}
 
Example #4
Source File: LayerWithStyles.java    From android_maplib with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void fillExtent() {
    try {
        mExtent = new GeoEnvelope();
        String url = NGWUtil.getExtent(mConnection.getURL(), mRemoteId);
        HttpResponse response =
                NetworkUtil.get(url, mConnection.getLogin(), mConnection.getPassword(), false);
        if (!response.isOk())
            return;
        JSONObject extent =
                new JSONObject(response.getResponseBody()).getJSONObject(JSON_EXTENT_KEY);
        double x = Geo.wgs84ToMercatorSphereX(extent.getDouble(JSON_MAX_LON_KEY));
        double y = Geo.wgs84ToMercatorSphereY(extent.getDouble(JSON_MAX_LAT_KEY));
        mExtent.setMax(x, y);
        x = Geo.wgs84ToMercatorSphereX(extent.getDouble(JSON_MIN_LON_KEY));
        y = Geo.wgs84ToMercatorSphereY(extent.getDouble(JSON_MIN_LAT_KEY));
        mExtent.setMin(x, y);
    } catch (IOException | JSONException ignored) { }
}
 
Example #5
Source File: NGIDUtils.java    From android_maplibui with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected HttpResponse doInBackground(String... args) {
    String url = args[0];
    String method = args[1];
    String token = args[2];

    if (TextUtils.isEmpty(token)) {
        try {
            token = getToken(args);
            userCheck(token);
        } catch (IOError e) {
            return new HttpResponse(NetworkUtil.ERROR_CONNECT_FAILED);
        }
    }

    HttpResponse response = getResponse(url, method, token);
    if (!response.isOk()) {
        response = userCheck(token);
        if (!response.isOk())
            return new HttpResponse(NetworkUtil.ERROR_CONNECT_FAILED);
        else
            response = getResponse(url, method, token);
    }

    return response;
}
 
Example #6
Source File: TrackerService.java    From android_maplibui with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void post(String payload, Context context, List<String> ids) throws IOException {
        String url = String.format("%s/%s/packet", URL, getUid(context));
//        Log.d(Constants.TAG, "Post to " + url);
        HttpResponse response = NetworkUtil.post(url, payload, null, null, false);
//        Log.d(Constants.TAG, "Response is " + response.getResponseCode());
        if (!response.isOk())
            return;

        ContentValues cv = new ContentValues();
        cv.put(TrackLayer.FIELD_SENT, 1);
        String where = TrackLayer.FIELD_TIMESTAMP + " in (" + MapUtil.makePlaceholders(ids.size()) + ")";
        String[] timestamps = ids.toArray(new String[0]);
        try {
            context.getContentResolver().update(mContentUriTrackPoints, cv, where, timestamps);
        } catch (SQLiteException ignored) {
        }
    }
 
Example #7
Source File: CreateFromQMSLayerDialog.java    From android_maplibui with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected void onPostExecute(HttpResponse response) {
    super.onPostExecute(response);

    if (response.isOk()) {
        try {
            new JSONArray(response.getResponseBody());
            createList(response.getResponseBody());
        } catch (JSONException ignored) {
            Toast.makeText(mContext, R.string.qms_unavailable, Toast.LENGTH_SHORT).show();
            showRetry();
        }
    } else {
        Toast.makeText(
                mContext, NetworkUtil.getError(mContext, response.getResponseCode()),
                Toast.LENGTH_SHORT).show();
        showRetry();
    }
}
 
Example #8
Source File: TMSLayer.java    From android_maplib with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void fillFromZipInt(Uri uri, IProgressor progressor) throws IOException, NGException, RuntimeException {
    InputStream inputStream;
    String url = uri.toString();
    if (NetworkUtil.isValidUri(url))
        inputStream = new URL(url).openStream();
    else
        inputStream = mContext.getContentResolver().openInputStream(uri);

    if (inputStream == null)
        throw new NGException(mContext.getString(R.string.error_download_data));

    int streamSize = inputStream.available();
    if (null != progressor)
        progressor.setMax(streamSize);

    int increment = 0;
    byte[] buffer = new byte[Constants.IO_BUFFER_SIZE];

    ZipInputStream zis = new ZipInputStream(inputStream);
    ZipEntry ze;
    while ((ze = zis.getNextEntry()) != null) {
        FileUtil.unzipEntry(zis, ze, buffer, mPath);
        increment += ze.getCompressedSize();
        zis.closeEntry();
        if (null != progressor) {
            if(progressor.isCanceled())
                return;
            progressor.setValue(increment);
            progressor.setMessage(getContext().getString(R.string.processed) + " " + increment + " " + getContext().getString(R.string.of) + " " + streamSize);
        }
    }
}
 
Example #9
Source File: SettingsFragment.java    From android_gisapp with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected Boolean doInBackground(Void... voids) {
    try {
        String url = String.format("%s/%s/registered", URL, getUid(mPreference.getContext()));
        HttpResponse response = NetworkUtil.get(url, null, null, false);
        String body = response.getResponseBody();
        JSONObject json = new JSONObject(body == null ? "" : body);
        return json.optBoolean("registered");
    } catch (IOException | JSONException e) {
        return null;
    }
}
 
Example #10
Source File: VectorLayer.java    From android_maplib with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void createFromGeoJson(
        Uri uri,
        IProgressor progressor)
        throws IOException, JSONException, NGException, SQLiteException
{
    InputStream inputStream, is;
    String url = uri.toString();
    if (NetworkUtil.isValidUri(url)) {
        inputStream = new URL(url).openStream();
        is = new URL(url).openStream();
    } else {
        inputStream = mContext.getContentResolver().openInputStream(uri);
        is = mContext.getContentResolver().openInputStream(uri);
    }

    if (inputStream == null) {
        throw new NGException(mContext.getString(R.string.error_download_data));
    }

    if (null != progressor) {
        progressor.setMessage(mContext.getString(R.string.message_opening));
        progressor.setIndeterminate(true);
    }

    boolean isWGS84 = GeoJSONUtil.readGeoJSONCRS(is, getContext());
    GeoJSONUtil.createLayerFromGeoJSONStream(this, inputStream, progressor, isWGS84);
}
 
Example #11
Source File: NGWVectorLayer.java    From android_maplib with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected HttpResponse changeFeatureOnServer(long featureId, String payload) throws IOException {
    AccountUtil.AccountData accountData = AccountUtil.getAccountData(mContext, mAccountName);

    // change on server
    String url = NGWUtil.getFeatureUrl(accountData.url, mRemoteId, featureId);
    return NetworkUtil.put(url, payload, accountData.login, accountData.password, false);
}
 
Example #12
Source File: NGWVectorLayer.java    From android_maplib with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected HttpURLConnection getHttpConnection(AccountUtil.AccountData accountData) throws IOException {
    URL url = new URL(getFeaturesUrl(accountData));
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();

    final String basicAuth = NetworkUtil.getHTTPBaseAuth(accountData.login, accountData.password);
    if (null != basicAuth) {
        connection.setRequestProperty("Authorization", basicAuth);
    }

    return connection;
}
 
Example #13
Source File: NGWVectorLayer.java    From android_maplib with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected HttpResponse sendAttachOnServer(long featureId, AttachItem attach) throws IOException {
    // fill attach info
    String fileName = attach.getDisplayName();
    File filePath = new File(mPath, featureId + File.separator + attach.getAttachId());
    String fileMime = attach.getMimetype();

    // get account data
    AccountUtil.AccountData accountData = AccountUtil.getAccountData(mContext, mAccountName);

    // upload file
    String url = NGWUtil.getFileUploadUrl(accountData.url);
    return NetworkUtil.postFile(url, fileName, filePath, fileMime, accountData.login, accountData.password, false);
}
 
Example #14
Source File: CreateFromQMSLayerDialog.java    From android_maplibui with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected HttpResponse doInBackground(Integer... params) {
    if (!mNet.isNetworkAvailable())
        return new HttpResponse(NetworkUtil.ERROR_NETWORK_UNAVAILABLE);

    try {
        mLayerId = params[0];
        return NetworkUtil.get(QMS_GEOSERVICE_URL + mLayerId + QMS_DETAIL_APPENDIX, null, null, false);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return new HttpResponse(NetworkUtil.ERROR_DOWNLOAD_DATA);
}
 
Example #15
Source File: NGWRasterLayer.java    From android_maplib with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public Bitmap getBitmap(TileItem tile) {
    if (!mExtentReceived) {
        HttpResponse result = null;
        try {
            AccountUtil.AccountData accountData = AccountUtil.getAccountData(mContext, getAccountName());
            result = NetworkUtil.get(NGWUtil.getExtent(accountData.url, mRemoteId), getLogin(), getPassword(), false);
            if (!result.isOk()) {
                throw new IllegalStateException("");
            }
            JSONObject extent = new JSONObject(result.getResponseBody()).getJSONObject(JSON_EXTENT_KEY);
            double x = Geo.wgs84ToMercatorSphereX(extent.getDouble(JSON_MAX_LON_KEY));
            double y = Geo.wgs84ToMercatorSphereY(extent.getDouble(JSON_MAX_LAT_KEY));
            mExtents.setMax(x, y);
            x = Geo.wgs84ToMercatorSphereX(extent.getDouble(JSON_MIN_LON_KEY));
            y = Geo.wgs84ToMercatorSphereY(extent.getDouble(JSON_MIN_LAT_KEY));
            mExtents.setMin(x, y);
            mExtentReceived = true;
        } catch (IOException | JSONException | IllegalStateException ignored) {
            if (result != null && result.getResponseCode() == 404)
                mExtentReceived = true;
        }
    }

    if (mExtents.intersects(tile.getEnvelope()))
        return super.getBitmap(tile);

    return null;
}
 
Example #16
Source File: NGIDLoginFragment.java    From android_maplibui with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void onClick(View v) {
    if (v.getId() == R.id.signin) {
        final Activity activity = getActivity();
        if (activity == null)
            return;

        boolean loginPasswordFilled = checkEditText(mLogin) && checkEditText(mPassword);
        if (!loginPasswordFilled) {
            Toast.makeText(activity, R.string.field_not_filled, Toast.LENGTH_SHORT).show();
            return;
        }

        IGISApplication application = (IGISApplication) activity.getApplication();
        application.sendEvent(ConstantsUI.GA_NGID, ConstantsUI.GA_CONNECT, ConstantsUI.GA_USER);
        mSignInButton.setEnabled(false);
        String login = mLogin.getText().toString().trim();
        String password = mPassword.getText().toString();
        NGIDUtils.getToken(activity, login, password, new NGIDUtils.OnFinish() {
            @Override
            public void onFinish(HttpResponse response) {
                mSignInButton.setEnabled(true);

                if (response.isOk()) {
                    activity.getIntent().putExtra(NGIDLoginActivity.EXTRA_SUCCESS, true);
                    activity.finish();
                } else {
                    Toast.makeText(
                            activity,
                            NetworkUtil.getError(activity, response.getResponseCode()),
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    } else if (v.getId() == R.id.signup) {
        Intent browser = new Intent(Intent.ACTION_VIEW, Uri.parse(NGIDUtils.NGID_MY));
        startActivity(browser);
    }
}
 
Example #17
Source File: RemoteTMSLayer.java    From android_maplib with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void getTileFromStream(
        String url,
        File tilePath)
        throws IOException
{
    FileUtil.createDir(tilePath.getParentFile());
    OutputStream output = new FileOutputStream(tilePath.getAbsolutePath());
    NetworkUtil.getStream(url, getLogin(), getPassword(), output);
}
 
Example #18
Source File: RemoteTMSLayer.java    From android_maplib with GNU Lesser General Public License v3.0 5 votes vote down vote up
public RemoteTMSLayer(
        Context context,
        File path)
{
    super(context, path);

    mNet = new NetworkUtil(context);
    mSubdomains = new ArrayList<>();
    mCurrentSubdomain = 0;
    mLayerType = LAYERTYPE_REMOTE_TMS;
    mTileMaxAge = DEFAULT_TILE_MAX_AGE;
    setViewSize(100, 100);
}
 
Example #19
Source File: CreateFromQMSLayerDialog.java    From android_maplibui with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected HttpResponse doInBackground(Void... params) {
    if (!mNet.isNetworkAvailable())
        return new HttpResponse(NetworkUtil.ERROR_NETWORK_UNAVAILABLE);

    try {
        return NetworkUtil.get(QMS_GEOSERVICE_LIST_URL, null, null, false);
    } catch (IOException e) {
        e.printStackTrace();
    }

    return new HttpResponse(NetworkUtil.ERROR_DOWNLOAD_DATA);
}
 
Example #20
Source File: NGWLookupTable.java    From android_maplib with GNU Lesser General Public License v3.0 5 votes vote down vote up
public NGWLookupTable(Context context, File path) {
    super(context, path);

    mNet = new NetworkUtil(context);
    mSyncType = Constants.SYNC_NONE;
    mLayerType = Constants.LAYERTYPE_LOOKUPTABLE;
}
 
Example #21
Source File: Resource.java    From android_maplib with GNU Lesser General Public License v3.0 5 votes vote down vote up
public void fillPermissions()
{
    try {
        String sURL = NGWUtil.getResourceUrl(mConnection.getURL(), mRemoteId) + "/permission";
        HttpResponse response =
                NetworkUtil.get(sURL, mConnection.getLogin(), mConnection.getPassword(), false);
        if (!response.isOk())
            return;
        mPermissions = new JSONObject(response.getResponseBody());
        if (!mPermissions.has(Constants.JSON_RESOURCE_KEY))
            mPermissions = null;
    } catch (IOException | JSONException e) {
        e.printStackTrace();
    }
}
 
Example #22
Source File: Connection.java    From android_maplib with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void fillCapabilities()
{
    mSupportedTypes.clear();
    try {
        String sURL = mURL + "/resource/schema";
        HttpResponse response = NetworkUtil.get(sURL, getLogin(), getPassword(), false);
        if (!response.isOk())
            return;
        JSONObject schema = new JSONObject(response.getResponseBody());
        JSONObject resources = schema.getJSONObject("resources");
        if (null != resources) {
            Iterator<String> keys = resources.keys();
            while (keys.hasNext()) {
                int type = getType(keys.next());
                if (type != NGWResourceTypeNone) {
                    if (mSupportedTypes.isEmpty()) {
                        mSupportedTypes.add(type);
                    } else if (!isTypeSupported(type)) {
                        mSupportedTypes.add(type);
                    }
                }
            }
        }
    } catch (IOException | JSONException e) {
        e.printStackTrace();
    }
}
 
Example #23
Source File: NGIDUtils.java    From android_maplibui with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static HttpResponse getResponse(String target, String method, String token) {
    try {
        URL url = new URL(target);
        HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();

        if (!TextUtils.isEmpty(token))
            conn.setRequestProperty("Authorization", token);

        conn.setRequestMethod(method);
        conn.connect();

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line, data = "";
        while ((line = in.readLine()) != null)
            data += line;
        in.close();

        HttpResponse response = new HttpResponse(200);
        response.setResponseBody(data);
        response.setOk(true);
        return response;
    } catch (IOException ignored) {
        ignored.printStackTrace();
    }

    return new HttpResponse(NetworkUtil.ERROR_CONNECT_FAILED);
}
 
Example #24
Source File: CreateFromQMSLayerDialog.java    From android_maplibui with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected Void doInBackground(Void... params) {
    if (!mFile.exists()) {
        try {
            float density = getContext().getResources().getDisplayMetrics().density;
            int size = (int) (16 * density);
            if (size < 16)
                size = 16;
            if (size > 64)
                size = 64;

            String iconUrl;
            if (mFile.getName().equals("default"))
                iconUrl = QMS_ICON_URL + mFile.getName() + QMS_ICON_APPENDIX;
            else
                iconUrl = QMS_ICON_URL + mFile.getName() + QMS_ICON_CONTENT;

            iconUrl = iconUrl.replace("{w}", size + "").replace("{h}", size + "");
            HttpURLConnection connection = NetworkUtil.getHttpConnection("GET", iconUrl, null, null);
            if (connection != null) {
                if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                    InputStream input = connection.getInputStream();
                    Bitmap icon = BitmapFactory.decodeStream(input);
                    FileOutputStream fos = new FileOutputStream(mFile);
                    icon.compress(Bitmap.CompressFormat.PNG, 100, fos);
                    fos.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    return null;
}
 
Example #25
Source File: NGWCreateNewResourceTask.java    From android_maplibui with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
protected void onPostExecute(HttpResponse result)
{
    super.onPostExecute(result);

    String message;
    if (result.isOk()) {
        try {
            JSONObject obj = new JSONObject(result.getResponseBody());
            Long id = obj.getLong(Constants.JSON_ID_KEY);
            if (mLayer != null)
                mLayer.toNGW(id, mConnection.getName(), Constants.SYNC_ALL, mVer);
            result.setResponseCode(-999);
        } catch (JSONException e) {
            result.setResponseCode(500);
            e.printStackTrace();
        }
    }

    switch (result.getResponseCode()) {
        case -999:
            message = mContext.getString(mLayer == null
                                         ? R.string.message_group_created
                                         : R.string.message_layer_created);
            break;
        default:
            message = NetworkUtil.getError(mContext, result.getResponseCode());
            break;
    }

    Toast.makeText(mContext, message, Toast.LENGTH_LONG).show();
}
 
Example #26
Source File: NGWVectorLayer.java    From android_maplib with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected HttpResponse changeAttachOnServer(long featureId, long attachId, String putData) throws IOException {
    AccountUtil.AccountData accountData = AccountUtil.getAccountData(mContext, mAccountName);
    String url = NGWUtil.getFeatureAttachmentUrl(accountData.url, mRemoteId, featureId) + attachId;
    return NetworkUtil.put(url, putData, accountData.login,
                                            accountData.password, false);
}
 
Example #27
Source File: NGWVectorLayer.java    From android_maplib with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected HttpResponse deleteAttachOnServer(long featureId, long attachId) throws IOException {
    AccountUtil.AccountData accountData = AccountUtil.getAccountData(mContext, mAccountName);

    return NetworkUtil.delete(NGWUtil.getFeatureAttachmentUrl(accountData.url, mRemoteId, featureId)
                    + attachId, accountData.login, accountData.password, false);
}
 
Example #28
Source File: NGWVectorLayer.java    From android_maplib with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected HttpResponse addFeatureOnServer(String payload) throws IOException {
    AccountUtil.AccountData accountData = AccountUtil.getAccountData(mContext, mAccountName);

    return NetworkUtil.post(NGWUtil.getFeaturesUrl(accountData.url, mRemoteId),
                     payload, accountData.login, accountData.password, false);
}
 
Example #29
Source File: NGWVectorLayer.java    From android_maplib with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected HttpResponse deleteFeatureOnServer(long featureId) throws IOException {
    AccountUtil.AccountData accountData = AccountUtil.getAccountData(mContext, mAccountName);

    return NetworkUtil.delete(NGWUtil.getFeatureUrl(accountData.url, mRemoteId, featureId),
                               accountData.login, accountData.password, false);
}