Example usage for java.lang IllegalArgumentException printStackTrace

List of usage examples for java.lang IllegalArgumentException printStackTrace

Introduction

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

Prototype

public void printStackTrace() 

Source Link

Document

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

Usage

From source file:com.ifoer.expeditionphone.MainActivity.java

public void onDestroy() {
    SimpleDialog.closeProgressDialog(this.progressDialog);
    super.onDestroy();
    if (this.service != null) {
        stopService(this.service);
    }/*w  w  w.  j a va  2s  .  c o  m*/
    try {
        if (this.receiver != null) {
            unregisterReceiver(this.receiver);
        }
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }
    this.mChinaBaseDiagAdapter = null;
    this.mAsiaBaseDiagAdapter = null;
    this.mEuroBaseDiagAdapter = null;
    this.mAmericaBaseDiagAdapter = null;
}

From source file:jdbc.pool.JDBCPoolMySQLTest.java

public void testGetInstanceStringFile1() {
    logger.debug("testGetInstanceStringFile1 Start");
    try {//from  ww  w  . j  a v  a 2  s  . c o m
        try {
            CConnectionPoolManager.getInstance();
            logger.debug("Instance is created. WRONG");
        } catch (IllegalArgumentException e) {
            logger.debug("Instance is not created. Alright");
        }
        CConnectionPoolManager manager = CConnectionPoolManager
                .getInstance("E:/Mastek/workspace/jdbcpool/config/log4j.properties", new File(
                        "C:/Documents and Settings/kedarr/workspace/jdbcpool/config/pool1245645558888.properties"));
        logger.debug("It came here Kedar in trouble" + manager);
        fail("getInstance(invalid data) was supposed to throw Configuration exception but did not.");
    } catch (IllegalArgumentException e) {
        assertTrue("Caught IllegalArgumentException", true);
    } catch (ConfigurationException e) {
        e.printStackTrace();
        fail("Caught ConfigurationException");
    } catch (ParseException e) {
        e.printStackTrace();
        fail("Caught ParseException");
    } catch (IOException e) {
        e.printStackTrace();
        fail("Caught IOException");
    } catch (SQLException e) {
        e.printStackTrace();
        fail("Caught SQLException");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        fail("Caught ClassNotFoundException");
    }
    logger.debug("testGetInstanceStringFile1 end");
}

From source file:hex.Model.java

