Example usage for java.lang Exception getStackTrace

List of usage examples for java.lang Exception getStackTrace

Introduction

In this page you can find the example usage for java.lang Exception getStackTrace.

Prototype

public StackTraceElement[] getStackTrace() 

Source Link

Document

Provides programmatic access to the stack trace information printed by #printStackTrace() .

Usage

From source file:com.spit.spirit17.Fragments.DevelopersFragment.java

@Nullable
@Override//from w  w w  .j a  va2 s  . c  om
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_developers, container, false);

    email1 = (TextView) view.findViewById(R.id.emailId_tejas);
    email2 = (TextView) view.findViewById(R.id.emailId_shubham);
    email3 = (TextView) view.findViewById(R.id.emailId_adnan);

    g1 = (Button) view.findViewById(R.id.google_tejas);
    g2 = (Button) view.findViewById(R.id.google_shubham);
    g3 = (Button) view.findViewById(R.id.google_adnan);

    l1 = (Button) view.findViewById(R.id.linkedin_tejas);
    l2 = (Button) view.findViewById(R.id.linkedin_shubham);
    l3 = (Button) view.findViewById(R.id.linkedin_adnan);

    image1 = (ImageView) view.findViewById(R.id.pic_tejas);
    image2 = (ImageView) view.findViewById(R.id.pic_shubham);
    image3 = (ImageView) view.findViewById(R.id.pic_adnan);

    /*Add Your Pics Here And Not In Xml*/
    Picasso.with(getActivity()).load(R.drawable.dev_tejas_bhitle).into(image1);
    Picasso.with(getActivity()).load(R.drawable.dev_shubham_mahajan).into(image2);
    Picasso.with(getActivity()).load(R.drawable.dev_adnan_ansari).into(image3);

    View.OnClickListener linkListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Uri uri;
            switch (v.getId()) {

            /*Google+ links*/
            case R.id.google_tejas:
                uri = Uri.parse(getResources().getString(R.string.googleplus_tejas));
                break;
            case R.id.google_shubham:
                uri = Uri.parse(getResources().getString(R.string.googleplus_shubham));
                break;
            case R.id.google_adnan:
                uri = Uri.parse(getResources().getString(R.string.googleplus_adnan));
                break;

            /*LInkedin Links*/
            case R.id.linkedin_tejas:
                uri = Uri.parse(getResources().getString(R.string.linkedin_tejas));
                break;
            case R.id.linkedin_shubham:
                uri = Uri.parse(getResources().getString(R.string.linkedin_shubham));
                break;
            case R.id.linkedin_adnan:
                uri = Uri.parse(getResources().getString(R.string.linkedin_adnan));
                break;
            default:
                uri = Uri.parse(getResources().getString(R.string.linkedin_tejas));
            }
            Intent i = new Intent(Intent.ACTION_VIEW, uri);
            try {
                startActivity(i);
            } catch (Exception e) {
                Toast.makeText(getActivity(), "Error Loading Link", Toast.LENGTH_SHORT).show();
            }

        }
    };

    View.OnClickListener emailListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String to = "";
            switch (v.getId()) {
            /*Email Ids*/
            case R.id.emailId_tejas:
                to = getResources().getString(R.string.email_tejas);
                break;
            case R.id.emailId_shubham:
                to = getResources().getString(R.string.email_shubham);
                break;
            case R.id.emailId_adnan:
                to = getResources().getString(R.string.email_adnan);
                break;
            }
            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SENDTO);
            intent.setType("text/plain");
            intent.setData(Uri.parse("mailto:" + to));
            intent.putExtra(Intent.EXTRA_EMAIL, to);
            try {
                startActivity(Intent.createChooser(intent, "Send Email"));
            } catch (Exception e) {
                Toast.makeText(getActivity(), e.getStackTrace().toString(), Toast.LENGTH_SHORT).show();
            }
        }
    };
    email1.setOnClickListener(emailListener);
    email2.setOnClickListener(emailListener);
    email3.setOnClickListener(emailListener);
    g1.setOnClickListener(linkListener);
    g2.setOnClickListener(linkListener);
    g3.setOnClickListener(linkListener);
    l1.setOnClickListener(linkListener);
    l2.setOnClickListener(linkListener);
    l3.setOnClickListener(linkListener);

    return view;
}

From source file:tools.xor.service.AggregateManager.java

