Example usage for java.lang ClassCastException printStackTrace

List of usage examples for java.lang ClassCastException printStackTrace

Introduction

In this page you can find the example usage for java.lang ClassCastException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:com.sos.JSHelper.Options.JSOptionsClass.java

public StringBuffer IterateAllDataElementsByAnnotation(final Class<?> objC, final Object objP,
        final IterationTypes enuIterate4What, StringBuffer pstrBuffer) {
    final String conMethodName = conClassName + "::IterateAllDataElementsByAnnotation";
    String strCommandLineOptions = "";
    if (objC == null) {
        throw new JobSchedulerException(conMethodName + ": objSegment is null, but must be not null");
    }/*  www .j  av  a 2 s  .c  o m*/
    Field objField = null;
    SOSOptionElement.gflgProcessHashMap = true;
    try {
        final Field objFields[] = objC.getFields();
        final StringBuffer strXML = new StringBuffer("");
        final String strT = objC.getName();
        if (enuIterate4What == IterationTypes.createXML) {
            strXML.append("<" + strT + " id=" + XmlId.QuotedValue() + ">");
        }
        for (final Field objField2 : objFields) {
            objField = objField2;
            try {
                if (objField.isAnnotationPresent(JSOptionDefinition.class)) {
                    final SOSOptionElement objDE = (SOSOptionElement) objField.get(objP);
                    if (objDE == null) {
                        // final JSOptionsClass objO = (JSOptionsClass) objField.get(objField);
                        // if (objO != null) {
                        // System.out.println("oooooooField : " + objField.getName());
                        //
                        // this.IterateAllDataElementsByAnnotation(objO.getClass(), objO, enuIterate4What, pstrBuffer);
                        // }
                        // else {
                        // System.out.println("*******Field : " + objField.getName());
                        // final Object objO2 = objField.getDeclaringClass();
                        // System.out.println(objField.getType().toString());
                        // // objField.Iterate(enuIterate4What);
                        // // this.IterateAllDataElementsByAnnotation(objO.getClass(), objO, enuIterate4What, pstrBuffer);
                        // }
                    } else {
                        if (enuIterate4What == IterationTypes.setPrefix) {
                            objDE.setPrefix(strAlternativePrefix);
                        }
                        if (enuIterate4What == IterationTypes.setRecord) {
                            SOSOptionElement.gflgProcessHashMap = true;
                            objDE.gflgProcessHashMap = true;
                            objDE.MapValue();
                            // continue;
                        }
                        if (enuIterate4What == IterationTypes.getRecord) {
                            // objDE.BuildRecord(pstrBuffer);
                            // continue;
                        }
                        if (enuIterate4What == IterationTypes.CheckMandatory) {
                            objDE.CheckMandatory();
                        }
                        if (enuIterate4What == IterationTypes.toOut) {
                            System.out.println(objDE.toString());
                        }
                        if (enuIterate4What == IterationTypes.toString) {
                            pstrBuffer.append(objDE.toString() + "\n");
                        }
                        if (enuIterate4What == IterationTypes.DirtyToString) {
                            if (objDE.isDirty() == true) {
                                pstrBuffer.append(objDE.DirtyToString() + "\n");
                            }
                        }
                        if (enuIterate4What == IterationTypes.createXML) {
                            strXML.append(objDE.toXml());
                        }
                        if (enuIterate4What == IterationTypes.setDefaultValues) {
                            final String strV = objDE.Value();
                            if (strV.length() <= 0) {
                                objDE.Value(objDE.DefaultValue());
                            }
                            // continue;
                        }
                        if (enuIterate4What == IterationTypes.clearAllValues) {
                            objDE.Value("");
                            // continue;
                        }
                        if (enuIterate4What == IterationTypes.getCommandLine) {
                            pstrBuffer.append(objDE.toCommandLine());
                        }

                        if (enuIterate4What == IterationTypes.countSegmentFields) {
                            // System.out.println("+++++Field : " + objField.getName());
                        }
                        /**
                         * hier versuchen wir herauszubekommen, ob es
                         * in dieser Instanz (weitere) geschachtelte Optionen gibt.
                         * Falls ja, wird die geforderte Funktion auch fr alle diese
                         * Instanzen ausgefhrt.
                         */
                        IterateAllDataElementsByAnnotation(objDE.getClass(), objDE, enuIterate4What,
                                pstrBuffer);
                    }
                } // if (objField.isAnnotationPresent(IDocSegmentField.class))
            } // try
            catch (final ClassCastException objException) {
            } catch (final Exception objE) {
                objE.printStackTrace();
                throw new RuntimeException(objE);
            } finally {
                //
            } // finally
        }
        if (enuIterate4What == IterationTypes.createXML) { // CreateXML
            strXML.append("</" + strT + ">");
            pstrBuffer = strXML;
        }
    } catch (final Exception objException) {
        objException.printStackTrace();
        throw new RuntimeException(objException);
    } finally {
        SOSOptionElement.gflgProcessHashMap = false;
        //
    } // finally
    return pstrBuffer;
}

