Example usage for org.json JSONObject JSONObject

List of usage examples for org.json JSONObject JSONObject

Introduction

In this page you can find the example usage for org.json JSONObject JSONObject.

Prototype

public JSONObject(String source) throws JSONException 

Source Link

Document

Construct a JSONObject from a source JSON text string.

Usage

From source file:org.openmidaas.library.authentication.AuthCallbackForAccessToken.java

private void obtainAccessToken(SubjectToken subjectToken, String deviceToken) throws JSONException {
    AVSServer.getAuthToken(subjectToken, deviceToken, new AsyncHttpResponseHandler() {
        @Override// w  w w . jav  a2  s  .co m
        public void onSuccess(String response) {
            if (response == null || response.isEmpty()) {
                MIDaaS.logError(TAG, "Server response is empty.");
                mCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
            } else {
                try {
                    JSONObject accessToken = new JSONObject(response);
                    if ((accessToken.has(Constants.AccessTokenKeys.ACCESS_TOKEN)
                            && !(accessToken.isNull(Constants.AccessTokenKeys.ACCESS_TOKEN)))
                            && (accessToken.has(Constants.AccessTokenKeys.EXPIRES_IN)
                                    && !(accessToken.isNull(Constants.AccessTokenKeys.EXPIRES_IN)))) {
                        AccessToken token = AccessToken.createAccessToken(
                                accessToken.getString(Constants.AccessTokenKeys.ACCESS_TOKEN),
                                accessToken.getInt(Constants.AccessTokenKeys.EXPIRES_IN));
                        if (token != null) {
                            MIDaaS.logDebug(TAG, "got access token: ");
                            mCallback.onSuccess(token);
                        } else {
                            MIDaaS.logError(TAG, "Error could not create access token");
                            mCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
                        }
                    } else {
                        MIDaaS.logError(TAG, "Server response is not what is expected");
                        mCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
                    }

                } catch (JSONException e) {
                    MIDaaS.logError(TAG, "Internal error while parsing server JSON response");
                    mCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
                }

            }

        }

        @Override
        public void onFailure(Throwable e, String response) {
            MIDaaS.logError(TAG, "Server responded with error " + response);
            mCallback.onError(new MIDaaSException(MIDaaSError.SERVER_ERROR));
        }
    });
}

From source file:com.cdd.bao.importer.KeywordMapping.java

public KeywordMapping(String mapFN) {
    file = new File(mapFN);

    // try to load the file, but it's OK if it fails
    JSONObject json = null;//from  w  ww  .j a  v a 2  s.  c o m
    try {
        Reader rdr = new FileReader(file);
        json = new JSONObject(new JSONTokener(rdr));
        rdr.close();
    } catch (JSONException ex) {
        Util.writeln("NOTE: reading file " + file.getAbsolutePath() + " failed: " + ex.getMessage());
    } catch (IOException ex) {
        return;
    } // includes file not found, which is OK

    try {
        for (JSONObject obj : json.optJSONArrayEmpty("identifiers").toObjectArray()) {
            Identifier id = new Identifier();
            id.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            id.prefix = obj.optString("prefix");
            identifiers.add(id);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("textBlocks").toObjectArray()) {
            TextBlock txt = new TextBlock();
            txt.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            txt.title = obj.optString("title");
            textBlocks.add(txt);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("properties").toObjectArray()) {
            Property prop = new Property();
            prop.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            prop.propURI = obj.optString("propURI");
            prop.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray();
            properties.add(prop);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("values").toObjectArray()) {
            Value val = new Value();
            val.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            val.valueRegex = regexOrName(obj.optString("valueRegex"), obj.optString("valueName"));
            val.valueURI = obj.optString("valueURI");
            val.propURI = obj.optString("propURI");
            val.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray();
            values.add(val);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("literals").toObjectArray()) {
            Literal lit = new Literal();
            lit.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            lit.valueRegex = regexOrName(obj.optString("valueRegex"), obj.optString("valueName"));
            lit.propURI = obj.optString("propURI");
            lit.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray();
            literals.add(lit);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("references").toObjectArray()) {
            Reference ref = new Reference();
            ref.regex = regexOrName(obj.optString("regex"), obj.optString("name"));
            ref.valueRegex = regexOrName(obj.optString("valueRegex"), obj.optString("valueName"));
            ref.prefix = obj.optString("prefix");
            ref.propURI = obj.optString("propURI");
            ref.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray();
            references.add(ref);
        }
        for (JSONObject obj : json.optJSONArrayEmpty("assertions").toObjectArray()) {
            Assertion asrt = new Assertion();
            asrt.propURI = obj.optString("propURI");
            asrt.groupNest = obj.optJSONArrayEmpty("groupNest").toStringArray();
            asrt.valueURI = obj.optString("valueURI");
            assertions.add(asrt);
        }
    } catch (JSONException ex) {
        Util.writeln("NOTE: parsing error");
        ex.printStackTrace();
        Util.writeln(
                "*** Execution will continue, but part of the mapping has not been loaded and may be overwritten.");
    }
}