private String getStackTrace(int numStackElements) {
    Exception e = new Exception();
    StringBuilder sb = new StringBuilder();

    int skip = 2; // skip first 2
    for (StackTraceElement element : e.getStackTrace()) {
        if (skip-- > 0) {
            continue;
        } else if (skip + numStackElements == 0) {
            break;
        }//from  www . j a  v  a 2s . c om
        sb.append(element.toString());
        sb.append("\r\n");
    }
    return sb.toString();
}

From source file:com.castis.xylophone.adsmadapter.convert.axistree.ConvertCategoryAxisTreeDTO.java

@Transactional(rollbackFor = Exception.class)
public int convertCategoryTree(Date date, ADSMSchedulerLogDTO schedulerLog, String treeName,
        ADSMJobNameType srcJopType, boolean isPartialUpdate, ADSMSchedulerLogDTO deleteSchedulerLog,
        Platform platformType) throws Exception {
    if (schedulerLog == null) {
        throw new CiRuntimeException("ADSMSchedulerLog is null");
    }//from   w  w w.j  av  a  2s .  c  o  m

    if (treeName == null || treeName.isEmpty()) {
        throw new CiRuntimeException("Cannot find treeName in generating CategoryTree");
    }

    long start = System.currentTimeMillis();
    this.srcJobType = srcJopType;

    log.info("TreeName : " + treeName + ", srcDataType : " + srcJopType + ". Start Update("
            + schedulerLog.getParam() + ")");

    int treeID = 0;
    int dataLogID = Integer.parseInt((String) schedulerLog.getParamValue("dataLogId"));

    String licenseStartDateStr = null;
    List<CategoryDTO> invenBoxCategoryDTOs = null;
    List<VirtualCategoryDTO> virtualCategoryDTOs = null;
    String addsSite = null;

    if (ADSMJobNameType.INVENTORY_CATEGORY_DATA == srcJopType || ADSMJobNameType.CATEGORY_DATA == srcJopType) {
        licenseStartDateStr = (String) schedulerLog.getParamValue(FilePolling.PARAM_START_TIME_PREFIX);
        addsSite = (String) schedulerLog.getParamValue(FilePolling.PARAM_SITE_PREFIX);

        invenBoxCategoryDTOs = tambourineConnector.getCategoryListFromInventoryBox(date);

        VirtualCategoryDefineDTO virtualCategoryDefineDTO = tambourineConnector
                .getVirtualCategoryDefineList(date);

        if (virtualCategoryDefineDTO != null)
            virtualCategoryDTOs = virtualCategoryDefineDTO.getVirtualCategoryList();
        if (invenBoxCategoryDTOs == null || invenBoxCategoryDTOs.size() == 0)
            log.warn("Cannot find InventoryBox at " + date.toString());
    }

    try {
        //?, , ,  ?
        //tambourineConnector.initializeInventoryCube(date);
        NodeDTO rootNodeDTO = getRootNode(dataLogID);

        if (rootNodeDTO == null) {
            throw new CiRuntimeException("Fail to Update Category Tree (Cannot Check root node Info. "
                    + schedulerLog.getParam() + ")");
        }

        treeID = tambourineConnector.getAxisTreeId(TreeType.CATEGORY_AXIS_TREE, treeName, addsSite,
                platformType, false);
        //?
        if (treeID <= 0)
            treeID = tambourineConnector.registerCategoryAxisTree(
                    getAxisTreeDTO(treeName, rootNodeDTO, addsSite, platformType), date);

        //TreeNode .
        //?
        if (ADSMJobNameType.INVENTORY_CATEGORY_DATA == srcJopType
                || ADSMJobNameType.CATEGORY_DATA == srcJopType) {
            if (licenseStartDateStr != null) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Date licenseStartDate = sdf.parse(licenseStartDateStr);
                Date syncStartDate = licenseStartDate;
                Date nowDate = new Date();

                if (isPartialUpdate == false)
                    syncStartDate = nowDate;

                makeTreeNode(treeID, licenseStartDate, rootNodeDTO.getExternalNodeId(), invenBoxCategoryDTOs,
                        virtualCategoryDTOs, dataLogID, isPartialUpdate);

                String param = "treeId:" + treeID + "/treeType:" + TreeType.CATEGORY_AXIS_TREE.toString()
                        + "/treeName:" + treeName;
                FeSyncNoticeboardDTO feSyncNoticeboardDTO = tambourineConnector.generateFeSyncNoticeboardData(
                        SyncDataType.TREEDATA, syncStartDate, param, addsSite, FeSyncNoticeboardStatus.NEWDATA,
                        platformType, null, null);

                //? sync ,treetype,treeName? syncNoticeboard disable
                tambourineConnector.disableFeSyncNoticeboard(feSyncNoticeboardDTO);

                //  syncNoticeboard? ?
                if (isPartialUpdate == false)
                    tambourineConnector.insertTreeLogNSyncNoticeboard(treeID, TreeType.CATEGORY_AXIS_TREE,
                            treeName, feSyncNoticeboardDTO, addsSite, platformType);
            } else {
                makeTreeNode(treeID, date, rootNodeDTO.getExternalNodeId(), invenBoxCategoryDTOs,
                        virtualCategoryDTOs, dataLogID, isPartialUpdate);
                addsSite = ADDSAdapterSetting.defaultSiteName;
                insertTreeLogNSyncNoticeboard(addsSite, treeID, treeName, null);
            }

            // ? ??   ? ?  ? ??    ? ?? .      
            if (isPartialUpdate == false) {
                if (deleteSchedulerLog == null)
                    throw new CiRuntimeException("Cannot Find deleteSchedulerLog in generating CategoryTree.");

                if (updateDisableContentPolicy(treeID, deleteSchedulerLog.getId()) == true) {
                    deleteSchedulerLog.setSchedulerStatus(ADSMSchedulerStatus.SUCCESS);
                } else
                    deleteSchedulerLog.setSchedulerStatus(ADSMSchedulerStatus.DONE);
            }
        } else { //viettel STB, OTT   ? 
            makeTreeNode(treeID, date, rootNodeDTO.getExternalNodeId(), null, null, dataLogID, false);
            Platform platform = getPlatformTypeByADSMJobNameType(srcJopType);
            insertTreeLogNSyncNoticeboard(addsSite, treeID, treeName, platform);

        }
        // ? 
        schedulerLog.setSchedulerStatus(ADSMSchedulerStatus.SUCCESS);
        schedulerLog.setMessage(TREE_NAME_MESSAGE_PREFIX + treeName);
    } catch (Exception e) {
        long end = System.currentTimeMillis();
        TheLogger.getWriter().error("Fail to Update Category Tree");
        log.error("Fail to update Category Tree.(" + schedulerLog.getParam() + ") - T(" + (end - start) + ")");
        schedulerLog.setMessage(e.getMessage());
        schedulerLog.setSchedulerStatus(ADSMSchedulerStatus.FAIL);
        if (ADSMJobNameType.INVENTORY_CATEGORY_DATA == srcJopType
                || ADSMJobNameType.CATEGORY_DATA == srcJopType) {
            deleteSchedulerLog.setSchedulerStatus(ADSMSchedulerStatus.FAIL);
        }
        StackTraceElement[] stackTraces = e.getStackTrace();
        if (stackTraces.length > 0) {
            schedulerLog.setFailProcess(stackTraces[0].getClassName() + " - " + stackTraces[0].getMethodName()
                    + "(" + stackTraces[0].getLineNumber() + ")");
        }
        throw e;
    }
    long end = System.currentTimeMillis();
    log.info("Complete to Update Category Tree (" + schedulerLog.getParam() + ") - T(" + (end - start) + ")");
    TheLogger.getWriter().info("Complete to Update Category Tree(" + schedulerLog.getParam() + ")");
    return treeID;
}

