Example usage for java.lang Throwable Throwable

List of usage examples for java.lang Throwable Throwable

Introduction

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

Prototype

public Throwable() 

Source Link

Document

Constructs a new throwable with null as its detail message.

Usage

From source file:io.stallion.services.Log.java

public static void warn(Throwable ex, String message, Object... args) {
    if (getLogLevel().intValue() > Level.WARNING.intValue()) {
        return;/*from   w  w  w  .  j a v a2 s .  c o m*/
    }
    if (args.length > 0) {
        message = MessageFormat.format(message, args);
    }
    Throwable t = new Throwable();
    StackTraceElement stackTraceElement = t.getStackTrace()[1];
    String clz = stackTraceElement.getClassName().replace("io.stallion.", "");
    String method = stackTraceElement.getMethodName() + ":" + t.getStackTrace()[1].getLineNumber();
    logger.logp(Level.WARNING, clz, method, message, ex);
}

From source file:org.apache.naming.modules.fs.FileDirContext.java

public void setAttribute(String name, Object v) {
    new Throwable().printStackTrace();
    System.out.println(name + " " + v);
}

From source file:com.heliosapm.opentsdb.client.jvmjmx.custom.aggregation.AggregateFunction.java

/**
 * Computes and returns the aggregate for the named aggregator and object of nput items.
 * The object is introspected to determine if it is:<ul>
 *  <li>Null</li>/*from   w  w w .j  a va  2s . co  m*/
 *    <li>{@link java.util.Map}</li>
 *    <li>{@link java.util.Collection}</li>
 *    <li>An array</li>
 * </ul>.
 * If it is none of the above, a runtime exception is thrown.
 * If it is a map or an array, it is converted to a list for aggregate computation.
 * @param name The name of the aggregator function
 * @param item The object of items to aggregate
 * @return the aggregate value
 * TODO:  Do we need to support multi dimmensional arrays ?
 */
@SuppressWarnings("unchecked")
public static Object aggregate(CharSequence name, Object item) {
    final List<Object> items;
    final AggregateFunction function = AggregateFunction.forName(name);
    if (item == null) {
        items = Collections.EMPTY_LIST;
    } else if (item instanceof Map) {
        Map<Object, Object> map = (Map<Object, Object>) item;
        items = new ArrayList<Object>(map.keySet());
    } else if (item instanceof Collection) {
        items = new ArrayList<Object>((Collection<Object>) item);
    } else if (item.getClass().isArray()) {
        int length = Array.getLength(item);
        items = new ArrayList<Object>(length);
        for (int i = 0; i < length; i++) {
            items.add(i, Array.get(item, i));
        }
    } else {
        throw new IllegalArgumentException("Aggregate object of type [" + item.getClass().getName()
                + "] was not a Map, Collection or Array", new Throwable());
    }
    return function.aggregate(items);
}

From source file:fr.opensagres.xdocreport.core.logging.LogUtils.java

private static void doLog(Logger log, Level level, String msg, Throwable t) {
    LogRecord record = new LogRecord(level, msg);

    record.setLoggerName(log.getName());
    record.setResourceBundleName(log.getResourceBundleName());
    record.setResourceBundle(log.getResourceBundle());

    if (t != null) {
        record.setThrown(t);/*from ww  w  .j a v a2  s  .c om*/
    }

    // try to get the right class name/method name - just trace
    // back the stack till we get out of this class
    StackTraceElement stack[] = (new Throwable()).getStackTrace();
    String cname = LogUtils.class.getName();
    for (int x = 0; x < stack.length; x++) {
        StackTraceElement frame = stack[x];
        if (!frame.getClassName().equals(cname)) {
            record.setSourceClassName(frame.getClassName());
            record.setSourceMethodName(frame.getMethodName());
            break;
        }
    }
    log.log(record);
}

From source file:org.apereo.portal.url.xml.XsltPortalUrlProvider.java

/**
 * Get the portlet URL builder for the specified fname or layoutId (fname takes precedence)
 * @param request//from w w w.  ja v  a  2  s .co m
 * @param portalUrlBuilder
 * @param fname - can be empty string
 * @param layoutId - can by empty string
 * @param state - can be empty string
 * @param mode - can be empty string
 * @param copyCurrentRenderParameters
 * @param resourceId - can be empty string
 * @return IPortletUrlBuilder
 * @since uPortal 4.1
 */