public boolean testJavaScoring(Frame data, Frame model_predictions, EasyPredictModelWrapper.Config config,
        double rel_epsilon, double abs_epsilon, double fraction) {
    ModelBuilder mb = ModelBuilder.make(_parms.algoName().toLowerCase(), null, null);
    boolean havePojo = mb.havePojo();
    boolean haveMojo = mb.haveMojo();

    Random rnd = RandomUtils.getRNG(data.byteSize());
    assert data.numRows() == model_predictions.numRows();
    Frame fr = new Frame(data);
    boolean computeMetrics = data.vec(_output.responseName()) != null
            && !data.vec(_output.responseName()).isBad();
    try {//from   ww  w.  j  a  v  a 2 s  .  c om
        String[] warns = adaptTestForTrain(fr, true, computeMetrics);
        if (warns.length > 0)
            System.err.println(Arrays.toString(warns));

        // Output is in the model's domain, but needs to be mapped to the scored
        // dataset's domain.
        int[] omap = null;
        if (_output.isClassifier()) {
            Vec actual = fr.vec(_output.responseName());
            String[] sdomain = actual == null ? null : actual.domain(); // Scored/test domain; can be null
            String[] mdomain = model_predictions.vec(0).domain(); // Domain of predictions (union of test and train)
            if (sdomain != null && !Arrays.equals(mdomain, sdomain)) {
                omap = CategoricalWrappedVec.computeMap(mdomain, sdomain); // Map from model-domain to scoring-domain
            }
        }

        String modelName = JCodeGen.toJavaId(_key.toString());
        boolean preview = false;
        GenModel genmodel = null;
        Vec[] dvecs = fr.vecs();
        Vec[] pvecs = model_predictions.vecs();
        double[] features = null;
        int num_errors = 0;
        int num_total = 0;

        // First try internal POJO via fast double[] API
        if (havePojo) {
            try {
                String java_text = toJava(preview, true);
                Class clz = JCodeGen.compile(modelName, java_text);
                genmodel = (GenModel) clz.newInstance();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
                return true;
            } catch (Exception e) {
                e.printStackTrace();
                throw H2O.fail("Internal POJO compilation failed", e);
            }

            // Check that POJO has the expected interfaces
            for (Class<?> clz : getPojoInterfaces())
                if (!clz.isInstance(genmodel))
                    throw new IllegalStateException("POJO is expected to implement interface " + clz.getName());

            // Check some model metadata
            assert _output.responseName() == null || _output.responseName().equals(genmodel.getResponseName());

            features = MemoryManager.malloc8d(genmodel.nfeatures());
            double[] predictions = MemoryManager.malloc8d(genmodel.nclasses() + 1);

            // Compare predictions, counting mis-predicts
            for (int row = 0; row < fr.numRows(); row++) { // For all rows, single-threaded
                if (rnd.nextDouble() >= fraction)
                    continue;
                num_total++;

                // Native Java API
                for (int col = 0; col < features.length; col++) // Build feature set
                    features[col] = dvecs[col].at(row);
                genmodel.score0(features, predictions); // POJO predictions
                for (int col = _output.isClassifier() ? 1 : 0; col < pvecs.length; col++) { // Compare predictions
                    double d = pvecs[col].at(row); // Load internal scoring predictions
                    if (col == 0 && omap != null)
                        d = omap[(int) d]; // map categorical response to scoring domain
                    if (!MathUtils.compare(predictions[col], d, abs_epsilon, rel_epsilon)) {
                        if (num_errors++ < 10)
                            System.err.println("Predictions mismatch, row " + row + ", col "
                                    + model_predictions._names[col] + ", internal prediction=" + d
                                    + ", POJO prediction=" + predictions[col]);
                        break;
                    }
                }
            }
        }

        // EasyPredict API with POJO and/or MOJO
        for (int i = 0; i < 2; ++i) {
            if (i == 0 && !havePojo)
                continue;
            if (i == 1 && !haveMojo)
                continue;
            if (i == 1) { // MOJO
                final String filename = modelName + ".zip";
                StreamingSchema ss = new StreamingSchema(getMojo(), filename);
                try {
                    FileOutputStream os = new FileOutputStream(ss.getFilename());
                    ss.getStreamWriter().writeTo(os);
                    os.close();
                    genmodel = MojoModel.load(filename);
                    features = MemoryManager.malloc8d(genmodel._names.length);
                } catch (IOException e1) {
                    e1.printStackTrace();
                    throw H2O.fail("Internal MOJO loading failed", e1);
                } finally {
                    boolean deleted = new File(filename).delete();
                    if (!deleted)
                        Log.warn("Failed to delete the file");
                }
            }

            EasyPredictModelWrapper epmw = new EasyPredictModelWrapper(
                    config.setModel(genmodel).setConvertUnknownCategoricalLevelsToNa(true));
            RowData rowData = new RowData();
            BufferedString bStr = new BufferedString();
            for (int row = 0; row < fr.numRows(); row++) { // For all rows, single-threaded
                if (rnd.nextDouble() >= fraction)
                    continue;

                // Generate input row
                for (int col = 0; col < features.length; col++) {
                    if (dvecs[col].isString()) {
                        rowData.put(genmodel._names[col], dvecs[col].atStr(bStr, row).toString());
                    } else {
                        double val = dvecs[col].at(row);
                        rowData.put(genmodel._names[col],
                                genmodel._domains[col] == null ? (Double) val
                                        : Double.isNaN(val) ? val // missing categorical values are kept as NaN, the score0 logic passes it on to bitSetContains()
                                                : (int) val < genmodel._domains[col].length
                                                        ? genmodel._domains[col][(int) val]
                                                        : "UnknownLevel"); //unseen levels are treated as such
                    }
                }

                // Make a prediction
                AbstractPrediction p;
                try {
                    p = epmw.predict(rowData);
                } catch (PredictException e) {
                    num_errors++;
                    if (num_errors < 20) {
                        System.err.println("EasyPredict threw an exception when predicting row " + rowData);
                        e.printStackTrace();
                    }
                    continue;
                }

                // Convert model predictions and "internal" predictions into the same shape
                double[] expected_preds = new double[pvecs.length];
                double[] actual_preds = new double[pvecs.length];
                for (int col = 0; col < pvecs.length; col++) { // Compare predictions
                    double d = pvecs[col].at(row); // Load internal scoring predictions
                    if (col == 0 && omap != null)
                        d = omap[(int) d]; // map categorical response to scoring domain
                    double d2 = Double.NaN;
                    switch (genmodel.getModelCategory()) {
                    case AutoEncoder:
                        d2 = ((AutoEncoderModelPrediction) p).reconstructed[col];
                        break;
                    case Clustering:
                        d2 = ((ClusteringModelPrediction) p).cluster;
                        break;
                    case Regression:
                        d2 = ((RegressionModelPrediction) p).value;
                        break;
                    case Binomial:
                        BinomialModelPrediction bmp = (BinomialModelPrediction) p;
                        d2 = (col == 0) ? bmp.labelIndex : bmp.classProbabilities[col - 1];
                        break;
                    case Multinomial:
                        MultinomialModelPrediction mmp = (MultinomialModelPrediction) p;
                        d2 = (col == 0) ? mmp.labelIndex : mmp.classProbabilities[col - 1];
                        break;
                    case DimReduction:
                        d2 = ((DimReductionModelPrediction) p).dimensions[col];
                        break;
                    }
                    expected_preds[col] = d;
                    actual_preds[col] = d2;
                }

                // Verify the correctness of the prediction
                num_total++;
                for (int col = genmodel.isClassifier() ? 1 : 0; col < pvecs.length; col++) {
                    if (!MathUtils.compare(actual_preds[col], expected_preds[col], abs_epsilon, rel_epsilon)) {
                        num_errors++;
                        if (num_errors < 20) {
                            System.err.println((i == 0 ? "POJO" : "MOJO")
                                    + " EasyPredict Predictions mismatch for row " + row + ":" + rowData);
                            System.err.println("  Expected predictions: " + Arrays.toString(expected_preds));
                            System.err.println("  Actual predictions:   " + Arrays.toString(actual_preds));
                            System.err
                                    .println("Difference: " + Math.abs(expected_preds[expected_preds.length - 1]
                                            - actual_preds[actual_preds.length - 1]));
                        }
                        break;
                    }
                }
            }
        }
        if (num_errors != 0)
            System.err.println(
                    "Number of errors: " + num_errors + (num_errors > 20 ? " (only first 20 are shown)" : "")
                            + " out of " + num_total + " rows tested.");
        return num_errors == 0;
    } finally {
        Frame.deleteTempFrameAndItsNonSharedVecs(fr, data); // Remove temp keys.
    }
}

