Example usage for java.lang RuntimeException getStackTrace

List of usage examples for java.lang RuntimeException getStackTrace

Introduction

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

Prototype

public StackTraceElement[] getStackTrace() 

Source Link

Document

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

Usage

From source file:ca.nrc.cadc.db.DBUtil.java

/**
 * Try to infer a suitable application name.
 *
 * TODO: make this config more generic and accessible to calling code
 *
 * @return//from   w w  w.j av  a  2  s .co m
 */
public static String getMainClass() {
    String ret = "java";
    try {
        throw new RuntimeException();
    } catch (RuntimeException rex) {
        StackTraceElement[] st = rex.getStackTrace();
        for (int i = 0; i < st.length; i++)
            if (st[i].getClassName().startsWith("ca.nrc.cadc."))
                ret = st[i].getClassName();

    }
    ret = shortenClassName(ret);
    return ret;
}

From source file:com.talis.platform.testsupport.VerifyableHandler.java

@Override
public void handle(final String target, final HttpServletRequest req, final HttpServletResponse resp,
        final int dispatch) throws IOException, ServletException {
    try {//  w w  w . j  a v a  2s.  co m
        StubCallDefn defn = getExpectedCallDefn(target, req);
        if (defn == null) {
            assertionLog.append(String.format("Unexpected call: %s %s\n", req.getMethod(), target));
            fail("fail test, no more handlers");
        }

        assertEquals(defn.getExpectedPath(), target);
        assertEquals(defn.getExpectedMethod(), req.getMethod());

        BufferedReader reader = req.getReader();

        String entity = IOUtils.toString(reader);
        assertEquals(defn.getExpectedEntity(), entity);

        for (String key : defn.getHeaders().keySet()) {
            String expected = defn.getHeaders().get(key);
            String value = req.getHeader(key);
            assertEquals("Headers don't match for header " + key, expected, value);
        }

        resp.setStatus(defn.getExpectedReturnStatus());
        resp.setHeader("Content-Type", defn.getExpectedReturnType());
        Map<String, String> returnHeaders = defn.getReturnHeaders();
        if (null != returnHeaders) {
            for (Entry<String, String> header : returnHeaders.entrySet()) {
                resp.setHeader(header.getKey(), header.getValue());
            }
        }

        byte[] expectedReturnEntity = defn.getExpectedReturnEntity();
        if (expectedReturnEntity != null) {
            resp.getOutputStream().write(expectedReturnEntity);
        }
        resp.flushBuffer();
    } catch (RuntimeException t) {
        isOk.set(false);
        assertionLog.append(t.getStackTrace());
        assertionLog.append('\n');
        throw t;
    } catch (Error t) {
        isOk.set(false);
        assertionLog.append(t.getMessage());
        assertionLog.append('\n');
        throw t;
    }
}

From source file:cn.bran.play.JapidTemplateBase.java