public IPortletUrlBuilder getPortletUrlBuilder(HttpServletRequest request, IPortalUrlBuilder portalUrlBuilder,
        String fname, String layoutId, String state, String mode, String copyCurrentRenderParameters,
        String resourceId) {
    final IPortletUrlBuilder portletUrlBuilder;

    if (StringUtils.isNotEmpty(fname)) {
        final IPortletWindow portletWindow = this.portletWindowRegistry
                .getOrCreateDefaultPortletWindowByFname(request, fname);
        final IPortletWindowId portletWindowId = portletWindow.getPortletWindowId();
        portletUrlBuilder = portalUrlBuilder.getPortletUrlBuilder(portletWindowId);
    } else if (StringUtils.isNotEmpty(layoutId)) {
        final IPortletWindow portletWindow = this.portletWindowRegistry
                .getOrCreateDefaultPortletWindowByLayoutNodeId(request, layoutId);
        final IPortletWindowId portletWindowId = portletWindow.getPortletWindowId();
        portletUrlBuilder = portalUrlBuilder.getPortletUrlBuilder(portletWindowId);
    } else {
        final IPortletWindowId targetPortletWindowId = portalUrlBuilder.getTargetPortletWindowId();
        if (targetPortletWindowId == null) {
            if (this.logger.isDebugEnabled()) {
                this.logger.warn(
                        "Can only target the default portlet if the root portal-url targets a portlet.",
                        new Throwable());
            } else {
                this.logger.warn(
                        "Can only target the default portlet if the root portal-url targets a portlet. Enable debug for stack trace.");
            }
            return new FailSafePortletUrlBuilder(null, portalUrlBuilder);
        }

        portletUrlBuilder = portalUrlBuilder.getTargetedPortletUrlBuilder();
    }

    portletUrlBuilder.setCopyCurrentRenderParameters(Boolean.parseBoolean(copyCurrentRenderParameters));

    if (StringUtils.isNotEmpty(state)) {
        portletUrlBuilder.setWindowState(PortletUtils.getWindowState(state));
    }

    if (StringUtils.isNotEmpty(mode)) {
        portletUrlBuilder.setPortletMode(PortletUtils.getPortletMode(mode));
    }

    if (StringUtils.isNotEmpty(resourceId)
            && portletUrlBuilder.getPortalUrlBuilder().getUrlType() == UrlType.RESOURCE) {
        portletUrlBuilder.setResourceId(resourceId);
    }

    return portletUrlBuilder;
}

From source file:org.apache.jk.common.ChannelUn.java

public int receive(Msg msg, MsgContext ep) throws IOException {
    int rc = super.nativeDispatch(msg, ep, CH_READ, 1);

    if (rc != 0) {
        log.error("receive error:   " + rc, new Throwable());
        return -1;
    }//w  w  w .j ava  2  s.  c  o  m

    msg.processHeader();

    if (log.isDebugEnabled())
        log.debug("receive:  total read = " + msg.getLen());

    return msg.getLen();
}

From source file:org.apache.zeppelin.rest.NotebookRestApiTest.java

@Test
public void testClearAllParagraphOutput() throws IOException {
    // Create note and set result explicitly
    Note note = ZeppelinServer.notebook.createNote(anonymous);
    Paragraph p1 = note.addParagraph(AuthenticationInfo.ANONYMOUS);
    InterpreterResult result = new InterpreterResult(InterpreterResult.Code.SUCCESS,
            InterpreterResult.Type.TEXT, "result");
    p1.setResult(result);//  www  .  j a v  a  2s  .  c om

    Paragraph p2 = note.addParagraph(AuthenticationInfo.ANONYMOUS);
    p2.setReturn(result, new Throwable());

    // clear paragraph result
    PutMethod put = httpPut("/notebook/" + note.getId() + "/clear", "");
    LOG.info("test clear paragraph output response\n" + put.getResponseBodyAsString());
    assertThat(put, isAllowed());
    put.releaseConnection();

    // check if paragraph results are cleared
    GetMethod get = httpGet("/notebook/" + note.getId() + "/paragraph/" + p1.getId());
    assertThat(get, isAllowed());
    Map<String, Object> resp1 = gson.fromJson(get.getResponseBodyAsString(),
            new TypeToken<Map<String, Object>>() {
            }.getType());
    Map<String, Object> resp1Body = (Map<String, Object>) resp1.get("body");
    assertNull(resp1Body.get("result"));

    get = httpGet("/notebook/" + note.getId() + "/paragraph/" + p2.getId());
    assertThat(get, isAllowed());
    Map<String, Object> resp2 = gson.fromJson(get.getResponseBodyAsString(),
            new TypeToken<Map<String, Object>>() {
            }.getType());
    Map<String, Object> resp2Body = (Map<String, Object>) resp2.get("body");
    assertNull(resp2Body.get("result"));
    get.releaseConnection();

    //cleanup
    ZeppelinServer.notebook.removeNote(note.getId(), anonymous);
}

From source file:org.tradex.camel.endpoint.file.FilePollerEndpoint.java

/**
 * Builds and registers an idempotent repository for the passed directory name
 * @param directoryName The directory name files are being polled from
 * @return The bean name of the idempotent repository
 *//*ww  w.ja  va 2 s  .c om*/