From source file:org.nightlabs.jfire.reporting.birt.layout.render.RenderManager.java

@Override
public RenderedReportLayout renderReport(PersistenceManager pm, RenderReportRequest renderRequest,
        String fileName, File layoutRoot, boolean prepareForTransfer) throws RenderReportException {
    ReportLayout reportLayout = null;/*w w w. j a v  a  2  s  . com*/
    try {
        reportLayout = (ReportLayout) pm.getObjectById(renderRequest.getReportRegistryItemID());
    } catch (ClassCastException e) {
        throw new IllegalArgumentException("The ReportRegistryItemID with id "
                + renderRequest.getReportRegistryItemID() + " is not of type ReportLayout.");
    }
    if (logger.isDebugEnabled())
        logger.debug("Rendering report " + reportLayout.getReportRegistryItemID() + " to outputformat: "
                + renderRequest.getOutputFormat());

    if (logger.isDebugEnabled())
        logger.debug("Have report engine");

    ServerResourceLocator.setCurrentReportLayout(reportLayout);
    try {

        InputStream inputStream = reportLayout.createReportDesignInputStream();
        IReportRunnable report = null;
        try {
            report = engine.openReportDesign(inputStream);
        } catch (EngineException e) {
            throw new RenderReportException(e);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
        if (logger.isDebugEnabled())
            logger.debug("Opened reportlayout, creating RunAndRenderTask");
        IRunAndRenderTask task = engine.createRunAndRenderTask(report);

        Locale locale = NLLocale.getDefault();
        if (renderRequest.getLocale() != null)
            locale = renderRequest.getLocale();
        else {
            // TODO: Add the users locale
        }

        task.setLocale((java.util.Locale) locale);

        if (logger.isDebugEnabled())
            logger.debug("Creating ReportLayoutRenderer");
        ReportLayoutRendererRegistry registry = ReportLayoutRendererRegistry.getReportRegistry(pm);
        ReportLayoutRenderer renderer = null;
        try {
            renderer = registry.createReportRenderer(renderRequest.getOutputFormat());
        } catch (Exception e) {
            throw new RenderReportException(
                    "Could not create ReportLayoutRenderer for OutputFormat " + renderRequest.getOutputFormat(),
                    e);
        }
        if (logger.isDebugEnabled())
            logger.debug("Have ReportLayoutRenderer: " + renderer.getClass().getName());

        HashMap<String, Object> parsedParams = parseReportParams(engine, report, renderRequest.getParameters());
        renderRequest.setParameters(parsedParams);

        if (logger.isDebugEnabled())
            logger.debug("Have report renderer, delegating render work");
        //         JFireReportingHelper.open(pm, false, parsedParams, locale, reportLayout);
        JFireReportingHelper.open(pm, false, reportLayout, renderRequest);
        RenderedReportLayout result = null;
        // Ask the renderer to do the work
        try {
            result = renderer.renderReport(pm, renderRequest, task, fileName, layoutRoot, prepareForTransfer);
        } catch (Exception e) {
            System.err.println("Caught RunAndRenderTask exception");
            e.printStackTrace();
            throw new RenderReportException("RunAndRenderTask aborted with errors",
                    ExceptionUtils.getRootCause(e));
        } finally {
            JFireReportingHelper.close();
        }
        // Check for rendering errors
        if (task.getErrors().size() > 0) {
            Collection<Throwable> errors = new ArrayList<Throwable>(task.getErrors().size());
            for (int i = 0; i < task.getErrors().size(); i++) {
                Throwable t = (Throwable) task.getErrors().get(0);
                String message = t.getMessage();
                if (message == null) {
                    message = t.getClass().getSimpleName();
                    logger.error("Render-excepton", t);
                }
                errors.add(new RenderReportException(message, t)); // Exception wrapped as some things contain non-serializable members.
            }
            result.getHeader().setRenderingErrors(errors);
        }
        return result;

    } finally {
        ServerResourceLocator.setCurrentReportLayout(null);
    }
}

From source file:guineu.modules.filter.Alignment.SerumHuNormalization.SerumHuNormalizationTask.java

private void normalize(Dataset data, Dataset newData) {
    // First row => ids of the samples ( 0 == standard serum, 1 == normal sample)
    this.ids = data.getRow(0).clone();

    // Second row => run order
    this.runOrder = data.getRow(0).clone();

    // Third row => different data sets
    this.batches = data.getRow(0).clone();

    for (String name : data.getAllColumnNames()) {
        ids.setPeak(name, data.getParametersValue(name, this.id));
        runOrder.setPeak(name, data.getParametersValue(name, this.order));
        batches.setPeak(name, data.getParametersValue(name, this.batchesName));
    }/*from   w w  w.  ja va2 s .  c  o m*/

    int numBatches = 1;
    double n = (Double) batches.getPeak(data.getAllColumnNames().get(0));

    for (String name : data.getAllColumnNames()) {
        if ((Double) batches.getPeak(name) > n) {
            numBatches++;
            n = (Double) batches.getPeak(name);
        }
    }

    this.createCurves(data, numBatches);
    for (int batch = 0; batch < numBatches; batch++) {
        message = "Normalizing";
        this.totalRows = data.getNumberRows();
        this.processedRows = 0;
        List<String> names = data.getAllColumnNames();
        for (int i = 0; i < data.getNumberRows(); i++) {
            this.processedRows++;
            PeakListRow row = data.getRow(i);
            PeakListRow newrow = newData.getRow(i);
            try {
                // Get the interpolation of all the human serum points using Loess 
                PolynomialSplineFunction function = functions.get(row.getID()).get(batch);

                if (function != null) {
                    // Prepare the points for the extrapolation
                    PolynomialFunction extrapolationFunction = null;
                    if (this.extrapolation) {
                        List<Double> points = new ArrayList<Double>();
                        for (int e = 0; e < row.getNumberPeaks(); e++) {
                            if ((Double) batches.getPeak(names.get(e)) == batch) {
                                try {
                                    points.add(function.value((Double) runOrder.getPeak(names.get(e))));
                                } catch (ArgumentOutsideDomainException ex) {
                                    Logger.getLogger(SerumHuNormalizationTask.class.getName()).log(Level.SEVERE,
                                            null, ex);
                                }
                            }
                        }

                        // Extrapolation function
                        extrapolationFunction = this.fittPolinomialFunction(batches, runOrder, names, batch,
                                points);
                    }
                    double lastPoint = 0;
                    for (int e = 0; e < row.getNumberPeaks(); e++) {
                        String sampleName = names.get(e);
                        if ((Double) ids.getPeak(sampleName) > 0.0) {
                            if ((Double) batches.getPeak(sampleName) == batch) {
                                try {

                                    if ((Double) ids.getPeak(sampleName) == 0) {
                                        lastPoint = function.value((Double) runOrder.getPeak(sampleName));
                                    }
                                    double value = 0;
                                    try {
                                        Double controlMol = function
                                                .value((Double) runOrder.getPeak(names.get(e)));
                                        if (controlMol < 0.0 || controlMol == Double.NaN
                                                || controlMol == Double.POSITIVE_INFINITY
                                                || controlMol == Double.NEGATIVE_INFINITY) {
                                            controlMol = getAverage(ids, row, e, names);
                                        }

                                        value = (Double) row.getPeak(sampleName) / controlMol;

                                        if (value < 0.0 || value == Double.NaN
                                                || value == Double.POSITIVE_INFINITY
                                                || value == Double.NEGATIVE_INFINITY) {
                                            controlMol = getAverage(ids, row, e, names);
                                        }

                                        value = (Double) row.getPeak(sampleName) / controlMol;
                                    } catch (ClassCastException exception) {
                                        value = -100;
                                    }
                                    newrow.setPeak(sampleName, value);
                                } catch (ArgumentOutsideDomainException ex) {
                                    // ex.printStackTrace();
                                    //if the value has to be extrapolated
                                    if (extrapolation && extrapolationFunction != null) {
                                        double value = 0;
                                        try {

                                            Double controlMol = extrapolationFunction
                                                    .value((Double) runOrder.getPeak(names.get(e)));
                                            if (controlMol < 0.0 || controlMol == Double.NaN
                                                    || controlMol == Double.POSITIVE_INFINITY
                                                    || controlMol == Double.NEGATIVE_INFINITY) {
                                                controlMol = getAverage(ids, row, e, names);
                                            }
                                            value = (Double) row.getPeak(sampleName) / controlMol;

                                            if (value < 0.0 || value == Double.NaN
                                                    || value == Double.POSITIVE_INFINITY
                                                    || value == Double.NEGATIVE_INFINITY) {
                                                controlMol = getAverage(ids, row, e, names);
                                            }

                                            value = (Double) row.getPeak(sampleName) / controlMol;
                                        } catch (ClassCastException exception) {
                                            value = -100;
                                        }
                                        newrow.setPeak(sampleName, value);
                                    } else {
                                        double value = 0;
                                        try {
                                            value = (Double) row.getPeak(sampleName) / lastPoint;//extrapolationFunction.value((Double) runOrder.getPeak(names.elementAt(e)));
                                        } catch (ClassCastException exception) {
                                            value = -100;
                                        }
                                        newrow.setPeak(sampleName, value);
                                    }

                                }
                            }
                        }
                    }
                } else {
                    System.out.println("Function is null" + row.getID());
                }
            } catch (Exception exception) {
                exception.printStackTrace();
                System.out.println(row.getID());

            }
        }
    }

}

From source file:org.aprilis.jrest.compile.Compile.java

/**
 * // w w w .  java  2 s. c o m
 * @param sJsonDef
 * @return
 */
@SuppressWarnings("unchecked")
private boolean loadJsonDefinition(String sJsonDef) {
    try {
        String commentsStrippedJson = sJsonDef.replaceAll(Constants.gsStripCommentLineRegEx,
                Constants.gsEmptyString);
        String newLineTrimmedJson = commentsStrippedJson.replaceAll(Constants.gsTrimFindeString,
                Constants.gsEmptyString);
        String spaceRemovedJson = newLineTrimmedJson.replaceAll(Constants.gsRemoveSpacesExcludingQuotes,
                Constants.gsEmptyString);

        mLogger.info(String.format(Exceptions.gsTrimmedJsonString, spaceRemovedJson));

        mhmapDefinitionDetails = (JSONObject) moJsonParser.parse(spaceRemovedJson);

        for (Map.Entry<String, HashMap<String, Object>> jsonEntry : mhmapDefinitionDetails.entrySet()) {
            // 1. Check whether definition key is valid (not null or empty) - Done
            // 2. Check whether value associated to key is valid (not null, since
            // its an
            // object) - Done
            //
            if (jsonEntry.getKey() != null && jsonEntry.getKey().length() >= Constants.gshMinDefinitionKeyLength
                    && jsonEntry.getValue() != null) {

                String sJsonKey = jsonEntry.getKey().toUpperCase();
                if ((sJsonKey.equals(Constants.gsAuthDefinitionKey) == true)
                        || (sJsonKey.equals(Constants.gsJdbcDefinitionKey) == true)) {
                    mLogger.warn(Exceptions.gsReservedKeywordNotAllowed);

                    continue;
                } // if ((sJsonKey.equals(Constants.gsAuthDefinitionKey) == true) ...
                  // )

                // 3. Check for mandatory keywords Type - Done
                //
                // if ( jsonEntry.getValue().containsKey(Constants.gsLangTokenQuery)
                // &&
                if (jsonEntry.getValue().containsKey(Constants.gsLangTokenType)) {

                    Definition apiDefinition = new Definition();

                    String sQueryType = jsonEntry.getValue().get(Constants.gsLangTokenType).toString().trim();

                    String sQueryValue = (String) jsonEntry.getValue().get(Constants.gsLangTokenQuery);
                    if ((sQueryType.equals(Constants.gsLangDefTypeGet)
                            || sQueryType.equals(Constants.gsLangDefTypeSet)) && sQueryValue == null) {
                        mLogger.error(Exceptions.gsMissingMandatoryKeywordsInDefFile);

                        return false;
                    }

                    if (sQueryValue != null) {
                        sQueryValue = jsonEntry.getValue().get(Constants.gsLangTokenQuery).toString().trim();

                        // 5. Check for value of keyword Query is not null or empty - Done
                        // 6. Check if Query value is terminated with a semicolon - Done
                        //
                        if (sQueryValue.length() > Constants.gshMinQueryLength) {
                            if (sQueryValue.charAt(
                                    sQueryValue.length() - Constants.gshOne) == Constants.gcDelimSemiColon) {
                                apiDefinition.setQuery(sQueryValue);
                            } else {
                                mLogger.error(Exceptions.gsQuerySyntaxError);

                                return false;
                            } // if (sQuery.charAt(sQuery.length() - Constants.gshOne) ==
                              // Constants.gcDelimSemiColon)
                        } else {
                            mLogger.error(Exceptions.gsEmptyOrInvalidQueryGiven);

                            return false;
                        } // end of if (sQueryValue != null && ... )
                    } // if (jsonEntry.getValue().get(Constants.gsLangTokenQuery) !=
                      // null)

                    // 9. Check for values of Before and After if they are mentioned -
                    // Done
                    //
                    if (jsonEntry.getValue().containsKey(Constants.gsLangTokenBefore)) {
                        try {
                            HashMap<String, String> hmapBeforeMapping = (JSONObject) jsonEntry.getValue()
                                    .get(Constants.gsLangTokenBefore);

                            if (loadJsonBeforeTagInfo(jsonEntry.getKey(), hmapBeforeMapping,
                                    apiDefinition) == false) {
                                return false;
                            } // if (loadJsonBeforeTagInfo(jsonEntry.getKey(), ... )
                        } catch (ClassCastException e) {
                            mLogger.error(String.format(Exceptions.gsMalformedDefinition,
                                    Constants.gsLangTokenBefore, jsonEntry.getKey()));

                            return false;
                        } // end of try ... catch block

                    } // end of
                      // if(jsonEntry.getValue().containsKey(Constants.gsLangTokenBefore))

                    if (jsonEntry.getValue().containsKey(Constants.gsLangTokenAfter)) {
                        try {
                            HashMap<String, String> hmapAfterMapping = (JSONObject) jsonEntry.getValue()
                                    .get(Constants.gsLangTokenAfter);

                            if (loadJsonAfterTagInfo(jsonEntry.getKey(), hmapAfterMapping,
                                    apiDefinition) == false) {
                                return false;
                            } // if (loadJsonAfterTagInfo(jsonEntry.getKey(), ... )
                        } catch (ClassCastException e) {
                            mLogger.error(String.format(Exceptions.gsMalformedDefinition,
                                    Constants.gsLangTokenAfter, jsonEntry.getKey()));

                            return false;
                        } // end of try ... catch block
                    } // end of if
                      // (jsonEntry.getValue().containsKey(Constants.gsLangTokenAfter))

                    loadRoles(jsonEntry.getKey(), (JSONObject) jsonEntry.getValue(), apiDefinition);

                    // 6. Check for value of keyword Type is either GET or SET or Upload
                    if (sQueryType != null) {
                        if (sQueryType.equals(Constants.gsLangDefTypeGet)) {
                            moStore.addGetDefinition(jsonEntry.getKey(), apiDefinition);
                        } else if (sQueryType.equals(Constants.gsLangDefTypeSet)) {
                            moStore.addSetDefinition(jsonEntry.getKey(), apiDefinition);
                        } else {
                            mLogger.error(Exceptions.gsInvalidDefinitionTypeGiven);

                            return false;
                        } // end of if (defType.equals(Constants.gsLangDefTypeGet))

                        return true;
                    } // if(jsonEntry.getValue().containsKey(Constants.gsLangTokenType))
                } else {
                    mLogger.error(Exceptions.gsMissingMandatoryKeywordsInDefFile);
                } // end of if
                  // (jsonEntry.getValue().containsKey(Constants.gsLangTokenQuery)
            } else {
                mLogger.error(Exceptions.gsEmptyDefinition);
            } // end of if (jsonEntry.getKey() != null && .... )
        } // for (Map.Entry<String, HashMap<String, Object>> jsonEntry
    } catch (Exception e) {
        e.printStackTrace();

        e.printStackTrace(moPrintWriter);

        mLogger.error(moStringWriter.toString());
    } // end of try ... catch block

    return false;
}

From source file:git.egatuts.nxtremotecontroller.fragment.OnlineControllerFragment.java

public void startSocketConnection() {
    final OnlineControllerFragment self = this;
    final GlobalUtils globalUtils = this.getGlobalUtils();
    if (this.socket != null && this.socket.connected()) {
        return;//  ww w . jav a 2s  . c o  m
    }
    this.progressDialog.show();
    this.progressDialog.setText(R.string.connecting_socket_server);
    String url = this.getPreferencesEditor().getString("preference_server_address",
            this.getString(R.string.preference_value_address));
    Uri uri = Uri.parse(url).buildUpon().appendQueryParameter("token", this.token).build();
    try {
        if (url.contains("https://")) {
            IO.setDefaultSSLContext(SSLContext.getDefault());
        }
        IO.Options options = new IO.Options();
        options.forceNew = true;
        options.reconnection = true;
        this.socket = IO.socket(uri.toString(), options);

        /*
         *  When the socket is connected.
         */
        socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                self.removeAllClients();
                self.progressDialog.dismiss();
            }

            /*
             *  When the socket is disconnected.
             */
        }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                self.removeAllClients();
            }

            /*
             *  When the socket receives an error.
             */
        }).on(Socket.EVENT_ERROR, new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                try {
                    String error = (String) args[0];
                    if (error.contains("JsonWebToken") || error.contains("TokenExpiredError")) {
                        self.getBaseActivity().getPreferencesEditor().saveString("preference_server_token", "");
                        globalUtils.showToast(R.string.restoring_token);
                        self.refreshFragment();
                        return;
                    }
                } catch (ClassCastException e) {
                    //e.printStackTrace();
                }
                self.progressDialog.dismiss();
                globalUtils.showToast(R.string.unknown_error);
            }

            /*
             *  When a new client is disconnected.
             */
        }).on("leave_member", new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                try {
                    JSONObject members = ((JSONObject) args[0]).getJSONObject("members");
                    Iterator<String> membersList = members.keys();
                    while (membersList.hasNext()) {
                        String id = membersList.next();
                        Client client = Client.fromJSON(members.getJSONObject(id));
                        client.setId(id);
                        final int index = self.clientsAdapter.exists(client);
                        if (index == -1) {
                            continue;
                        }
                        if (self.calling != null
                                && self.calling.equals(self.clientsAdapter.get(index).getPeerId())) {
                            self.hideActions();
                            self.calling = "";
                            self.controlledBy = null;
                            self.getConnector().motorBC(0, 0, false, false);
                        }
                        self.getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                self.clientsAdapter.remove(index);
                            }
                        });
                    }
                } catch (JSONException e) {
                    //e.printStackTrace();
                }
            }

            /*
             *  When a new client is connected (also fired on first connection with all the active clients)
             */
        }).on("join_member", new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                try {
                    JSONObject members = ((JSONObject) args[0]).getJSONObject("members");
                    Iterator<String> membersList = members.keys();
                    while (membersList.hasNext()) {
                        String id = membersList.next();
                        JSONObject member = members.getJSONObject(id);
                        final Client client = Client.fromJSON(member);
                        client.setId(id);
                        if (self.clientsAdapter.exists(client) > -1) {
                            continue;
                        }
                        self.getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                self.clientsAdapter.add(client);
                            }
                        });
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            /*
             *  When the client has answered our call request.
             */
        }).on("answered", new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                self.progressDialog.dismiss();
                try {
                    JSONObject data = (JSONObject) args[0];
                    String from = data.getString("from");
                    boolean accepted = data.getBoolean("state");
                    if (from.equals(self.calling)) {
                        globalUtils.showToast(accepted ? R.string.call_accepted : R.string.call_rejected);
                        if (accepted) {
                            self.controlledBy = self.clientsAdapter.getByPeer(from);
                            self.showActions();
                        }
                    }
                } catch (JSONException e) {
                    //e.printStackTrace();
                }
            }

            /*
             *  When the client sends us a motor order.
             */
        }).on("motors", new Emitter.Listener() {
            @Override
            public void call(Object... args) {
                try {
                    JSONObject data = (JSONObject) args[0];
                    String sender = data.getString("from");
                    if (!sender.equals(self.controlledBy.getPeerId()))
                        return;
                    double b = data.getDouble("b");
                    double c = data.getDouble("c");
                    self.getConnector().motorBC(c, b, false, false);
                } catch (JSONException e) {
                    //e.printStackTrace();
                }
            }
        });/*.on("flash", new Emitter.Listener() {
           @Override
           public void call (Object... args) {
            try {
              JSONObject data = (JSONObject) args[0];
              String sender = data.getString("from");
              boolean state = data.getBoolean("state");
              if (!sender.equals(self.controlledBy.getPeerId())) return;
              if (!globalUtils.isFlashAvailable()) return;
              Camera camera = Camera.open();
              Camera.Parameters parameters = camera.getParameters();
              parameters.setFlashMode(state ? Camera.Parameters.FLASH_MODE_ON : Camera.Parameters.FLASH_MODE_OFF);
              camera.setParameters(parameters);
              camera.startPreview();
            } catch (JSONException e) {
              e.printStackTrace();
            }
           }
           });*/
        socket.connect();
    } catch (URISyntaxException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        // We are fucked if this ends here!
    }
}