From source file:ai.ilikeplaces.logic.sits9.SubscriberNotifications.java

@Timeout
synchronized public void timeout(final Timer timer)
        throws IOException, SAXException, TransformerException, JSONException, SQLException {

    final HBaseCrudService<GeohashSubscriber> _geohashSubscriberHBaseCrudService = new HBaseCrudService<GeohashSubscriber>();
    final HBaseCrudService<GeohashSubscriber>.Scanner _scanner = _geohashSubscriberHBaseCrudService
            .scan(new GeohashSubscriber(), 1).returnValueBadly();

    while (_scanner.getNewValue() != null) {
        final String _newValue = _scanner.getNewValue();
        Loggers.debug("Scanned value:" + _newValue);
        final RowResponse _rowResponse = new Gson().fromJson(_newValue, RowResponse.class);
        Loggers.debug("Scanned as GSON:" + _rowResponse.toString());

        for (final Row _row : _rowResponse.Row) {

            final BASE64Decoder _base64DecoderRowKey = new BASE64Decoder();
            final byte[] _bytes = _base64DecoderRowKey.decodeBuffer(_row.key);
            final String rowKey = new String(_bytes);
            Loggers.debug("Decoded row key:" + rowKey);

            for (final Cell _cell : _row.Cell) {
                final BASE64Decoder _base64DecoderValue = new BASE64Decoder();
                final byte[] _valueBytes = _base64DecoderValue.decodeBuffer(_cell.$);
                final String _cellAsString = new String(_valueBytes);
                Loggers.debug("Cell as string:" + _cellAsString);
                final GeohashSubscriber _geohashSubscriber = new GeohashSubscriber();

                final DatumReader<GeohashSubscriber> _geohashSubscriberSpecificDatumReader = new SpecificDatumReader<GeohashSubscriber>(
                        _geohashSubscriber.getSchema());
                final BinaryDecoder _binaryDecoder = DecoderFactory.get().binaryDecoder(_valueBytes, null);
                final GeohashSubscriber _read = _geohashSubscriberSpecificDatumReader.read(_geohashSubscriber,
                        _binaryDecoder);
                Loggers.debug("Decoded value avro:" + _read.toString());

                final Date now = new Date();
                final Calendar _week = Calendar.getInstance();
                _week.setTimeInMillis(now.getTime() + (7 * 24 * 60 * 60 * 1000));
                final SimpleDateFormat _simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
                _simpleDateFormat.format(_week.getTime());

                final StringBuffer eventList = new StringBuffer("");

                {//Eventful

                    try {

                        final SimpleDateFormat eventfulDate = new SimpleDateFormat("yyyyMMdd00");
                        _simpleDateFormat.format(_week.getTime());

                        final JSONObject jsonObject = Modules.getModules().getEventulFactory()
                                .getInstance("http://api.eventful.com/json/events/search/")
                                .get("", new HashMap<String, String>() {
                                    {//Don't worry, this is a static initializer of this map :)
                                        put("location", "" + _read.getLatitude() + "," + _read.getLongitude());
                                        put("within", "" + 100);
                                        put("date", eventfulDate.format(Calendar.getInstance().getTime()) + "-"
                                                + eventfulDate.format(_week.getTime()));
                                    }//from  w ww. ja va  2 s  .c o m
                                }

                        );

                        Loggers.debug("Eventful Reply:" + jsonObject.toString());

                        final JSONArray events = jsonObject.getJSONObject("events").getJSONArray("event");

                        final Document eventTemplateDocument = HTMLDocParser
                                .getDocument(RBGet.getGlobalConfigKey("PAGEFILES") + SUBSCRIBER_EMAIL_EVENT);
                        final String eventTemplate = HTMLDocParser
                                .convertNodeToHtml(HTMLDocParser.$("content", eventTemplateDocument));

                        for (int i = 0; i < events.length(); i++) {
                            final JSONObject eventJSONObject = new JSONObject(events.get(i).toString());
                            Double.parseDouble(eventJSONObject.getString(LATITUDE));
                            Double.parseDouble(eventJSONObject.getString(LONGITUDE));
                            final String eventName = eventJSONObject.getString("title");
                            final String eventUrl = eventJSONObject.getString("url");
                            final String eventDate = eventJSONObject.getString("start_time");
                            final String eventVenue = eventJSONObject.getString("venue_name");
                            Loggers.debug("Event name:" + eventName);
                            eventList
                                    .append(eventTemplate
                                            .replace("_name_link_",
                                                    !(("" + eventUrl).isEmpty()) ? eventUrl
                                                            : ("https://www.google.com/search?q=" + eventName
                                                                    .replaceAll(" ", "+").replaceAll("-", "+")))
                                            .replace("_place_link_",
                                                    "https://maps.googleapis.com/maps/api/staticmap?sensor=false&size=600x600&markers=color:blue%7Clabel:S%7C"
                                                            + _read.getLatitude().toString() + ","
                                                            + _read.getLongitude().toString())
                                            .replace("_name_", eventName).replace("_place_", eventVenue)
                                            .replace("_date_", eventDate));
                        }
                    } catch (final Throwable t) {
                        Loggers.error("Error appending Eventful data to Geohash Subscriber", t);
                    }
                }

                {//Foursquare

                    try {

                        _simpleDateFormat.format(_week.getTime());

                        final JSONObject jsonObject = Modules.getModules().getEventulFactory()
                                .getInstance("https://api.foursquare.com/v2/venues/explore")
                                .get("", new HashMap<String, String>() {
                                    {//Don't worry, this is a static initializer of this map :)
                                        put("ll", "" + _read.getLatitude() + "," + _read.getLongitude());
                                        put("radius", "" + 50000);//meters
                                        put("intent", "browse");
                                        put("section", "topPicks");
                                        put("client_secret",
                                                "PODRX5YWBSLAKAYRQ5CLPEPS3WHCXWFIJ3LXF3AKH4U1BDNI");
                                        put("client_id", "25JZAK3TQPLIPUUXPIJWXQ5NSKSPTP4SYZLUZSCTZF3UJ4YX");
                                    }
                                }

                        );

                        Loggers.debug("Foursquare Reply:" + jsonObject.toString());

                        final JSONArray referralArray = jsonObject.getJSONObject("response")
                                .getJSONArray("groups").getJSONObject(0).getJSONArray("items");

                        final Document eventTemplateDocument = HTMLDocParser
                                .getDocument(RBGet.getGlobalConfigKey("PAGEFILES") + SUBSCRIBER_EMAIL_PLACE);
                        final String eventTemplate = HTMLDocParser
                                .convertNodeToHtml(HTMLDocParser.$("content", eventTemplateDocument));

                        for (int i = 0; i < referralArray.length(); i++) {

                            final JSONObject referral = referralArray.getJSONObject(i);
                            referral.getJSONObject("venue").getJSONObject("location").getDouble("lng");
                            referral.getJSONObject("venue").getJSONObject("location").getDouble("lat");
                            final String eventName = referral.getJSONObject("venue").getString("name");
                            final String eventUrl = referral.getJSONObject("venue").optString("url");
                            final String eventVenue = referral.getJSONObject("venue").getJSONObject("location")
                                    .getString("address");
                            Loggers.debug("Event name:" + eventName);
                            eventList
                                    .append(eventTemplate
                                            .replace("_name_link_",
                                                    !(("" + eventUrl).isEmpty()) ? eventUrl
                                                            : ("https://www.google.com/search?q=" + eventName
                                                                    .replaceAll(" ", "+").replaceAll("-", "+")))
                                            .replace("_place_link_",
                                                    "https://maps.googleapis.com/maps/api/staticmap?sensor=false&size=600x600&markers=color:blue%7Clabel:S%7C"
                                                            + _read.getLatitude().toString() + ","
                                                            + _read.getLongitude().toString())
                                            .replace("_name_", eventName).replace("_place_", eventVenue)
                                            .replace("_date_", eventName));
                        }
                    } catch (final Throwable t) {
                        Loggers.error("Error appending Foursquare data to Geohash Subscriber", t);
                    }
                }

                final String template = HTMLDocParser
                        .getDocumentAsString(RBGet.getGlobalConfigKey("PAGEFILES") + EMAIL_FRAME);
                final Document email = HTMLDocParser
                        .getDocument(RBGet.getGlobalConfigKey("PAGEFILES") + SUBSCRIBER_EMAIL);
                final String _content = HTMLDocParser.convertNodeToHtml(HTMLDocParser.$("content", email));
                final Parameter _unsubscribeLink = new Parameter("http://www.ilikeplaces.com/unsubscribe/")
                        .append(Unsubscribe.TYPE, Unsubscribe.Type.GeohashSubscribe.name(), true)
                        .append(Unsubscribe.VALUE, rowKey);
                final String finalEmail = template.replace("_FrameContent_",
                        _content.replace(" ___||_", eventList.toString()).replace("_unsubscribe_link_",
                                _unsubscribeLink.get()));
                Loggers.debug("Final email:" + finalEmail);
                sendMailLocal.sendAsHTML(_read.getEmailId().toString(), "Thank God it's Friday!", finalEmail);
            }

        }

        _geohashSubscriberHBaseCrudService.scan(new GeohashSubscriber(), _scanner);
    }

    Loggers.debug("Completed scanner");

}