From source file:cn.com.zhenshiyin.crowd.net.AsyncHttpPost.java

@Override
public void run() {
    String ret = "";
    try {//from   ww  w  .j  a  v  a  2  s.  c  o  m
        request = new HttpPost(url);
        if (Constants.isGzip) {
            request.addHeader("Accept-Encoding", "gzip");
        } else {
            request.addHeader("Accept-Encoding", "default");
        }
        LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost  request to url :" + url);

        if (parameter != null && parameter.size() > 0) {
            List<BasicNameValuePair> list = new ArrayList<BasicNameValuePair>();
            for (RequestParameter p : parameter) {
                list.add(new BasicNameValuePair(p.getName(), p.getValue()));
            }
            ((HttpPost) request).setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
        }
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout);
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout);
        HttpResponse response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            InputStream is = response.getEntity().getContent();
            BufferedInputStream bis = new BufferedInputStream(is);
            bis.mark(2);
            // ??
            byte[] header = new byte[2];
            int result = bis.read(header);
            // reset??
            bis.reset();
            // ?GZIP?
            int headerData = getShort(header);
            // Gzip ? ? 0x1f8b
            if (result != -1 && headerData == 0x1f8b) {
                LogUtil.d("HttpTask", " use GZIPInputStream  ");
                is = new GZIPInputStream(bis);
            } else {
                LogUtil.d("HttpTask", " not use GZIPInputStream");
                is = bis;
            }
            InputStreamReader reader = new InputStreamReader(is, "utf-8");
            char[] data = new char[100];
            int readSize;
            StringBuffer sb = new StringBuffer();
            while ((readSize = reader.read(data)) > 0) {
                sb.append(data, 0, readSize);
            }
            ret = sb.toString();
            bis.close();
            reader.close();

        } else {
            RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                    "??,??" + statusCode);
            ret = ErrorUtil.errorJson("ERROR.HTTP.001", exception.getMessage());
        }

        LogUtil.d(AsyncHttpPost.class.getName(), "AsyncHttpPost  request to url :" + url + "  finished !");
    } catch (java.lang.IllegalArgumentException e) {
        RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.002", exception.getMessage());
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (org.apache.http.conn.ConnectTimeoutException e) {
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.003", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (java.net.SocketTimeoutException e) {
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.004", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        RequestException exception = new RequestException(RequestException.UNSUPPORTED_ENCODEING_EXCEPTION,
                "?");
        ret = ErrorUtil.errorJson("ERROR.HTTP.005", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  UnsupportedEncodingException  " + e.getMessage());
    } catch (org.apache.http.conn.HttpHostConnectException e) {
        RequestException exception = new RequestException(RequestException.CONNECT_EXCEPTION, "");
        ret = ErrorUtil.errorJson("ERROR.HTTP.006", exception.getMessage());
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  HttpHostConnectException  " + e.getMessage());
    } catch (ClientProtocolException e) {
        RequestException exception = new RequestException(RequestException.CLIENT_PROTOL_EXCEPTION,
                "??");
        ret = ErrorUtil.errorJson("ERROR.HTTP.007", exception.getMessage());
        e.printStackTrace();
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  ClientProtocolException " + e.getMessage());
    } catch (IOException e) {
        RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "??");
        ret = ErrorUtil.errorJson("ERROR.HTTP.008", exception.getMessage());
        e.printStackTrace();
        LogUtil.d(AsyncHttpPost.class.getName(),
                "AsyncHttpPost  request to url :" + url + "  IOException  " + e.getMessage());
    } finally {
        if (!Constants.IS_STOP_REQUEST) {
            Message msg = new Message();
            msg.obj = ret;
            LogUtil.d("", ret);
            msg.getData().putSerializable("callback", callBack);
            resultHandler.sendMessage(msg);
        }
        //
        if (customLoadingDialog != null && customLoadingDialog.isShowing()) {
            customLoadingDialog.dismiss();
            customLoadingDialog = null;
        }
    }
    super.run();
}

From source file:com.kimbrelk.da.oauth2.OAuth2.java