From source file:com.zoho.creator.jframework.JSONParser.java

static List<ZCChoice> parseCrmLookupChoices(String response, ZCRecordValue zcRecordValue) {

    String moduleType = zcRecordValue.getField().getModuleType();
    List<ZCChoice> choices = new ArrayList<ZCChoice>();
    try {/*from   w w w. j  a  v a2 s . c  o m*/
        JSONObject resObj = new JSONObject(response);
        if (moduleType.equalsIgnoreCase("users")) {
            if (resObj.has("users")) {
                JSONObject usersObj = (JSONObject) resObj.get("users");
                if (usersObj.has("user")) {
                    try {
                        JSONArray jarray = (JSONArray) usersObj.get("user");
                        for (int i = 0; i < jarray.length(); i++) {
                            JSONObject jObj = jarray.getJSONObject(i);
                            parseUserModuleInternalObj(choices, jObj);
                        }
                    } catch (ClassCastException e) {
                        JSONObject jObj = (JSONObject) usersObj.get("user");
                        parseUserModuleInternalObj(choices, jObj);
                    }
                }
            }
        } else {
            if (resObj.has("response")) {
                JSONObject resultObj = (JSONObject) resObj.get("response");
                if (resultObj.has("result")) {
                    JSONObject modObj = (JSONObject) resultObj.get("result");
                    if (modObj.has(moduleType)) {
                        JSONObject rowObj = (JSONObject) modObj.get(moduleType);
                        if (rowObj.has("row")) {
                            if (moduleType.equals("Leads")) {
                                try {
                                    JSONArray rowArray = (JSONArray) rowObj.get("row");

                                    for (int i = 0; i < rowArray.length(); i++) {
                                        JSONObject rowArrayObj = rowArray.getJSONObject(i);
                                        parseCrmLeadModule(choices, rowArrayObj);
                                    }
                                } catch (ClassCastException e) {
                                    JSONObject jObj = (JSONObject) rowObj.get("row");
                                    parseCrmLeadModule(choices, jObj);
                                }
                            } else if (moduleType.equals("Accounts")) {
                                try {
                                    JSONArray rowArray = (JSONArray) rowObj.get("row");
                                    for (int i = 0; i < rowArray.length(); i++) {
                                        JSONObject rowArrayObj = rowArray.getJSONObject(i);
                                        parseCrmAccountsModule(choices, rowArrayObj);
                                    }
                                } catch (ClassCastException e) {
                                    JSONObject jObj = (JSONObject) rowObj.get("row");
                                    parseCrmAccountsModule(choices, jObj);
                                }

                            } else if (moduleType.equals("Potentials")) {
                                try {
                                    JSONArray rowArray = (JSONArray) rowObj.get("row");
                                    for (int i = 0; i < rowArray.length(); i++) {
                                        JSONObject rowArrayObj = rowArray.getJSONObject(i);
                                        parseCrmPotentialsModule(choices, rowArrayObj);
                                    }
                                } catch (ClassCastException e) {
                                    JSONObject jObj = (JSONObject) rowObj.get("row");
                                    parseCrmPotentialsModule(choices, jObj);
                                }

                            } else if (moduleType.equals("Contacts")) {
                                try {
                                    JSONArray rowArray = (JSONArray) rowObj.get("row");
                                    for (int i = 0; i < rowArray.length(); i++) {
                                        JSONObject rowArrayObj = rowArray.getJSONObject(i);
                                        parseCrmContactsModule(choices, rowArrayObj);
                                    }
                                } catch (ClassCastException e) {
                                    JSONObject jObj = (JSONObject) rowObj.get("row");
                                    parseCrmContactsModule(choices, jObj);
                                }

                            } else if (moduleType.equals("Campaigns")) {
                                try {
                                    JSONArray rowArray = (JSONArray) rowObj.get("row");
                                    for (int i = 0; i < rowArray.length(); i++) {
                                        JSONObject rowArrayObj = rowArray.getJSONObject(i);
                                        parseCrmCampaignsModule(choices, rowArrayObj);
                                    }
                                } catch (ClassCastException e) {
                                    JSONObject jObj = (JSONObject) rowObj.get("row");
                                    parseCrmCampaignsModule(choices, jObj);
                                }

                            } else if (moduleType.equals("Cases")) {
                                try {
                                    JSONArray rowArray = (JSONArray) rowObj.get("row");
                                    for (int i = 0; i < rowArray.length(); i++) {
                                        JSONObject rowArrayObj = rowArray.getJSONObject(i);
                                        parseCrmCasesModule(choices, rowArrayObj);
                                    }
                                } catch (ClassCastException e) {
                                    JSONObject jObj = (JSONObject) rowObj.get("row");
                                    parseCrmCasesModule(choices, jObj);
                                }

                            } else if (moduleType.equals("Solutions")) {
                                try {
                                    JSONArray rowArray = (JSONArray) rowObj.get("row");
                                    for (int i = 0; i < rowArray.length(); i++) {
                                        JSONObject rowArrayObj = rowArray.getJSONObject(i);
                                        parseCrmSolutionsModule(choices, rowArrayObj);
                                    }
                                } catch (ClassCastException e) {
                                    JSONObject jObj = (JSONObject) rowObj.get("row");
                                    parseCrmSolutionsModule(choices, jObj);
                                }

                            } else if (moduleType.equals("Products")) {
                                try {
                                    JSONArray rowArray = (JSONArray) rowObj.get("row");
                                    for (int i = 0; i < rowArray.length(); i++) {
                                        JSONObject rowArrayObj = rowArray.getJSONObject(i);
                                        parseCrmProductsModule(choices, rowArrayObj);
                                    }
                                } catch (ClassCastException e) {
                                    JSONObject jObj = (JSONObject) rowObj.get("row");
                                    parseCrmProductsModule(choices, jObj);
                                }

                            } else if (moduleType.equals("PriceBooks")) {
                                try {
                                    JSONArray rowArray = (JSONArray) rowObj.get("row");
                                    for (int i = 0; i < rowArray.length(); i++) {
                                        JSONObject rowArrayObj = rowArray.getJSONObject(i);
                                        parseCrmPriceBooksModule(choices, rowArrayObj);
                                    }
                                } catch (ClassCastException e) {
                                    JSONObject jObj = (JSONObject) rowObj.get("row");
                                    parseCrmPriceBooksModule(choices, jObj);
                                }

                            } else if (moduleType.equals("Quotes")) {
                                try {
                                    JSONArray rowArray = (JSONArray) rowObj.get("row");
                                    for (int i = 0; i < rowArray.length(); i++) {
                                        JSONObject rowArrayObj = rowArray.getJSONObject(i);
                                        parseCrmQuotesModule(choices, rowArrayObj);
                                    }
                                } catch (ClassCastException e) {
                                    JSONObject jObj = (JSONObject) rowObj.get("row");
                                    parseCrmQuotesModule(choices, jObj);
                                }

                            } else if (moduleType.equals("Vendors")) {
                                try {
                                    JSONArray rowArray = (JSONArray) rowObj.get("row");
                                    for (int i = 0; i < rowArray.length(); i++) {
                                        JSONObject rowArrayObj = rowArray.getJSONObject(i);
                                        parseCrmVendorsModule(choices, rowArrayObj);
                                    }
                                } catch (ClassCastException e) {
                                    JSONObject jObj = (JSONObject) rowObj.get("row");
                                    parseCrmVendorsModule(choices, jObj);
                                }

                            } else if (moduleType.equals("PurchaseOrders")) {
                                try {
                                    JSONArray rowArray = (JSONArray) rowObj.get("row");
                                    for (int i = 0; i < rowArray.length(); i++) {
                                        JSONObject rowArrayObj = rowArray.getJSONObject(i);
                                        parseCrmPurchaseOrdersModule(choices, rowArrayObj);
                                    }
                                } catch (ClassCastException e) {
                                    JSONObject jObj = (JSONObject) rowObj.get("row");
                                    parseCrmPurchaseOrdersModule(choices, jObj);
                                }

                            } else if (moduleType.equals("SalesOrders")) {
                                try {
                                    JSONArray rowArray = (JSONArray) rowObj.get("row");
                                    for (int i = 0; i < rowArray.length(); i++) {
                                        JSONObject rowArrayObj = rowArray.getJSONObject(i);
                                        parseCrmSalesOrdersModule(choices, rowArrayObj);
                                    }
                                } catch (ClassCastException e) {
                                    JSONObject jObj = (JSONObject) rowObj.get("row");
                                    parseCrmSalesOrdersModule(choices, jObj);
                                }

                            } else if (moduleType.equals("Invoices")) {
                                try {
                                    JSONArray rowArray = (JSONArray) rowObj.get("row");
                                    for (int i = 0; i < rowArray.length(); i++) {
                                        JSONObject rowArrayObj = rowArray.getJSONObject(i);
                                        parseCrmInvoicesModule(choices, rowArrayObj);
                                    }
                                } catch (ClassCastException e) {
                                    JSONObject jObj = (JSONObject) rowObj.get("row");
                                    parseCrmInvoicesModule(choices, jObj);
                                }

                            }
                        }
                    }
                }
            }
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return choices;
}