From source file:com.ryandymock.consumptionvisualization.ParticleRenderer.java

public void onSurfaceCreated(Context context) {
    // Create the render surfaces
    for (int i = 0; i < mRenderSurface.length; i++) {
        mRenderSurface[i] = new RenderSurface(FB_SIZE, FB_SIZE);
        mRenderSurface[i].setClearColor(Color.argb(0, 255, 255, 255));
    }//from   ww  w .  j av  a  2s. c o m

    // Create the blur renderer
    mBlurRenderer = new BlurRenderer();

    // Read in our specific json file
    String materialFile = FileHelper.loadAsset(context.getAssets(), JSON_FILE);
    try {
        JSONObject json = new JSONObject(materialFile);

        // Water particle material. We are utilizing the position and color
        // buffers returned from LiquidFun directly.
        mWaterParticleMaterial = new WaterParticleMaterial(context,
                json.getJSONObject("waterParticlePointSprite"));

        // Initialize attributes specific to this material
        mWaterParticleMaterial.addAttribute("aPosition", 2, Material.AttrComponentType.FLOAT, 4, false, 0);
        mWaterParticleMaterial.addAttribute("aColor", 4, Material.AttrComponentType.UNSIGNED_BYTE, 1, true, 0);
        mWaterParticleMaterial.addAttribute("aWeight", 1, Material.AttrComponentType.FLOAT, 1, false, 0);
        mWaterParticleMaterial.setBlendFunc(Material.BlendFactor.ONE, Material.BlendFactor.ONE_MINUS_SRC_ALPHA);

        // Non-water particle material. We are utilizing the position and
        // color buffers returned from LiquidFun directly.
        mParticleMaterial = new ParticleMaterial(context, json.getJSONObject("otherParticlePointSprite"));

        // Initialize attributes specific to this material
        mParticleMaterial.addAttribute("aPosition", 2, Material.AttrComponentType.FLOAT, 4, false, 0);
        mParticleMaterial.addAttribute("aColor", 4, Material.AttrComponentType.UNSIGNED_BYTE, 1, true, 0);
        mParticleMaterial.setBlendFunc(Material.BlendFactor.ONE, Material.BlendFactor.ONE_MINUS_SRC_ALPHA);

        // Scrolling texture when we copy water particles from FBO to screen
        mWaterScreenRenderer = new ScreenRenderer(context, json.getJSONObject("waterParticleToScreen"),
                mRenderSurface[0].getTexture());

        // Scrolling texture when we copy water particles from FBO to screen
        mScreenRenderer = new ScreenRenderer(context, json.getJSONObject("otherParticleToScreen"),
                mRenderSurface[1].getTexture());

        // Texture for paper
        JSONObject materialData = json.getJSONObject(PAPER_MATERIAL_NAME);
        String textureName = materialData.getString(DIFFUSE_TEXTURE_NAME);
        mPaperTexture = new Texture(context, textureName);
    } catch (JSONException ex) {
        Log.e(TAG, "Cannot parse" + JSON_FILE + "\n" + ex.getMessage());
    }
}