public final Response requestAuthToken(AuthGrantType grantType, String code, String redirectUri) {
    Map<String, String> params = new HashMap<String, String>();
    params.put("client_id", mClientCredentials.getId() + "");
    params.put("client_secret", mClientCredentials.getSecret());
    params.put("grant_type", grantType.toString().toLowerCase());
    switch (grantType) {
    case CLIENT_CREDENTIALS: {
        break;/*ww w . j  av a  2  s. c  o m*/
    }
    case AUTHORIZATION_CODE: {
        if (code == null) {
            throw new InvalidParameterException("Parameter code cannot be null when using the CODE grantType.");
        }
        if (redirectUri == null) {
            throw new InvalidParameterException(
                    "Parameter redirectUri cannot be null when using the CODE grantType.");
        }
        params.put("code", code);
        params.put("redirect_uri", redirectUri);
        break;
    }
    case REFRESH_TOKEN: {
        if (code == null) {
            throw new InvalidParameterException(
                    "Parameter code cannot be null when using the REFRESH_TOKEN grantType.");
        }
        params.put("refresh_token", code);
        break;
    }
    default: {
        throw new InvalidParameterException("Unsupported grantType: " + grantType);
    }
    }

    JSONObject json = requestJSON(Verb.GET, createURL(ENDPOINTS.OAUTH2_TOKEN, params));
    Response response = null;
    try {
        if (json.getString("status").equalsIgnoreCase("error")) {
            response = new RespError(json);
        } else {
            if (grantType == AuthGrantType.CLIENT_CREDENTIALS) {
                response = new RespToken(json.getInt("expires_in"), json.getString("access_token"), null);
            } else {
                String[] parse = json.getString("scope").replace(".", "_").toUpperCase().split("[ ]+");
                Scope scopes[] = new Scope[parse.length];
                for (int a = 0; a < parse.length; a++) {
                    try {
                        scopes[a] = Scope.valueOf(parse[a]);
                    } catch (IllegalArgumentException e) {
                        scopes[a] = null;
                        e.printStackTrace();
                    }
                }
                response = new RespToken(json.getInt("expires_in"), json.getString("access_token"),
                        json.getString("refresh_token"), scopes);
            }
            mToken = (RespToken) response;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    return response;
}

From source file:com.pipi.studio.dev.net.AsyncHttpGet.java

@Override
public void run() {
    String ret = "";
    try {//w  w  w.  j a v a2s  .c  o m
        if (parameter != null && parameter.size() > 0) {
            StringBuilder bulider = new StringBuilder();
            for (RequestParameter p : parameter) {
                if (bulider.length() != 0) {
                    bulider.append("&");
                }

                bulider.append(Utils.encode(p.getName()));
                bulider.append("=");
                bulider.append(Utils.encode(p.getValue()));
            }
            url += "?" + bulider.toString();
        }
        LogUtil.d(AsyncHttpGet.class.getName(), "AsyncHttpGet  request to url :" + url);
        request = new HttpGet(url);
        /*if(Constants.isGzip){
        request.addHeader("Accept-Encoding", "gzip");
          }else{
        request.addHeader("Accept-Encoding", "default");
          }*/
        //  
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout);
        // ? 
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout);
        HttpResponse response = httpClient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            InputStream is = response.getEntity().getContent();
            BufferedInputStream bis = new BufferedInputStream(is);
            bis.mark(2);
            // ??
            byte[] header = new byte[2];
            int result = bis.read(header);
            // reset??
            bis.reset();
            // ?GZIP?
            int headerData = getShort(header);
            // Gzip ? ? 0x1f8b
            if (result != -1 && headerData == 0x1f8b) {
                LogUtil.d("HttpTask", " use GZIPInputStream  ");
                is = new GZIPInputStream(bis);
            } else {
                LogUtil.d("HttpTask", " not use GZIPInputStream");
                is = bis;
            }
            InputStreamReader reader = new InputStreamReader(is, "utf-8");
            char[] data = new char[100];
            int readSize;
            StringBuffer sb = new StringBuffer();
            while ((readSize = reader.read(data)) > 0) {
                sb.append(data, 0, readSize);
            }
            ret = sb.toString();
            bis.close();
            reader.close();

            //            ByteArrayOutputStream content = new ByteArrayOutputStream();
            //            response.getEntity().writeTo(content);
            //            ret = new String(content.toByteArray()).trim();
            //            content.close();
        } else {
            RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                    "??,??" + statusCode);
            ret = ErrorUtil.errorJson("ERROR.HTTP.001", exception.getMessage());
        }

        LogUtil.d(AsyncHttpGet.class.getName(), "AsyncHttpGet  request to url :" + url + "  finished !");

    } catch (java.lang.IllegalArgumentException e) {

        RequestException exception = new RequestException(RequestException.IO_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.002", exception.getMessage());
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (org.apache.http.conn.ConnectTimeoutException e) {
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.003", exception.getMessage());
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (java.net.SocketTimeoutException e) {
        RequestException exception = new RequestException(RequestException.SOCKET_TIMEOUT_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.004", exception.getMessage());
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  onFail  " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        RequestException exception = new RequestException(RequestException.UNSUPPORTED_ENCODEING_EXCEPTION,
                "?");
        ret = ErrorUtil.errorJson("ERROR.HTTP.005", exception.getMessage());
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  UnsupportedEncodingException  " + e.getMessage());
    } catch (org.apache.http.conn.HttpHostConnectException e) {
        RequestException exception = new RequestException(RequestException.CONNECT_EXCEPTION,
                Constants.ERROR_MESSAGE);
        ret = ErrorUtil.errorJson("ERROR.HTTP.006", exception.getMessage());
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  HttpHostConnectException  " + e.getMessage());
    } catch (ClientProtocolException e) {
        RequestException exception = new RequestException(RequestException.CLIENT_PROTOL_EXCEPTION,
                "??");
        ret = ErrorUtil.errorJson("ERROR.HTTP.007", exception.getMessage());
        e.printStackTrace();
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  ClientProtocolException " + e.getMessage());
    } catch (IOException e) {
        RequestException exception = new RequestException(RequestException.IO_EXCEPTION, "??");
        ret = ErrorUtil.errorJson("ERROR.HTTP.008", exception.getMessage());
        e.printStackTrace();
        LogUtil.d(AsyncHttpGet.class.getName(),
                "AsyncHttpGet  request to url :" + url + "  IOException  " + e.getMessage());
    } finally {
        if (!Constants.IS_STOP_REQUEST) {
            Message msg = new Message();
            msg.obj = ret;
            LogUtil.d("result", ret);
            msg.getData().putSerializable("callback", callBack);
            resultHandler.sendMessage(msg);
        }
        //request.//
        if (customLoadingDialog != null && customLoadingDialog.isShowing()) {
            customLoadingDialog.dismiss();
            customLoadingDialog = null;
        }
    }
    super.run();
}

From source file:com.lzy.mmd.widget.viewpager.ViewPagerCompat.java

@Override
public boolean onTouchEvent(MotionEvent ev) {
    try {/*from   w  ww. j  av  a  2 s .  c  o  m*/
        if (mFakeDragging) {
            // A fake drag is in progress already, ignore this real one
            // but still eat the touch events.
            // (It is likely that the user is multi-touching the screen.)
            return true;
        }

        if (ev.getAction() == MotionEvent.ACTION_DOWN && ev.getEdgeFlags() != 0) {
            // Don't handle edge touches immediately -- they may actually belong to one of our
            // descendants.
            return false;
        }

        if (mAdapter == null || mAdapter.getCount() == 0) {
            // Nothing to present or scroll; nothing to touch.
            return false;
        }

        if (mVelocityTracker == null) {
            mVelocityTracker = VelocityTracker.obtain();
        }
        mVelocityTracker.addMovement(ev);

        final int action = ev.getAction();
        boolean needsInvalidate = false;

        switch (action & MotionEventCompat.ACTION_MASK) {
        case MotionEvent.ACTION_DOWN: {
            mScroller.abortAnimation();
            mPopulatePending = false;
            populate();

            // Remember where the motion event started
            mLastMotionX = mInitialMotionX = ev.getX();
            mLastMotionY = mInitialMotionY = ev.getY();
            mActivePointerId = MotionEventCompat.getPointerId(ev, 0);
            break;
        }
        case MotionEvent.ACTION_MOVE:
            if (!mIsBeingDragged) {
                final int pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
                final float x = MotionEventCompat.getX(ev, pointerIndex);
                final float xDiff = Math.abs(x - mLastMotionX);
                final float y = MotionEventCompat.getY(ev, pointerIndex);
                final float yDiff = Math.abs(y - mLastMotionY);
                if (DEBUG)
                    Log.v(TAG, "Moved x to " + x + "," + y + " diff=" + xDiff + "," + yDiff);
                if (xDiff > mTouchSlop && xDiff > yDiff) {
                    if (DEBUG)
                        Log.v(TAG, "Starting drag!");
                    mIsBeingDragged = true;
                    requestParentDisallowInterceptTouchEvent(true);
                    mLastMotionX = x - mInitialMotionX > 0 ? mInitialMotionX + mTouchSlop
                            : mInitialMotionX - mTouchSlop;
                    mLastMotionY = y;
                    setScrollState(SCROLL_STATE_DRAGGING);
                    setScrollingCacheEnabled(true);

                    // Disallow Parent Intercept, just in case
                    ViewParent parent = getParent();
                    if (parent != null) {
                        parent.requestDisallowInterceptTouchEvent(true);
                    }
                }
            }
            // Not else! Note that mIsBeingDragged can be set above.
            if (mIsBeingDragged) {
                // Scroll to follow the motion event
                final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
                final float x = MotionEventCompat.getX(ev, activePointerIndex);
                needsInvalidate |= performDrag(x);
            }
            break;
        case MotionEvent.ACTION_UP:
            if (mIsBeingDragged) {
                final VelocityTracker velocityTracker = mVelocityTracker;
                velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity);
                int initialVelocity = (int) VelocityTrackerCompat.getXVelocity(velocityTracker,
                        mActivePointerId);
                mPopulatePending = true;
                final int width = getClientWidth();
                final int scrollX = getScrollX();
                final ItemInfo ii = infoForCurrentScrollPosition();
                final int currentPage = ii.position;
                final float pageOffset = (((float) scrollX / width) - ii.offset) / ii.widthFactor;
                final int activePointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId);
                final float x = MotionEventCompat.getX(ev, activePointerIndex);
                final int totalDelta = (int) (x - mInitialMotionX);
                int nextPage = determineTargetPage(currentPage, pageOffset, initialVelocity, totalDelta);
                setCurrentItemInternal(nextPage, true, true, initialVelocity);

                mActivePointerId = INVALID_POINTER;
                endDrag();
                needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease();
            }
            break;
        case MotionEvent.ACTION_CANCEL:
            if (mIsBeingDragged) {
                scrollToItem(mCurItem, true, 0, false);
                mActivePointerId = INVALID_POINTER;
                endDrag();
                needsInvalidate = mLeftEdge.onRelease() | mRightEdge.onRelease();
            }
            break;
        case MotionEventCompat.ACTION_POINTER_DOWN: {
            final int index = MotionEventCompat.getActionIndex(ev);
            final float x = MotionEventCompat.getX(ev, index);
            mLastMotionX = x;
            mActivePointerId = MotionEventCompat.getPointerId(ev, index);
            break;
        }
        case MotionEventCompat.ACTION_POINTER_UP:
            onSecondaryPointerUp(ev);
            mLastMotionX = MotionEventCompat.getX(ev, MotionEventCompat.findPointerIndex(ev, mActivePointerId));
            break;
        }
        if (needsInvalidate) {
            ViewCompat.postInvalidateOnAnimation(this);
        }
        return true;
    } catch (IllegalArgumentException e) {
        // 
        e.printStackTrace();
        return false;
    }
}

