Example usage for org.json JSONObject getString

List of usage examples for org.json JSONObject getString

Introduction

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

Prototype

public String getString(String key) throws JSONException 

Source Link

Document

Get the string associated with a key.

Usage

From source file:com.extremeboredom.wordattack.utils.JSONUtils.java

/**
 * get String from jsonObject/*from w w w.j a  v a  2  s  .co  m*/
 *
 * @param jsonObject
 * @param key
 * @param defaultValue
 * @return <ul>
 * <li>if jsonObject is null, return defaultValue</li>
 * <li>if key is null or empty, return defaultValue</li>
 * <li>if {@link JSONObject#getString(String)} exception, return defaultValue</li>
 * <li>return {@link JSONObject#getString(String)}</li>
 * </ul>
 */
public static String getString(JSONObject jsonObject, String key, String defaultValue) {
    if (jsonObject == null || StringUtils.isEmpty(key)) {
        return defaultValue;
    }

    try {
        return jsonObject.getString(key);
    } catch (JSONException e) {
        if (isPrintException) {
            e.printStackTrace();
        }
        return defaultValue;
    }
}

From source file:com.example.android.popularmoviesist2.data.FetchTrailerMovieTask.java

private String[] getMoviesDataFromJson(String moviesJsonStr) throws JSONException {

    final String JSON_LIST = "results";
    final String JSON_ID = "id";
    final String JSON_KEY = "key";
    final String JSON_NAME = "name";
    final String JSON_SITE = "site";

    urlYoutbe.clear();/*from  w w  w  . j av a  2  s .com*/

    try {
        JSONObject moviesJson = new JSONObject(moviesJsonStr);
        JSONArray moviesArray = moviesJson.getJSONArray(JSON_LIST);

        final String[] result = new String[moviesArray.length()];

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

            JSONObject movie = moviesArray.getJSONObject(i);
            String id = movie.getString(JSON_ID);
            String key = movie.getString(JSON_KEY);
            String name = movie.getString(JSON_NAME);
            String site = movie.getString(JSON_SITE);

            result[i] = key;
        }
        return result;
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
        return null;
    }

}

From source file:org.entando.entando.plugins.jptrello.aps.system.services.trello.TrelloConfig.java

public TrelloConfig(String xml) {
    if (StringUtils.isNotBlank(xml)) {
        JSONObject json = XML.toJSONObject(xml);
        json = json.getJSONObject(CONFIG_ROOT);

        if (json.has(CONFIG_ORGANIZATION)) {
            _organization = json.getString(CONFIG_ORGANIZATION);
        }/*from  w  w  w .j  a  va 2  s. c  om*/
        if (json.has(CONFIG_KEY)) {
            _apiKey = json.getString(CONFIG_KEY);
        }
        if (json.has(CONFIG_SECRET)) {
            _apiSecret = json.getString(CONFIG_SECRET);
        }
        if (json.has(CONFIG_TOKEN)) {
            _token = json.getString(CONFIG_TOKEN);
        }
    }
}

From source file:gov.sfmta.sfpark.MainScreenActivity.java

public void readData() throws JSONException {
    MYLOG("readData() start");

    if (SFparkActivity.responseString == null || SFparkActivity.responseString == "") {
        return;//from  w w w. j a v  a 2s . co m
    }

    String message = null;
    JSONObject rootObject = null;
    JSONArray jsonAVL = null;

    rootObject = new JSONObject(SFparkActivity.responseString);
    message = rootObject.getString("MESSAGE");
    jsonAVL = rootObject.getJSONArray("AVL");
    timeStampXML = rootObject.getString("AVAILABILITY_UPDATED_TIMESTAMP");

    MYLOG(message);

    int i = 0;
    int len = jsonAVL.length();

    if (annotations == null) {
        annotations = new ArrayList<MyAnnotation>();
    } else {
        annotations.clear();
    }

    for (i = 0; i < len; ++i) {
        JSONObject interestArea = jsonAVL.getJSONObject(i);
        MyAnnotation annotation = new MyAnnotation();
        annotation.allGarageData = interestArea;
        annotation.initFromData();

        // new: UBER-HACK! SFMTA wants me to hide the Calif/Steiner lot.
        if ("California and Steiner Lot".equals(annotation.title))
            continue;

        annotations.add(annotation);
    }

    MYLOG("readData() finish ");
}

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//from  w ww. ja  v a  2s . com
        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 JSONObject createAssay(JSONObject keydata, Schema schema, Map<Schema.Assignment, SchemaTree> treeCache)
        throws JSONException, IOException {
    String uniqueID = null;//  w w w .jav  a 2  s .  c om
    List<String> linesTitle = new ArrayList<>(), linesBlock = new ArrayList<>();
    List<String> linesSkipped = new ArrayList<>(), linesProcessed = new ArrayList<>();
    Set<String> gotAnnot = new HashSet<>(), gotLiteral = new HashSet<>();
    JSONArray jsonAnnot = new JSONArray();
    final String SEP = "::";

    // assertions: these always supply a term
    for (Assertion asrt : assertions) {
        JSONObject obj = new JSONObject();
        obj.put("propURI", ModelSchema.expandPrefix(asrt.propURI));
        obj.put("groupNest", new JSONArray(expandPrefixes(asrt.groupNest)));
        obj.put("valueURI", ModelSchema.expandPrefix(asrt.valueURI));
        jsonAnnot.put(obj);

        String hash = asrt.propURI + SEP + asrt.valueURI + SEP
                + (asrt.groupNest == null ? "" : String.join(SEP, asrt.groupNest));
        gotAnnot.add(hash);
    }

    // go through the columns one at a time
    for (String key : keydata.keySet()) {
        String data = keydata.getString(key);

        Identifier id = findIdentifier(key);
        if (id != null) {
            if (uniqueID == null)
                uniqueID = id.prefix + data;
            continue;
        }

        TextBlock tblk = findTextBlock(key);
        if (tblk != null) {
            if (Util.isBlank(tblk.title))
                linesTitle.add(data);
            else
                linesBlock.add(tblk.title + ": " + data);
        }

        Value val = findValue(key, data);
        if (val != null) {
            if (Util.isBlank(val.valueURI)) {
                linesSkipped.add(key + ": " + data);
            } else {
                String hash = val.propURI + SEP + val.valueURI + SEP
                        + (val.groupNest == null ? "" : String.join(SEP, val.groupNest));
                if (gotAnnot.contains(hash))
                    continue;

                JSONObject obj = new JSONObject();
                obj.put("propURI", ModelSchema.expandPrefix(val.propURI));
                obj.put("groupNest", new JSONArray(expandPrefixes(val.groupNest)));
                obj.put("valueURI", ModelSchema.expandPrefix(val.valueURI));
                jsonAnnot.put(obj);
                gotAnnot.add(hash);
                linesProcessed.add(key + ": " + data);
            }
            continue;
        }

        Literal lit = findLiteral(key, data);
        if (lit != null) {
            String hash = lit.propURI + SEP + (lit.groupNest == null ? "" : String.join(SEP, lit.groupNest))
                    + SEP + data;
            if (gotLiteral.contains(hash))
                continue;

            JSONObject obj = new JSONObject();
            obj.put("propURI", ModelSchema.expandPrefix(lit.propURI));
            obj.put("groupNest", new JSONArray(expandPrefixes(lit.groupNest)));
            obj.put("valueLabel", data);
            jsonAnnot.put(obj);
            gotLiteral.add(hash);
            linesProcessed.add(key + ": " + data);

            continue;
        }

        Reference ref = findReference(key, data);
        if (ref != null) {
            Pattern ptn = Pattern.compile(ref.valueRegex);
            Matcher m = ptn.matcher(data);
            if (!m.matches() || m.groupCount() < 1)
                throw new IOException(
                        "Pattern /" + ref.valueRegex + "/ did not match '" + data + "' to produce a group.");

            JSONObject obj = new JSONObject();
            obj.put("propURI", ModelSchema.expandPrefix(ref.propURI));
            obj.put("groupNest", new JSONArray(expandPrefixes(ref.groupNest)));
            obj.put("valueLabel", ref.prefix + m.group(1));
            jsonAnnot.put(obj);
            linesProcessed.add(key + ": " + data);

            continue;
        }

        // probably shouldn't get this far, but just in case
        linesSkipped.add(key + ": " + data);
    }

    // annotation collapsing: sometimes there's a branch sequence that should exclude parent nodes
    for (int n = 0; n < jsonAnnot.length(); n++) {
        JSONObject obj = jsonAnnot.getJSONObject(n);
        String propURI = obj.getString("propURI"), valueURI = obj.optString("valueURI");
        if (valueURI == null)
            continue;
        String[] groupNest = obj.getJSONArray("groupNest").toStringArray();
        Schema.Assignment[] assnList = schema.findAssignmentByProperty(ModelSchema.expandPrefix(propURI),
                groupNest);
        if (assnList.length == 0)
            continue;
        SchemaTree tree = treeCache.get(assnList[0]);
        if (tree == null)
            continue;

        Set<String> exclusion = new HashSet<>();
        for (SchemaTree.Node node = tree.getNode(valueURI); node != null; node = node.parent)
            exclusion.add(node.uri);
        if (exclusion.size() == 0)
            continue;

        for (int i = jsonAnnot.length() - 1; i >= 0; i--)
            if (i != n) {
                obj = jsonAnnot.getJSONObject(i);
                if (!obj.has("valueURI"))
                    continue;
                if (!propURI.equals(obj.getString("propURI")))
                    continue;
                if (!Objects.deepEquals(groupNest, obj.getJSONArray("groupNest").toStringArray()))
                    continue;
                if (!exclusion.contains(obj.getString("valueURI")))
                    continue;
                jsonAnnot.remove(i);
            }
    }

    /*String text = "";
    if (linesBlock.size() > 0) text += String.join("\n", linesBlock) + "\n\n";
    if (linesSkipped.size() > 0) text += "SKIPPED:\n" + String.join("\n", linesSkipped) + "\n\n";
    text += "PROCESSED:\n" + String.join("\n", linesProcessed);*/

    List<String> sections = new ArrayList<>();
    if (linesTitle.size() > 0)
        sections.add(String.join(" / ", linesTitle));
    if (linesBlock.size() > 0)
        sections.add(String.join("\n", linesBlock));
    sections.add("#### IMPORTED ####");
    if (linesSkipped.size() > 0)
        sections.add("SKIPPED:\n" + String.join("\n", linesSkipped));
    if (linesProcessed.size() > 0)
        sections.add("PROCESSED:\n" + String.join("\n", linesProcessed));
    String text = String.join("\n\n", sections);

    JSONObject assay = new JSONObject();
    assay.put("uniqueID", uniqueID);
    assay.put("text", text);
    assay.put("schemaURI", schema.getSchemaPrefix());
    assay.put("annotations", jsonAnnot);
    return assay;
}

From source file:com.beevou.android.authentication.NetworkUtilities.java

/**
 * Connects to the Voiper server, authenticates the provided username and
 * password.//from ww  w  .j  av  a 2  s  .c  o  m
 * 
 * @param username The user's username
 * @param password The user's password
 * @param handler The hander instance from the calling UI thread.
 * @param context The context of the calling Activity.
 * @return boolean The boolean result indicating whether the user was
 *         successfully authenticated.
 */
/* 
 public static boolean authenticate(String username, String password,
Handler handler, final Context context) {
final HttpResponse resp;
        
final ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(PARAM_USERNAME, username));
params.add(new BasicNameValuePair(PARAM_PASSWORD, password));
HttpEntity entity = null;
try {
    entity = new UrlEncodedFormEntity(params);
} catch (final UnsupportedEncodingException e) {
    // this should never happen.
    throw new AssertionError(e);
}
final HttpPost post = new HttpPost(AUTH_URI);
Log.e("url", AUTH_URI);
post.addHeader(entity.getContentType());
post.setEntity(entity);
maybeCreateHttpClient();
        
try {
    resp = mHttpClient.execute(post);
    if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
               
       HttpEntity httpEntity = resp.getEntity();
       InputStream is = httpEntity.getContent();
               
       try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "n");
            }
            is.close();
            String json = sb.toString();
            Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }
               
       if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "Successful authentication");
        }
        sendResult(true, handler, context);
        return true;
    } else {
        if (Log.isLoggable(TAG, Log.VERBOSE)) {
            Log.v(TAG, "Error authenticating" + resp.getStatusLine());
        }
        sendResult(false, handler, context);
        return false;
    }
} catch (final IOException e) {
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "IOException when getting authtoken", e);
    }
    sendResult(false, handler, context);
    return false;
} finally {
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "getAuthtoken completing");
    }
}
 }*/

public static boolean authenticate(String username, String password, Handler handler, final Context context) {

    JSONObject token = jsonParser.getJSONFromUrl(
            "https://beevou.net/oauth/token?grant_type=password&username=" + username + "&password=" + password
                    + "&client_id=NTEyMWZmNTdkZDVlMDVm&client_secret=438a58c31557b2db11523a2dc350e74fae06e0d2");

    if (token != null) {
        try {
            String accessToken = token.getString("access_token");
            String refreshToken = token.getString("refresh_token");
            //tokenExpiresIn.add(Calendar.SECOND, expirationSecs);
            sendResult(true, handler, context);
            return true;
        } catch (JSONException e) {
            e.printStackTrace();
            sendResult(false, handler, context);
            return false;
        }
    } else {
        sendResult(false, handler, context);
        return false;
    }

}

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 w  w  .jav  a 2s. com
                                }

                        );

                        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   w  ww .ja va2  s  . 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  va2s.  c o  m
    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;
}