From source file:co.forsaken.api.json.JsonWebCall.java

public <T> T execute(Class<T> retType, Object arg) {
    if (_log)/*from w w  w  .  j  av a  2s  .  c  o  m*/
        System.out.println("Requested: [" + _url + "]");
    try {
        canConnect();
    } catch (Exception ex) {
        ex.printStackTrace();
        return null;
    }
    HttpClient httpClient = new DefaultHttpClient(_connectionManager);
    InputStream in = null;
    T returnData = null;
    String res = null;

    try {
        Gson gson = new Gson();
        HttpPost request = new HttpPost(_url);
        if (arg != null) {
            StringEntity params = new StringEntity(gson.toJson(arg));
            params.setContentType(new BasicHeader("Content-Type", "application/json"));
            request.setEntity(params);
        }
        HttpResponse response = httpClient.execute(request);
        if (response != null) {
            in = response.getEntity().getContent();
            res = convertStreamToString(in);
            returnData = new Gson().fromJson(res, retType);
        }
    } catch (Exception ex) {
        System.out.println("JSONWebCall.execute() Error: \n" + ex.getMessage());
        System.out.println("Result: \n" + res);
        StackTraceElement[] arrOfSTE;
        int max = (arrOfSTE = ex.getStackTrace()).length;
        for (int i = 0; i < max; i++) {
            StackTraceElement trace = arrOfSTE[i];
            System.out.println(trace);
        }
    } finally {
        httpClient.getConnectionManager().shutdown();
        if (in != null) {
            try {
                in.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    if (_log)
        System.out.println("Returned: [" + _url + "] [" + res + "]");
    return returnData;
}

From source file:org.alfresco.reporting.processor.NodeRefBasedPropertyProcessor.java

public void processQueueValues(String table) throws Exception {
    if (logger.isDebugEnabled())
        logger.debug("Enter processQueueValues table=" + table);

    // Statement stmt = null;
    // Properties tableDesc = dbhb.getTableDescription(stmt, table);

    if (logger.isDebugEnabled())
        logger.debug(//w  ww  . java2 s.  c o m
                "************ Found " + queue.size() + " entries in " + table + " **************** " + method);
    ReportLine rl = new ReportLine(table, getSimpleDateFormat(), reportingHelper);

    // Create the processing object once...

    long now_before = (new Date()).getTime();
    int queuesize = queue.size();
    for (int q = 0; q < queue.size(); q++) {
        String identifier = queue.get(q).toString();
        try {
            NodeRef nodeRef = new NodeRef(identifier.split(",")[0]);

            if (logger.isDebugEnabled()) {
                String name = (String) getNodeService().getProperty(nodeRef, ContentModel.PROP_NAME);
                logger.debug("processQueueValues: " + q + "/" + queuesize + ": " + name);
            }

            // run each queue entry through the processing object
            rl = processNodeToMap(identifier, table, rl);

            int numberOfRows = 0;
            if (logger.isDebugEnabled())
                logger.debug("Current method=" + this.method);
            try { // SINGLE_INSTANCE,
                  // logger.debug(method + " ##### " + rl.size());
                if ((rl.size() > 0) /*
                                    * &&
                                    * (rl.getValue("sys_node_uuid").length(
                                    * )>5)
                                    */) {
                    // logger.debug("method="+method+" && row exists?");

                    if (this.method.equals(Constants.INSERT_ONLY)) {
                        // if (logger.isDebugEnabled()) logger.debug("Going
                        // INSERT_ONLY");

                        numberOfRows = dbhb.insertIntoTable(rl);
                        // logger.debug(numberOfRows+ " rows inserted");
                    }

                    // -------------------------------------------------------------

                    if (this.method.equals(Constants.SINGLE_INSTANCE)) {
                        // if (logger.isDebugEnabled()) logger.debug("Going
                        // SINGLE_INSTANCE");

                        if (dbhb.rowExists(rl)) {
                            numberOfRows = dbhb.updateIntoTable(rl);
                            // logger.debug(numberOfRows+ " rows updated");
                        } else {
                            numberOfRows = dbhb.insertIntoTable(rl);
                            // logger.debug(numberOfRows+ " rows inserted");

                        }

                    }

                    // -------------------------------------------------------------

                    if (this.method.equals(Constants.UPDATE_VERSIONED)) {
                        if (logger.isDebugEnabled())
                            logger.debug("Going UPDATE_VERSIONED");
                        try {
                            if (dbhb.rowExists(rl)) {
                                numberOfRows = dbhb.updateVersionedIntoTable(rl);
                                // numberOfRows = dbhb.insertIntoTable(rl);
                                if (logger.isDebugEnabled())
                                    logger.debug(numberOfRows + " rows updated");
                            } else {
                                if (logger.isDebugEnabled()) {
                                    logger.debug("No rows exist");
                                    logger.debug("## Set " + rl.getInsertListOfKeys());
                                    logger.debug("## Values " + rl.getInsertListOfValues());
                                }
                                numberOfRows = dbhb.insertIntoTable(rl);
                                if (logger.isDebugEnabled())
                                    logger.debug(numberOfRows + " rows inserted");

                            }
                        } catch (org.springframework.dao.RecoverableDataAccessException rdae) {
                            throw new AlfrescoRuntimeException("processQueueValues1: " + rdae.getMessage());
                        } catch (Exception ee) {
                            ee.printStackTrace();
                            logger.fatal("processQueueValues Exception1: " + ee.getMessage());
                        }
                    }
                } // end if rl.size>0

            } catch (org.springframework.dao.RecoverableDataAccessException rdae) {
                throw new AlfrescoRuntimeException("processQueueValues2: " + rdae.getMessage());
            } catch (Exception e) {
                logger.fatal("processQueueValues Exception2: " + e.getStackTrace());
                e.printStackTrace();
            } finally {
                rl.reset();
            }
        } catch (Exception e) {
            logger.info("Bad node detected; ignoring... " + identifier);
        }
    } // end for scriptnode in queue

    long now_after = (new Date()).getTime();

    if (logger.isInfoEnabled()) {

        logger.info("processQueueValues summary: " + queuesize + " rows in " + (now_after - now_before)
                + "ms = " + (now_after - now_before) / queuesize + "ms per row");
    }

    if (logger.isDebugEnabled())
        logger.debug("Exit processQueueValues");
}

From source file:com.inverse2.ajaxtoaster.AjaxToasterServlet.java

private void respondWithMessage(HttpServletResponse response, String messageType, String description,
        Exception exception, String responseFormat, String callbackFunction)
        throws ServletException, IOException {
    try {/*from  w w  w . ja  v a  2 s. c om*/
        PrintWriter out = response.getWriter();
        String format = null;
        String callbackFunctionTail = ");";

        if (responseFormat == null) {
            responseFormat = "JSON";
        }

        if (callbackFunction == null) {
            callbackFunction = "";
            callbackFunctionTail = "";
        } else {
            callbackFunction = callbackFunction + "(";
        }

        format = convertResponseFormat(responseFormat);

        response.setContentType(format);
        response.setHeader("Cache-Control", "no-cache, must-revalidate");
        response.setHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT");

        if (responseFormat.equals("XML")) {
            // print the error message in XML format

            out.println(
                    callbackFunction + "<" + messageType + "><description>" + description + "</description>");

            if (exception != null) {
                out.println("<detail>" + exception.toString() + "</detail>");
            } else {
                out.println("<detail/>");
            }

            out.println("</" + messageType + ">" + callbackFunctionTail);
        } else if (responseFormat.equals("JSON")) {
            // print the error message in JSON format
            out.println(callbackFunction + "{\"" + messageType + "\":{\"detail\":\"" + description
                    + "\",\"description\":\"" + (exception == null ? "" : exception.toString()) + "\"}}"
                    + callbackFunctionTail);
        } else {
            // output raw
            out.println(messageType + ":" + description);
            out.println("Exception: " + exception.toString());
        }

        out.close();
    } catch (Exception ex) {
        log.error("ERROR printing error - " + ex.toString() + ". " + ex.getStackTrace());
    }
}

From source file:org.apache.hadoop.yarn.client.api.impl.YarnClientImpl.java

@VisibleForTesting
org.apache.hadoop.security.token.Token<TimelineDelegationTokenIdentifier> getTimelineDelegationToken()
        throws IOException, YarnException {
    try {/*from  w  ww.  j a  v a 2  s  . co m*/
        // Only reachable when both security and timeline service are enabled.
        if (timelineClient == null) {
            synchronized (this) {
                if (timelineClient == null) {
                    timelineClient = createTimelineClient();
                    timelineClient.init(getConfig());
                    timelineClient.start();
                }
            }
        }
        return timelineClient.getDelegationToken(timelineDTRenewer);
    } catch (Exception e) {
        if (timelineServiceBestEffort) {
            LOG.warn("Failed to get delegation token from the timeline server: " + e.getMessage());
            return null;
        }
        throw e;
    } catch (NoClassDefFoundError e) {
        NoClassDefFoundError wrappedError = new NoClassDefFoundError(
                e.getMessage() + ". It appears that the timeline client "
                        + "failed to initiate because an incompatible dependency "
                        + "in classpath. If timeline service is optional to this "
                        + "client, try to work around by setting " + YarnConfiguration.TIMELINE_SERVICE_ENABLED
                        + " to false in client configuration.");
        wrappedError.setStackTrace(e.getStackTrace());
        throw wrappedError;
    }
}

From source file:ait.ffma.service.preservation.riskmanagement.TestLODFreebaseRetrieve.java

/**
 * This method retrieves objects set from database according to Ffma domain object type and to 
 * passed query parameter/*from   www. j  ava2  s  .  co  m*/
 * @param FfmaDomainObject
 * @param parameterMap
 */
public void removeObjectsSet(FfmaDomainObject FfmaDomainObject, Map<String, String> queryParameterMap) {
    try {
        List<String> exclusionsList = new ArrayList<String>();
        exclusionsList.add(RiskConstants.DOMAIN_OBJECT_NAME);
        List<? extends FfmaDomainObject> objectsList = dataStoreDao
                .retrieveCollection((FfmaDomainObject) FfmaDomainObject, exclusionsList);

        Iterator<? extends FfmaDomainObject> iter = objectsList.iterator();
        while (iter.hasNext()) {
            dataStoreDao.removeObject(iter.next());
            PronomFileFormat pronomFileFormatObject = (PronomFileFormat) iter.next();
            log.info("retrieved pronomFileFormat object: " + pronomFileFormatObject);
        }
    } catch (Exception e) {
        fail("Caught ObjectNotRetrievedException error: " + e + e.getStackTrace());
    }
}

From source file:ait.ffma.service.preservation.riskmanagement.TestLODFreebaseRetrieve.java

/**
 * This method initializes extensions list
 *///from ww w  .  ja  va2s . com
@SuppressWarnings("unused")
private void initFileFormatList() {
    PronomFileFormat pronomFileFormat = new PronomFileFormat();
    pronomFileFormat.setFfmaObjectName(PronomFileFormat.class.getSimpleName());

    try {
        CommonApiServerConfigurationImpl commonApiServerConfiguration = new CommonApiServerConfigurationImpl();
        commonApiServerConfiguration.init();
        MongoDbManager mongoDbManager = new MongoDbManager();
        mongoDbManager.setCommonApiServerConfiguration(commonApiServerConfiguration);
        FfmaAbstractFactoryImpl objectFactory = new FfmaAbstractFactoryImpl();
        mongoDbManager.setObjectFactory(objectFactory);
        mongoDbManager.init();
        DataStoreDaoImpl dataStoreDao = new DataStoreDaoImpl();
        dataStoreDao.setMongoDbManager(mongoDbManager);

        List<String> exclusionsList = new ArrayList<String>();
        exclusionsList.add(RiskConstants.DOMAIN_OBJECT_NAME);
        List<? extends FfmaDomainObject> fileFormats = dataStoreDao
                .retrieveCollection((FfmaDomainObject) pronomFileFormat, exclusionsList);

        fileFormatList = LODUtils.getFileFormatsList(fileFormats);
        log.info("extensionsList size: " + fileFormatList.size());
    } catch (Exception e) {
        fail("Caught ObjectNotRetrievedException error: " + e + e.getStackTrace());
    }
}

From source file:com.proofpoint.http.client.ApacheHttpClient.java

public <T, E extends Exception> T execute(Request request, final ResponseHandler<T, E> responseHandler)
        throws E {
    Preconditions.checkNotNull(request, "request is null");
    Preconditions.checkNotNull(responseHandler, "responseHandler is null");

    for (HttpRequestFilter requestFilter : requestFilters) {
        request = requestFilter.filterRequest(request);
    }//from   www  . j  av a  2 s  . c  om

    final long requestStart = System.nanoTime();
    final StatsHttpUriRequest httpUriRequest = StatsHttpUriRequest.createGenericHttpRequest(request);
    final Request finalRequest = request;
    try {
        T value = httpClient.execute(httpUriRequest, new org.apache.http.client.ResponseHandler<T>() {
            @Override
            public T handleResponse(HttpResponse httpResponse) throws IOException {
                long responseStart = System.nanoTime();

                Response response = new MyResponse(httpResponse);
                try {
                    T value = responseHandler.handle(finalRequest, response);
                    return value;
                } catch (Exception e) {
                    throw new ExceptionFromResponseHandler(e);
                } finally {
                    Duration responseProcessingTime = Duration.nanosSince(responseStart);
                    Duration requestProcessingTime = new Duration(responseStart - requestStart,
                            TimeUnit.NANOSECONDS);

                    stats.record(finalRequest.getMethod(), response.getStatusCode(),
                            httpUriRequest.getBytesWritten(), response.getBytesRead(), requestProcessingTime,
                            responseProcessingTime);
                }
            }
        });
        return value;
    } catch (Exception e) {
        if (e instanceof ExceptionFromResponseHandler) {
            try {
                throw (E) e.getCause();
            } catch (ClassCastException classCastException) {
                // this should never happen but generics suck so be safe
                // handler will be notified of the same exception again below
            }
        } else if (e instanceof ConnectTimeoutException) {
            // apache http client eats the socket timeout exception
            SocketTimeoutException socketTimeoutException = new SocketTimeoutException(e.getMessage());
            socketTimeoutException.setStackTrace(e.getStackTrace());
            return responseHandler.handleException(request, socketTimeoutException);
        }
        return responseHandler.handleException(request, e);
    }
}