From source file:calendarioSeries.vistas.NewSerieController.java

@FXML
public void handleOk() {
    String tituloAux = titulo.getText().replaceAll(" ", "+").toLowerCase();
    String toJson = readUrl(BASE + tituloAux + "&type=series" + "&r=json");
    resultados.getChildren().clear();//w  w  w .j a  v  a 2 s .  c  om
    try {
        JSONObject busqueda = new JSONObject(toJson);
        if (busqueda.getString("Response").equals("True")) {
            JSONArray res = busqueda.getJSONArray("Search");
            resultados.setPrefRows(res.length());
            for (int i = 0; i < res.length(); i++) {
                JSONObject resActual = new JSONObject(res.get(i).toString());
                HBox resultadoActual = new HBox(50);
                resultadoActual.setMaxWidth(Double.MAX_VALUE);
                resultadoActual.setAlignment(Pos.CENTER_LEFT);
                ImageView posterActual = new ImageView();

                try {
                    Image image = new Image(resActual.getString("Poster"));
                    posterActual.setImage(image);
                    posterActual.setFitHeight(240);
                    posterActual.setFitWidth(180);
                    posterActual.setPreserveRatio(false);
                    resultadoActual.getChildren().add(posterActual);
                } catch (IllegalArgumentException e) {
                    //                        System.out.println("Bad url");
                    Image image = new Image(
                            MainApp.class.getResource("resources/no-image.png").toExternalForm());
                    posterActual.setImage(image);
                    posterActual.setFitHeight(240);
                    posterActual.setFitWidth(180);
                    posterActual.setPreserveRatio(false);
                    resultadoActual.getChildren().add(posterActual);
                }

                String details;
                String nomSerie = new String(resActual.getString("Title").getBytes(), "UTF-8");
                String anoSerie = new String(resActual.getString("Year").getBytes(), "UTF-8");
                if (nomSerie.length() > 15) {
                    details = "%-12.12s...\t\t Ao: %-10s";
                } else {
                    details = "%-12s\t\t Ao: %-10s";
                }
                details = String.format(details, nomSerie, anoSerie);
                Label elemento = new Label(details);
                elemento.setMaxWidth(Double.MAX_VALUE);
                elemento.setMaxHeight(Double.MAX_VALUE);
                resultadoActual.getChildren().add(elemento);

                posterActual.setId(resActual.getString("imdbID"));
                posterActual.setOnMouseClicked(new EventHandler<MouseEvent>() {
                    @Override
                    public void handle(MouseEvent event) {
                        ImageView clickedButton = (ImageView) event.getSource();
                        Stage stage = (Stage) clickedButton.getScene().getWindow();
                        Task task = new Task() {
                            @Override
                            protected Object call() throws Exception {
                                mainController.mainApp.scene.setCursor(Cursor.WAIT);
                                Serie toAdd = new Serie(clickedButton.getId());
                                boolean possible = true;
                                for (Serie serie : mainController.getSeries()) {
                                    if (serie.equals(toAdd))
                                        possible = false;
                                }
                                if (possible)
                                    mainController.getSeries().add(toAdd);

                                try {
                                    mainController.populateImagenes();
                                    mainController.showDetallesMes(mainController.getMesActual());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                } finally {
                                    mainController.mainApp.scene.setCursor(Cursor.DEFAULT);

                                    return mainController.getSeries();
                                }
                            }
                        };
                        Thread th = new Thread(task);
                        th.setDaemon(true);
                        th.start();
                        stage.close();
                    }
                });
                resultados.getChildren().add(resultadoActual);
            }
        } else {
            resultados.getChildren().add(new Label("La busqueda no obtuvo resultados"));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(NewSerieController.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.nuvolect.deepdive.webserver.OmniRest.java

public static InputStream process(Context ctx, Map<String, String> params) {

    long timeStart = System.currentTimeMillis();
    CMD_ID cmd_id = CMD_ID.NIL;/*  w w w .  j  ava2s  . c o  m*/
    String error = "";
    String volumeId = App.getUser().getDefaultVolumeId();
    if (params.containsKey("volume_id"))
        volumeId = params.get("volume_id");
    String path = "";
    if (params.containsKey("path"))
        path = params.get("path");

    try {
        String uri = params.get("uri");
        String segments[] = uri.split("/");
        cmd_id = CMD_ID.valueOf(segments[2]);
    } catch (IllegalArgumentException e) {
        error = "Error, invalid command: " + params.get("cmd");
    }

    JSONObject wrapper = new JSONObject();
    String extra = "";

    try {
        switch (cmd_id) {

        case NIL:
            break;
        case decode_hash: {
            String result = decode_hash(params.get("data"));
            wrapper.put("result", result);
            break;
        }
        case delete: {
            JSONObject result = new JSONObject();
            OmniFile file = new OmniFile(params.get("encoded_path"));
            boolean delete_result = file.delete();
            result.put("result", delete_result);
            result.put("error", "");
            wrapper.put("result", result);
            break;
        }
        case encode_hash: {
            String result = encode_hash(params.get("data"));
            wrapper.put("result", result);
            break;
        }
        case get: {
            //                    InputStream is = null;
            //                    OmniFile of = new OmniFile( encodedPath);
            //
            //                    if( of.exists())
            //                        is = of.getFileInputStream();
            //                    else
            //                        is = IOUtils.getInputStreamFromString("File not found: " + encodedPath);
            //
            //                    try {
            //                        org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
            //                        response.flushBuffer();
            //
            //                    } catch (IOException e) {
            //                        LogUtil.logException(OmniRest.class, e);
            //                    }
            break;
        }
        case get_info: {
            String result = ProbeUtil.getInfo(params.get("encoded_path")).toString();
            wrapper.put("result", result);
            break;
        }
        case get_text: {
            JSONObject result = OmniUtil.getText(volumeId, path);
            wrapper.put("result", result.toString());
            break;
        }
        case list_files: {
            JSONObject result = new JSONObject();
            OmniFile om = new OmniFile(params.get("encoded_path"));
            OmniFile[] files = om.listFiles();

            JSONArray jsonArray = new JSONArray();
            for (OmniFile file : files) {

                JSONObject fileObj = FileObj.makeObj(file, "");
                jsonArray.put(fileObj);
            }

            result.put("result", jsonArray.toString());
            result.put("error", "");
            wrapper.put("result", result);
            break;
        }
        case mime: {
            String result = MimeUtil.getMime(params.get("data"));
            wrapper.put("result", result);
            break;
        }
        case mkdir: {
            JSONObject result = new JSONObject();
            OmniFile file = new OmniFile(params.get("encoded_path"));
            boolean mkdir_result = file.mkdirs();
            result.put("result", mkdir_result);
            result.put("error", "");
            wrapper.put("result", result);
            break;
        }
        case upload:
            break;
        }
        if (!error.isEmpty())
            LogUtil.log(OmniRest.class, "Error: " + error);

        wrapper.put("error", error);
        wrapper.put("cmd_id", cmd_id.toString());
        wrapper.put("delta_time", String.valueOf(System.currentTimeMillis() - timeStart) + " ms");

        return new ByteArrayInputStream(wrapper.toString().getBytes("UTF-8"));

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:me.azenet.UHPlugin.UHPluginCommand.java

/**
 * This command is used to manage the teams.
 * //w  w w  .  j a  v a2s  . com
 * Usage: /uh team (for the doc).
 * Usage: /uh team <add|remove|join|leave|list|reset> (see doc for details).
 *    
 * @param sender
 * @param command
 * @param label
 * @param args
 */
@SuppressWarnings("unused")
private void doTeam(CommandSender sender, Command command, String label, String[] args) {
    if (args.length == 1) { // No action provided: doc
        displaySeparator(sender);
        sender.sendMessage(
                i.t("cmd.titleHelp", p.getDescription().getDescription(), p.getDescription().getVersion()));
        sender.sendMessage(i.t("cmd.legendHelp"));

        sender.sendMessage(i.t("cmd.teamHelpTitle"));
        sender.sendMessage(i.t("cmd.teamHelpAdd"));
        sender.sendMessage(i.t("cmd.teamHelpAddName"));
        sender.sendMessage(i.t("cmd.teamHelpRemove"));
        sender.sendMessage(i.t("cmd.teamHelpJoin"));
        sender.sendMessage(i.t("cmd.teamHelpLeave"));
        sender.sendMessage(i.t("cmd.teamHelpList"));
        sender.sendMessage(i.t("cmd.teamHelpReset"));
        sender.sendMessage(i.t("cmd.teamHelpJoinCmd"));
        sender.sendMessage(i.t("cmd.teamHelpLeaveCmd"));
        displaySeparator(sender);
    } else {
        TeamManager tm = p.getTeamManager();
        String subcommand = args[1];

        if (subcommand.equalsIgnoreCase("add")) {
            if (args.length == 3) { // /uh team add <color>

                TeamColor color = TeamColor.fromString(args[2]);
                UHTeam team;

                if (color == null) {
                    sender.sendMessage(i.t("team.add.errorColor"));
                } else {
                    try {
                        team = tm.addTeam(color);
                    } catch (IllegalArgumentException e) {
                        sender.sendMessage(i.t("team.add.errorExists"));
                        return;
                    }

                    sender.sendMessage(i.t("team.add.added", team.getDisplayName()));
                }

            } else if (args.length >= 4) { // /uh team add <color> <name ...>

                TeamColor color = TeamColor.fromString(args[2]);
                UHTeam team;

                if (color == null) {
                    sender.sendMessage(i.t("team.add.errorColor"));
                } else {
                    String name = UHUtils.getStringFromCommandArguments(args, 3);

                    try {
                        team = tm.addTeam(color, name);
                    } catch (IllegalArgumentException e) {
                        e.printStackTrace();
                        sender.sendMessage(i.t("team.add.errorExists"));
                        return;
                    }

                    sender.sendMessage(i.t("team.add.added", team.getDisplayName()));
                }

            } else {
                sender.sendMessage(i.t("team.syntaxError"));
            }
        }

        else if (subcommand.equalsIgnoreCase("remove")) {
            if (args.length >= 3) { // /uh team remove <teamName>
                String name = UHUtils.getStringFromCommandArguments(args, 2);
                if (!tm.removeTeam(name)) {
                    sender.sendMessage(i.t("team.remove.doesNotExists"));
                } else {
                    sender.sendMessage(i.t("team.remove.removed", name));
                }
            } else {
                sender.sendMessage(i.t("team.syntaxError"));
            }
        }

        else if (subcommand.equalsIgnoreCase("join")) {
            if (args.length >= 4) { // /uh team join <player> <teamName>

                OfflinePlayer player = p.getServer().getOfflinePlayer(args[2]);
                String teamName = UHUtils.getStringFromCommandArguments(args, 3);

                if (player == null || !player.isOnline()) {
                    sender.sendMessage(i.t("team.addplayer.disconnected", args[2], teamName));
                } else {
                    try {
                        tm.addPlayerToTeam(teamName, player);
                    } catch (IllegalArgumentException e) {
                        sender.sendMessage(i.t("team.addplayer.doesNotExists"));
                        return;
                    } catch (RuntimeException e) {
                        sender.sendMessage(i.t("team.addplayer.full", teamName));
                        return;
                    }
                    UHTeam team = p.getTeamManager().getTeam(teamName);
                    sender.sendMessage(i.t("team.addplayer.success", args[2], team.getDisplayName()));
                }
            } else {
                sender.sendMessage(i.t("team.syntaxError"));
            }
        }

        else if (subcommand.equalsIgnoreCase("leave")) {
            if (args.length == 3) { // /uh team leave <player>

                OfflinePlayer player = p.getServer().getOfflinePlayer(args[2]);

                if (player == null) {
                    sender.sendMessage(i.t("team.removeplayer.disconnected", args[2]));
                } else {
                    tm.removePlayerFromTeam(player);
                    sender.sendMessage(i.t("team.removeplayer.success", args[2]));
                }
            } else {
                sender.sendMessage(i.t("team.syntaxError"));
            }
        }

        else if (subcommand.equalsIgnoreCase("list")) {
            if (tm.getTeams().size() == 0) {
                sender.sendMessage(i.t("team.list.nothing"));
                return;
            }

            for (final UHTeam team : tm.getTeams()) {
                sender.sendMessage(i.t("team.list.itemTeam", team.getDisplayName(),
                        ((Integer) team.getSize()).toString()));
                for (final OfflinePlayer player : team.getPlayers()) {
                    String bullet = null;
                    if (player.isOnline()) {
                        bullet = i.t("team.list.bulletPlayerOnline");
                    } else {
                        bullet = i.t("team.list.bulletPlayerOffline");
                    }

                    sender.sendMessage(bullet + i.t("team.list.itemPlayer", player.getName()));
                }
            }
        }

        else if (subcommand.equalsIgnoreCase("reset")) {
            tm.reset();
            sender.sendMessage(i.t("team.reset.success"));
        }

        else {
            sender.sendMessage(i.t("team.unknownCommand"));
        }
    }
}