protected String buildIdempotentRepository(String directoryName) {
    String idempotentFactoryName = null;
    String[] repoNames = applicationContext.getBeanNamesForType(IdempotentRepository.class, true, false);
    if (repoNames.length == 0) {
        throw new RuntimeException("No IdempotentRepository Bean Found", new Throwable());
    }
    for (String repoName : repoNames) {
        if (applicationContext.isPrototype(repoName)) {
            idempotentFactoryName = repoName;
            break;
        }
    }
    if (idempotentFactoryName == null) {
        throw new RuntimeException("No IdempotentRepository Prototype Bean Found", new Throwable());
    }
    String generatedId = directoryName.replace('/', '_').replace('\\', '_').replace(':', '_');
    ObjectName on = JMXHelper
            .objectName("org.tradex.idempotent:service=IdempotentRepository,name=" + generatedId);
    IdempotentRepository<?> repository = (IdempotentRepository<?>) applicationContext
            .getBean(idempotentFactoryName, dataSource, generatedId, on);
    ((GenericApplicationContext) applicationContext).getBeanFactory().registerSingleton(generatedId,
            repository);
    //((GenericApplicationContext)applicationContext).getBeanFactory().configureBean(repository, generatedId);

    idempotentRepositories.put(directoryName, repository);
    log.info("Created and registered Idempotent Repository [" + generatedId + "]");
    return generatedId;
}

From source file:com.malin.rxjava.activity.MainActivity.java

private void method0() {

    //1:,?//from   w  w  w . j  a v a2 s .  c  o  m
    //:RxJava  Observable.create() ? Observable ?
    Observable<String> observable = Observable.create(new Observable.OnSubscribe<String>() {
        @Override
        public void call(Subscriber<? super String> subscriber) {
            subscriber.onNext("Hello");
            subscriber.onNext("World");
            subscriber.onNext("!");
            subscriber.onCompleted();
            subscriber.onError(new Throwable());
            Logger.d("-observable->call()->onCompleted()??");
        }
    });

    /**
     * ? OnSubscribe ?
     * OnSubscribe  Observable 
     * Observable OnSubscribe  call() ????
     * ??subscriber  onNext()  onCompleted()
     * ???
     */
    //2:
    Observer<String> observer = new Observer<String>() {
        @Override
        public void onCompleted() {
            Logger.d("-observer:onCompleted()");
        }

        @Override
        public void onError(Throwable e) {
            Logger.d("-observer:onError" + e.getMessage());
        }

        @Override
        public void onNext(String s) {
            Logger.d("-observer:onNext():" + s);
            // getException();//??,onError()....
        }
    };

    //3:--
    observable.subscribe(observer);
}

From source file:co.cask.hydrator.plugin.batch.source.ExcelInputReader.java

@Override
public void transform(KeyValue<LongWritable, Object> input, Emitter<StructuredRecord> emitter)
        throws Exception {

    getOutputSchema();//from  ww  w  .  j a v a2 s.c om
    StructuredRecord.Builder builder = StructuredRecord.builder(outputSchema);
    String inputValue = input.getValue().toString();

    String[] excelRecords = inputValue.split("\t");

    String fileName = excelRecords[1];
    String sheetName = excelRecords[2];
    String ifEndRow = excelRecords[3];

    int prevRowNum = Integer.parseInt(excelRecords[0]);

    if (filePrevRowNumMap.containsKey(fileName)) {
        if (prevRowNum - filePrevRowNumMap.get(fileName) > 1
                && excelInputreaderConfig.terminateIfEmptyRow.equalsIgnoreCase("true")) {
            throw new ExecutionException(
                    "Encountered empty row while reading Excel file :" + fileName + " . Terminating processing",
                    new Throwable());
        }
    }

    filePrevRowNumMap.put(fileName, prevRowNum);

    Map<String, String> excelColumnValueMap = new HashMap<>();

    for (String columns : excelRecords) {
        String[] columnValueArray = columns.split("\r");
        if (columnValueArray.length > 1) {
            String columnName = columnValueArray[0];
            String columnValue = columnValueArray[1];

            if (columnMapping.containsKey(columnName)) {
                excelColumnValueMap.put(columnMapping.get(columnName), columnValue);
            } else {
                excelColumnValueMap.put(columnName, columnValue);
            }
        }
    }

    try {
        for (Schema.Field field : outputSchema.getFields()) {
            String fieldName = field.getName();
            if (excelColumnValueMap.containsKey(fieldName)) {
                builder.convertAndSet(fieldName, excelColumnValueMap.get(fieldName));
            } else {
                builder.set(fieldName, NULL);
            }
        }

        builder.set(FILE, new Path(fileName).getName());
        builder.set(SHEET, sheetName);

        if (ifEndRow.equalsIgnoreCase(END)) {
            trackProcessedFiles(fileName);
        }

        emitter.emit(builder.build());
    } catch (Exception e) {
        switch (excelInputreaderConfig.ifErrorRecord) {
        case EXIT_ON_ERROR:
            throw new IllegalStateException("Terminating processing on error : " + e.getMessage());
        case WRITE_ERROR_DATASET:
            StructuredRecord.Builder errorRecordBuilder = StructuredRecord.builder(errorRecordSchema);
            errorRecordBuilder.set(KEY, fileName + "_" + sheetName + "_" + excelRecords[0]);
            errorRecordBuilder.set(FILE, fileName);
            errorRecordBuilder.set(SHEET, sheetName);
            errorRecordBuilder.set(RECORD, inputValue);
            writeErrorRecordToDataset(errorRecordBuilder.build());
            break;
        default:
            //ignore on error
            break;
        }

    }

}