From source file:eu.codeplumbers.cosi.api.tasks.RegisterDeviceTask.java

@Override
protected Device doInBackground(Void... voids) {
    URL urlO = null;//from  w  w w  .  j  a  v a  2  s.c  om
    try {
        urlO = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        OutputStream os = conn.getOutputStream();
        os.write(deviceString.getBytes("UTF-8"));
        os.flush();

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONObject jsonObject = new JSONObject(result);

        if (jsonObject != null) {
            if (jsonObject.has("login")) {
                resultDevice = new Device();
                resultDevice.setUrl(url.replace("/device/", ""));
                //Log.d(getClass().getName(), "Token="+jsonObject.getString("login"));
                resultDevice.setLogin(jsonObject.getString("login"));
                resultDevice.setPassword(jsonObject.getString("password"));
                resultDevice.setPermissions(jsonObject.getString("permissions"));

                resultDevice.setFirstSyncDone(false);
                resultDevice.setSyncCalls(false);
                resultDevice.setSyncContacts(false);
                resultDevice.setSyncFiles(false);
                resultDevice.setSyncNotes(false);

                resultDevice.save();
            } else {
                errorMessage = jsonObject.getString("error");
            }
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        errorMessage = e.getLocalizedMessage();
    } catch (ProtocolException e) {
        errorMessage = e.getLocalizedMessage();
    } catch (IOException e) {
        errorMessage = e.getLocalizedMessage();
    } catch (JSONException e) {
        errorMessage = e.getLocalizedMessage();
    }

    return resultDevice;
}

From source file:io.fabric8.kubernetes.api.Controller.java

private String convertYamlToJson(String yamlString) throws FileNotFoundException {
    Yaml yaml = new Yaml();

    Map<String, Object> map = (Map<String, Object>) yaml.load(yamlString);
    JSONObject jsonObject = new JSONObject(map);

    return jsonObject.toString();
}

From source file:io.fabric8.kubernetes.api.Controller.java

private String convertYamlToJson(File yamlFile) throws FileNotFoundException {
    Yaml yaml = new Yaml();
    FileInputStream fstream = new FileInputStream(yamlFile);

    Map<String, Object> map = (Map<String, Object>) yaml.load(fstream);
    JSONObject jsonObject = new JSONObject(map);

    return jsonObject.toString();
}

From source file:nl.b3p.viewer.stripes.IbisMergeFeaturesActionBean.java

/**
 * Force the workflow status attribute on the feature. This will handle the
 * case where the {@code extraData} attribute is a piecs of json with the
 * workflow, eg/*from w ww. j  a  v  a 2s  . c  o  m*/
 * {@code {workflow_status:'afgevoerd',datum_mutatie:'2015-12-01Z00:00'}}.
 *
 * @param features A list of features to be modified
 * @return the list of modified features that are about to be committed to
 * the datastore
 *
 * @throws JSONException if json parsing failed
 */
@Override
protected List<SimpleFeature> handleExtraData(List<SimpleFeature> features) throws JSONException {
    JSONObject json = new JSONObject(this.getExtraData());
    Iterator items = json.keys();
    while (items.hasNext()) {
        String key = (String) items.next();
        for (SimpleFeature f : features) {
            log.debug(String.format("Setting value: %s for attribute: %s on feature %s", json.get(key), key,
                    f.getID()));
            f.setAttribute(key, json.get(key));
            if (key.equalsIgnoreCase(WORKFLOW_FIELDNAME)) {
                newWorkflowStatus = WorkflowStatus.valueOf(json.getString(key));
            }
        }
    }
    return features;
}

From source file:eu.codeplumbers.cosi.services.CosiLoyaltyCardService.java

/**
 * Make remote request to get all loyalty cards stored in Cozy
 *//*from ww w.ja v  a  2s  .  co  m*/
public String getRemoteLoyaltyCards() {
    URL urlO = null;
    try {
        urlO = new URL(designUrl);
        HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        conn.setRequestProperty("Authorization", authHeader);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");

        // read the response
        int status = conn.getResponseCode();
        InputStream in = null;

        if (status >= HttpURLConnection.HTTP_BAD_REQUEST) {
            in = conn.getErrorStream();
        } else {
            in = conn.getInputStream();
        }

        StringWriter writer = new StringWriter();
        IOUtils.copy(in, writer, "UTF-8");
        String result = writer.toString();

        JSONArray jsonArray = new JSONArray(result);

        if (jsonArray != null) {
            if (jsonArray.length() == 0) {
                EventBus.getDefault()
                        .post(new LoyaltyCardSyncEvent(SYNC_MESSAGE, "Your Cozy has no calls stored."));
                LoyaltyCard.setAllUnsynced();
            } else {
                for (int i = 0; i < jsonArray.length(); i++) {
                    try {

                        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SYNC_MESSAGE,
                                "Reading loyalty cards on Cozy " + i + "/" + jsonArray.length() + "..."));
                        JSONObject loyaltyCardJson = jsonArray.getJSONObject(i).getJSONObject("value");
                        LoyaltyCard loyaltyCard = LoyaltyCard
                                .getByRemoteId(loyaltyCardJson.get("_id").toString());
                        if (loyaltyCard == null) {
                            loyaltyCard = new LoyaltyCard(loyaltyCardJson);
                        } else {
                            loyaltyCard.setRemoteId(loyaltyCardJson.getString("_id"));
                            loyaltyCard.setRawValue(loyaltyCardJson.getString("rawValue"));
                            loyaltyCard.setCode(loyaltyCardJson.getInt("code"));
                            loyaltyCard.setLabel(loyaltyCardJson.getString("label"));
                            loyaltyCard.setCreationDate(loyaltyCardJson.getString("creationDate"));
                        }

                        loyaltyCard.save();
                    } catch (JSONException e) {
                        EventBus.getDefault()
                                .post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
                        stopSelf();
                    }
                }
            }
        } else {
            errorMessage = new JSONObject(result).getString("error");
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, errorMessage));
            stopSelf();
        }

        in.close();
        conn.disconnect();

    } catch (MalformedURLException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (ProtocolException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (IOException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    } catch (JSONException e) {
        EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
        stopSelf();
    }
    return errorMessage;
}

From source file:eu.codeplumbers.cosi.services.CosiLoyaltyCardService.java

public void sendChangesToCozy() {
    List<LoyaltyCard> unSyncedLoyaltyCards = LoyaltyCard.getAllUnsynced();
    int i = 0;//from  ww  w  .j a  v a 2s  .  c om
    for (LoyaltyCard loyaltyCard : unSyncedLoyaltyCards) {
        URL urlO = null;
        try {
            JSONObject jsonObject = loyaltyCard.toJsonObject();
            mBuilder.setProgress(unSyncedLoyaltyCards.size(), i + 1, false);
            mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":");
            mNotifyManager.notify(notification_id, mBuilder.build());
            EventBus.getDefault().post(
                    new LoyaltyCardSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_sms_status_read_phone)));
            String remoteId = jsonObject.getString("remoteId");
            String requestMethod = "";

            if (remoteId.isEmpty()) {
                urlO = new URL(syncUrl);
                requestMethod = "POST";
            } else {
                urlO = new URL(syncUrl + remoteId + "/");
                requestMethod = "PUT";
            }

            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestMethod(requestMethod);

            // set request body
            jsonObject.remove("remoteId");
            long objectId = jsonObject.getLong("id");
            jsonObject.remove("id");
            OutputStream os = conn.getOutputStream();
            os.write(jsonObject.toString().getBytes("UTF-8"));
            os.flush();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());

            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer, "UTF-8");
            String result = writer.toString();

            JSONObject jsonObjectResult = new JSONObject(result);

            if (jsonObjectResult != null && jsonObjectResult.has("_id")) {
                result = jsonObjectResult.getString("_id");
                loyaltyCard.setRemoteId(result);
                loyaltyCard.save();
            }

            in.close();
            conn.disconnect();

        } catch (MalformedURLException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (ProtocolException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (IOException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (JSONException e) {
            EventBus.getDefault().post(new LoyaltyCardSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        }
        i++;
    }
}