@Override
protected void handleException(RuntimeException e) {
    if (Play.mode == Mode.PROD)
        throw e;//w  w  w.  j a  va  2s .  co  m

    // find the latest japidviews exception
    StackTraceElement[] stackTrace = e.getStackTrace();
    for (StackTraceElement ele : stackTrace) {
        String className = ele.getClassName();
        if (className.startsWith("japidviews")) {
            int lineNumber = ele.getLineNumber();
            // TODO: should really remove the Play reference.  Shall we jump to the file system for the source?
            ApplicationClass applicationClass = Play.classes.getApplicationClass(className);
            if (applicationClass != null) {
                // let's get the line of problem
                String jsrc = applicationClass.javaSource;
                String[] splitSrc = jsrc.split("\n");
                String line = splitSrc[lineNumber - 1];
                // can we have a line marker?
                int lineMarker = line.lastIndexOf("// line ");
                if (lineMarker > 0) {
                    int oriLineNumber = Integer.parseInt(line.substring(lineMarker + 8).trim());
                    StackTraceElement[] newStack = new StackTraceElement[stackTrace.length + 1];
                    newStack[0] = new StackTraceElement(sourceTemplate, "", sourceTemplate, oriLineNumber);
                    System.arraycopy(stackTrace, 0, newStack, 1, stackTrace.length);
                    e.setStackTrace(newStack);

                    File file = new File("app/" + sourceTemplate);
                    //         
                    JapidPlayTemplate jpt = new JapidPlayTemplate();
                    jpt.name = sourceTemplate;
                    try {
                        jpt.source = FileUtils.readFileToString(file);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                    throw new TemplateExecutionException(jpt, oriLineNumber, e.getMessage(), e);
                }
            }
        }
    }
    throw e;
}

From source file:com.redhat.rhn.common.localization.LocalizationService.java

private StackTraceElement getCallingMethod() {
    try {/*from  w ww  .  j  a va2  s . c o m*/
        throw new RuntimeException("Stacktrace Dummy Exception");
    } catch (RuntimeException e) {
        try {
            final String prefix = this.getClass().getPackage().getName();
            for (StackTraceElement element : e.getStackTrace()) {
                if (!element.getClassName().startsWith(prefix)) {
                    return element;
                }
            }
        } catch (Throwable t) {
            // dont break - return nothing rather than stop
            return null;
        }
    }
    return null;
}

From source file:com.ltmonitor.jt808.service.impl.CommandService.java

 private void ParseCommandThreadFunc() {
   logger.info("?");
   while (IsContinue) {
      try {/*from w  w w  .j  a  va  2  s .  c  om*/
         ParseCommand();
      } catch (RuntimeException ex) {
         logger.error(ex.getMessage());
         logger.error(ex.getStackTrace());
      }
      try {
         Thread.sleep(getInterval());
      } catch (InterruptedException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
   }

}

From source file:de.tud.inf.db.sparqlytics.olap.Compute.java

/**
 * Extends the given runtime exception with the given query string.
 * //from   w w  w .ja  v  a 2s  .  co m
 * @param ex    the exception to extend
 * @param query the query to add to the exception message
 * @return the extended exception
 */
protected RuntimeException extendRuntimeException(RuntimeException ex, String query) {
    StringBuilder builder = new StringBuilder();
    String message = ex.getMessage();
    if (message != null) {
        builder.append(message).append(System.lineSeparator());
    }
    builder.append(ex.getClass().getSimpleName()).append(" caused by query:").append(System.lineSeparator());
    builder.append(query);
    RuntimeException extended = new RuntimeException(builder.toString(), ex.getCause());
    extended.setStackTrace(ex.getStackTrace());
    return extended;
}

From source file:terse.vm.Terp.java

public void tick() {
    --tickCounter;/*  www. j  a  va  2 s. c o  m*/
    if (tickCounter < 1) {
        try {
            throw new RuntimeException("Going To Throw TooManyTicks");
        } catch (RuntimeException ex) {
            ex.printStackTrace();

            StringBuffer sb = new StringBuffer(ex.toString());
            StackTraceElement[] elems = ex.getStackTrace();
            for (StackTraceElement e : elems) {
                sb.append("\n  * ");
                sb.append(e.toString());
            }

            say(sb.toString());
        }
        throw new TooManyTicks();
    }

}

From source file:net.cbtltd.rest.interhome.A_Handler.java

/**
 * Read prices./*  ww  w .j  av  a 2s .  c  om*/
 *
 * @param version the version
 * @param salesoffice the salesoffice
 * @param currency the currency
 * @param duration the duration
 */
private synchronized void readPrices(Date version, String salesoffice, Currency.Code currency, int duration) {
    String altparty = getAltpartyid();
    String message = "Interhome readPrices Weekly " + altparty;
    LOG.debug(message);
    String fn = null;
    final SqlSession sqlSession = RazorServer.openSession();
    try {
        JAXBContext jc = JAXBContext.newInstance("net.cbtltd.rest.interhome.price");
        Unmarshaller um = jc.createUnmarshaller();

        fn = "price_" + salesoffice + "_" + currency.name().toLowerCase()
                + (duration < 14 ? "" : "_" + String.valueOf(duration)) + ".xml";
        Prices prices = (Prices) um.unmarshal(ftp(fn));

        if (prices != null && prices.getPrice() != null) {
            int count = prices.getPrice().size();
            LOG.debug("Total prices for " + duration + " days: " + count);
        } else {
            LOG.debug("Error, no price file for " + duration + " days");
            return;
        }

        int i = 0;
        for (Price weekprice : prices.getPrice()) {
            String altid = weekprice.getCode();
            //            if (!altid.equals("CH3920.126.1") || !"CH3920.126.1".equalsIgnoreCase(altid)) continue;
            String productid = getProductId(altid);

            if (productid == null) {
                Product product = sqlSession.getMapper(ProductMapper.class)
                        .altread(new NameId(altparty, altid));
                if (product == null) {
                    LOG.error(Error.product_id.getMessage() + " " + weekprice.getCode());
                    continue;
                }
                PRODUCTS.put(altid, product.getId());
                productid = getProductId(altid);
            }

            //            if (!productid.equals("27077") || !String.valueOf(27077).equalsIgnoreCase(productid)) continue;

            Date fromdate = weekprice.getStartdate().toGregorianCalendar().getTime();
            Date todate = weekprice.getEnddate().toGregorianCalendar().getTime();

            if (weekprice.getServices() != null && weekprice.getServices().getService() != null) {
                net.cbtltd.shared.Price mandatory = new net.cbtltd.shared.Price();
                mandatory.setEntitytype(NameId.Type.Mandatory.name());
                mandatory.setEntityid(productid);
                mandatory.setCurrency(currency.name());
                mandatory.setPartyid(altparty);
                mandatory.setVersion(version);

                for (Service service : weekprice.getServices().getService()) {
                    mandatory.setType("Fees");
                    mandatory.setDate(fromdate);
                    mandatory.setTodate(todate);
                    mandatory.setQuantity(0.0);
                    mandatory.setUnit(Unit.EA);
                    mandatory.setAvailable(1);
                    mandatory.setMinStay(1);
                    net.cbtltd.shared.Price existprice = sqlSession.getMapper(PriceMapper.class)
                            .exists(mandatory);
                    if (existprice == null) {
                        sqlSession.getMapper(PriceMapper.class).create(mandatory);
                    } else {
                        mandatory = existprice;
                    }

                    mandatory.setState(net.cbtltd.shared.Price.CREATED);
                    mandatory.setName(getServicename(service.getCode()));
                    mandatory.setMinimum(0.0);
                    mandatory.setValue(
                            service.getServiceprice() == null ? 0.0 : service.getServiceprice().doubleValue());
                    mandatory.setRule("Manual");
                    sqlSession.getMapper(PriceMapper.class).update(mandatory);
                }
                sqlSession.getMapper(PriceMapper.class).cancelversion(mandatory);
            }

            //            Adjustment adjustment = setAdjustment(sqlSession, productid, 7, 7, currency.name(), fromdate, todate, weekprice, "1111111", "week", version);

            Adjustment action = new Adjustment();
            action.setCurrency(currency.name());
            action.setState(Adjustment.Created);
            action.setPartyID(altparty);
            action.setProductID(productid);
            action.setFromDate(fromdate);
            action.setToDate(todate);
            action.setMaxStay(999);
            action.setMinStay(5);

            Adjustment example = sqlSession.getMapper(AdjustmentMapper.class).readbyexample(action);
            if (example == null)
                continue;

            Double rentalPrice;
            if (weekprice.getSpecialoffer() != null
                    && weekprice.getSpecialoffer().getSpecialofferprice() != null) {
                rentalPrice = weekprice.getSpecialoffer().getSpecialofferprice().doubleValue();
            } else {
                rentalPrice = weekprice.getRentalprice().doubleValue();
            }

            Double dailyprice = DAILYPRICES.get(example.getID());
            Double fixprice = example.getFixPrice();
            Double extra = ((rentalPrice - fixprice) / duration) - dailyprice;// ( ( weekprice - fixprice ) / 7 ) - rentalprice[per/day]

            action.setMinStay(duration);
            action.setMaxStay(duration);
            action.setState(null);

            net.cbtltd.shared.Adjustment exists = sqlSession.getMapper(AdjustmentMapper.class).exists(action);
            if (exists == null) {
                sqlSession.getMapper(AdjustmentMapper.class).create(action);
            } else {
                action = exists;
            }

            action.setExtra(PaymentHelper.getAmountWithTwoDecimals(extra));
            action.setServicedays(Adjustment.WEEK);
            action.setState(Adjustment.Created);
            action.setFixPrice(fixprice);
            action.setVersion(version);

            sqlSession.getMapper(AdjustmentMapper.class).update(action);
            sqlSession.getMapper(AdjustmentMapper.class).cancelversion(action);

            LOG.debug(i++ + " WeekPrice: " + " " + weekprice.getCode() + " " + productid + " " + salesoffice
                    + " " + action.getExtra() + " " + currency + " " + duration);
        }
        sqlSession.commit();
    } catch (NullPointerException ex) {
        ex.printStackTrace();
        LOG.error("NPE" + ex.getStackTrace());
        sqlSession.rollback();
    } catch (RuntimeException e) {
        e.printStackTrace();
        LOG.error("RuntimeExc " + e.getStackTrace());
        sqlSession.rollback();
    } catch (Throwable x) {
        sqlSession.rollback();
        LOG.error(x.getClass().getName() + ": " + x.getMessage());
    } finally {
        sqlSession.close();
        delete(fn);
    }
}

From source file:org.apache.maven.surefire.its.fixture.MavenLauncher.java

StackTraceElement[] getStackTraceElements() {
    try {/*from www .  j  ava  2s.  c o m*/
        throw new RuntimeException();
    } catch (RuntimeException e) {
        return e.getStackTrace();
    }
}

From source file:org.codelibs.fess.web.base.FessBaseAction.java

protected void buildApplicationExceptionStackTrace(RuntimeException cause, StringBuilder sb) {
    final StackTraceElement[] stackTrace = cause.getStackTrace();
    if (stackTrace == null) { // just in case
        return;//from w  w  w .j ava 2 s.c o m
    }
    int index = 0;
    for (StackTraceElement element : stackTrace) {
        if (index > 10) { // not all because it's not error
            break;
        }
        final String className = element.getClassName();
        final String fileName = element.getFileName(); // might be null
        final int lineNumber = element.getLineNumber();
        final String methodName = element.getMethodName();
        sb.append("\n at ").append(className).append(".").append(methodName);
        sb.append("(").append(fileName);
        if (lineNumber >= 0) {
            sb.append(":").append(lineNumber);
        }
        sb.append(")");
        ++index;
    }
}