Example usage for java.util.logging LogRecord setThrown

List of usage examples for java.util.logging LogRecord setThrown

Introduction

In this page you can find the example usage for java.util.logging LogRecord setThrown.

Prototype

public void setThrown(Throwable thrown) 

Source Link

Document

Set a throwable associated with the log event.

Usage

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   w  w w .j a va 2 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:jenkins.security.plugins.ldap.FromUserRecordLDAPGroupMembershipStrategy.java

@Override
public GrantedAuthority[] getGrantedAuthorities(LdapUserDetails ldapUser) {
    List<GrantedAuthority> result = new ArrayList<GrantedAuthority>();
    Attributes attributes = ldapUser.getAttributes();
    final String attributeName = getAttributeName();
    Attribute attribute = attributes == null ? null : attributes.get(attributeName);
    if (attribute != null) {
        try {/*w w  w  . jav a 2 s.c  om*/
            for (Object value : Collections.list(attribute.getAll())) {
                String groupName = String.valueOf(value);
                try {
                    LdapName dn = new LdapName(groupName);
                    groupName = String.valueOf(dn.getRdn(dn.size() - 1).getValue());
                } catch (InvalidNameException e) {
                    LOGGER.log(Level.FINEST, "Expected a Group DN but found: {0}", groupName);
                }
                result.add(new GrantedAuthorityImpl(groupName));
            }
        } catch (NamingException e) {
            LogRecord lr = new LogRecord(Level.FINE,
                    "Failed to retrieve member of attribute ({0}) from LDAP user details");
            lr.setThrown(e);
            lr.setParameters(new Object[] { attributeName });
            LOGGER.log(lr);
        }

    }
    return result.toArray(new GrantedAuthority[result.size()]);
}

From source file:com.cloudbees.jenkins.support.SupportPlugin.java

@Override
public void postInitialize() throws Exception {
    super.postInitialize();
    for (Component component : getComponents()) {
        try {//www. jav  a2  s.  c o m
            component.start(getContext());
        } catch (Throwable t) {
            LogRecord logRecord = new LogRecord(Level.WARNING, "Exception propagated from component: {0}");
            logRecord.setThrown(t);
            logRecord.setParameters(new Object[] { component.getDisplayName() });
            logger.log(logRecord);
        }
    }
}

From source file:com.cloudbees.jenkins.support.SupportPlugin.java

public List<LogRecord> getAllLogRecords(final Node node) throws IOException, InterruptedException {
    if (node != null) {
        VirtualChannel channel = node.getChannel();
        if (channel != null) {
            final Future<List<LogRecord>> future = channel.callAsync(new LogFetcher());
            try {
                return future.get(REMOTE_OPERATION_TIMEOUT_MS, TimeUnit.MILLISECONDS);
            } catch (ExecutionException e) {
                final LogRecord lr = new LogRecord(Level.WARNING, "Could not retrieve remote log records");
                lr.setThrown(e);
                return Collections.singletonList(lr);
            } catch (TimeoutException e) {
                Computer.threadPoolForRemoting.submit(() -> {
                    List<LogRecord> records;
                    try {
                        records = future.get(REMOTE_OPERATION_CACHE_TIMEOUT_SEC, TimeUnit.SECONDS);
                    } catch (InterruptedException e1) {
                        final LogRecord lr = new LogRecord(Level.WARNING,
                                "Could not retrieve remote log records");
                        lr.setThrown(e1);
                        records = Collections.singletonList(lr);
                    } catch (ExecutionException e1) {
                        final LogRecord lr = new LogRecord(Level.WARNING,
                                "Could not retrieve remote log records");
                        lr.setThrown(e1);
                        records = Collections.singletonList(lr);
                    } catch (TimeoutException e1) {
                        final LogRecord lr = new LogRecord(Level.WARNING,
                                "Could not retrieve remote log records");
                        lr.setThrown(e1);
                        records = Collections.singletonList(lr);
                        future.cancel(true);
                    }/*w  ww.  j  av a2s. c o  m*/
                    synchronized (SupportPlugin.this) {
                        if (logRecords == null) {
                            logRecords = new WeakHashMap<>();
                        }
                        logRecords.put(node, records);
                    }
                });
                synchronized (this) {
                    if (logRecords != null) {
                        List<LogRecord> result = logRecords.get(node);
                        if (result != null) {
                            result = new ArrayList<>(result);
                            final LogRecord lr = new LogRecord(Level.WARNING,
                                    "Using cached remote log records");
                            lr.setThrown(e);
                            result.add(lr);
                            return result;
                        }
                    } else {
                        final LogRecord lr = new LogRecord(Level.WARNING,
                                "No previous cached remote log records");
                        lr.setThrown(e);
                        return Collections.singletonList(lr);
                    }
                }
            }
        }
    }
    return Collections.emptyList();
}

From source file:com.cloudbees.plugins.credentials.impl.CertificateCredentialsImpl.java

/**
 * Returns the {@link KeyStore} containing the certificate.
 *
 * @return the {@link KeyStore} containing the certificate.
 *//*from   www. j  a  v a2  s  .  co m*/
@NonNull
public synchronized KeyStore getKeyStore() {
    long lastModified = keyStoreSource.getKeyStoreLastModified();
    if (keyStore == null || keyStoreLastModified < lastModified) {
        KeyStore keyStore;
        try {
            keyStore = KeyStore.getInstance("PKCS12");
        } catch (KeyStoreException e) {
            throw new IllegalStateException("PKCS12 is a keystore type per the JLS spec", e);
        }
        try {
            keyStore.load(new ByteArrayInputStream(keyStoreSource.getKeyStoreBytes()), toCharArray(password));
        } catch (CertificateException e) {
            LogRecord lr = new LogRecord(Level.WARNING, "Credentials ID {0}: Could not load keystore from {1}");
            lr.setParameters(new Object[] { getId(), keyStoreSource });
            lr.setThrown(e);
            LOGGER.log(lr);
        } catch (NoSuchAlgorithmException e) {
            LogRecord lr = new LogRecord(Level.WARNING, "Credentials ID {0}: Could not load keystore from {1}");
            lr.setParameters(new Object[] { getId(), keyStoreSource });
            lr.setThrown(e);
            LOGGER.log(lr);
        } catch (IOException e) {
            LogRecord lr = new LogRecord(Level.WARNING, "Credentials ID {0}: Could not load keystore from {1}");
            lr.setParameters(new Object[] { getId(), keyStoreSource });
            lr.setThrown(e);
            LOGGER.log(lr);
        }
        this.keyStore = keyStore;
        this.keyStoreLastModified = lastModified;
    }
    return keyStore;
}

From source file:hudson.model.Computer.java

/**
 * This method tries to compute the name of the host that's reachable by all the other nodes.
 *
 * <p>/*from   w ww.j a  va 2  s  .  c  om*/
 * Since it's possible that the agent is not reachable from the master (it may be behind a firewall,
 * connecting to master via JNLP), this method may return null.
 *
 * It's surprisingly tricky for a machine to know a name that other systems can get to,
 * especially between things like DNS search suffix, the hosts file, and YP.
 *
 * <p>
 * So the technique here is to compute possible interfaces and names on the agent,
 * then try to ping them from the master, and pick the one that worked.
 *
 * <p>
 * The computation may take some time, so it employs caching to make the successive lookups faster.
 *
 * @since 1.300
 * @return
 *      null if the host name cannot be computed (for example because this computer is offline,
 *      because the agent is behind the firewall, etc.)
 */
public String getHostName() throws IOException, InterruptedException {
    if (hostNameCached)
        // in the worst case we end up having multiple threads computing the host name simultaneously, but that's not harmful, just wasteful.
        return cachedHostName;

    VirtualChannel channel = getChannel();
    if (channel == null)
        return null; // can't compute right now

    for (String address : channel.call(new ListPossibleNames())) {
        try {
            InetAddress ia = InetAddress.getByName(address);
            if (!(ia instanceof Inet4Address)) {
                LOGGER.log(Level.FINE, "{0} is not an IPv4 address", address);
                continue;
            }
            if (!ComputerPinger.checkIsReachable(ia, 3)) {
                LOGGER.log(Level.FINE, "{0} didn't respond to ping", address);
                continue;
            }
            cachedHostName = ia.getCanonicalHostName();
            hostNameCached = true;
            return cachedHostName;
        } catch (IOException e) {
            // if a given name fails to parse on this host, we get this error
            LogRecord lr = new LogRecord(Level.FINE, "Failed to parse {0}");
            lr.setThrown(e);
            lr.setParameters(new Object[] { address });
            LOGGER.log(lr);
        }
    }

    // allow the administrator to manually specify the host name as a fallback. HUDSON-5373
    cachedHostName = channel.call(new GetFallbackName());
    hostNameCached = true;
    return cachedHostName;
}

From source file:jenkins.branch.MultiBranchProject.java

/**
 * {@inheritDoc}//w  ww .  j  av  a  2  s .c o m
 */
@Override
public void onLoad(ItemGroup<? extends Item> parent, String name) throws IOException {
    super.onLoad(parent, name);
    init2();
    try {
        srcDigest = Util.getDigestOf(Items.XSTREAM2.toXML(sources));
    } catch (XStreamException e) {
        srcDigest = null;
    }
    BranchProjectFactory<P, R> factory = getProjectFactory();
    try {
        facDigest = Util.getDigestOf(Items.XSTREAM2.toXML(factory));
    } catch (XStreamException e) {
        facDigest = null;
    }
    if (state == null) {
        state = new State(this);
    }
    try {
        state.load();
    } catch (XStreamException | IOException e) {
        LOGGER.log(Level.WARNING, "Could not read persisted state, will be recovered on next index.", e);
        state.reset();
    }
    // optimize lookup of sources by building a temporary map that is equivalent to getSCMSource(id) in results
    Map<String, SCMSource> sourceMap = new HashMap<>();
    for (BranchSource source : sources) {
        SCMSource s = source.getSource();
        String id = s.getId();
        if (!sourceMap.containsKey(id)) { // only the first match should win
            sourceMap.put(id, s);
        }
    }
    for (P item : getItems()) {
        if (factory.isProject(item)) {
            Branch oldBranch = factory.getBranch(item);
            SCMSource source = sourceMap.get(oldBranch.getSourceId());
            if (source == null || source instanceof NullSCMSource) {
                continue;
            }
            SCMHead oldHead = oldBranch.getHead();
            SCMHead newHead = SCMHeadMigration.readResolveSCMHead(source, oldHead);
            if (newHead != oldHead) {
                LOGGER.log(Level.INFO,
                        "Job {0}: a plugin upgrade is requesting migration of branch from {1} to {2}",
                        new Object[] { item.getFullName(), oldHead.getClass(), newHead.getClass() });
                try {
                    Branch newBranch = new Branch(oldBranch.getSourceId(), newHead, oldBranch.getScm(),
                            oldBranch.getProperties());
                    newBranch.setActions(oldBranch.getActions());
                    factory.setBranch(item, newBranch);
                    SCMRevision revision = factory.getRevision(item);
                    factory.setRevisionHash(item, SCMHeadMigration.readResolveSCMRevision(source, revision));
                } catch (IOException | RuntimeException e) {
                    LogRecord lr = new LogRecord(Level.WARNING,
                            "Job {0}: Could not complete migration of branch from type {1} to {2}. "
                                    + "The side-effect of this is that the next index may trigger a rebuild "
                                    + "of the job (after which the issue will be resolved)");
                    lr.setThrown(e);
                    lr.setParameters(
                            new Object[] { item.getFullName(), oldHead.getClass(), newHead.getClass() });
                    LOGGER.log(lr);
                }
            }
        }
    }
}

From source file:org.apache.cxf.common.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);
    }// w w  w .  j a  v  a  2  s .com

    //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.apache.tomee.jul.formatter.SimpleTomEEFormatterTest.java

@Test
public void formatNullThrown() throws Exception {
    final String previousLineSeparatorProperty = System.getProperty(LINE_SEPARATOR_KEY);
    try {//from   ww w.j  av a 2 s. co m
        final String lineSeparatorValue = "\n";
        final String logMessage = "An example log record";
        final Level level = Level.FINEST;

        System.setProperty(LINE_SEPARATOR_KEY, lineSeparatorValue);
        final LogRecord logRecordInput = new LogRecord(level, logMessage);
        logRecordInput.setThrown(null);

        final Formatter formatter = new SimpleTomEEFormatter();
        final String actualFormatOutput = formatter.format(logRecordInput);

        final String expectedFormatOutput = level.getLocalizedName() + " - " + logMessage + "\n";

        assertEquals(expectedFormatOutput, actualFormatOutput);
    } finally {
        System.setProperty(LINE_SEPARATOR_KEY, previousLineSeparatorProperty);
    }
}

From source file:org.apache.tomee.jul.formatter.SimpleTomEEFormatterTest.java

@Test
public void formatNotNullThrown() throws Exception {
    final String previousLineSeparatorProperty = System.getProperty(LINE_SEPARATOR_KEY);

    try {//  www .j  a v  a2  s .co  m
        final String lineSeparatorValue = "\n";
        final String logMessage = "An example log record";
        final Level level = Level.CONFIG;
        final String exceptionMessage = "An example exception";
        final Throwable thrown = new Exception(exceptionMessage);

        System.setProperty(LINE_SEPARATOR_KEY, lineSeparatorValue);
        final LogRecord logRecordInput = new LogRecord(level, logMessage);
        logRecordInput.setThrown(thrown);

        final Formatter formatter = new SimpleTomEEFormatter();
        final String actualFormatOutput = formatter.format(logRecordInput);

        final String expectedFormatOutput = level.getLocalizedName() + " - " + logMessage + lineSeparatorValue
                + ExceptionUtils.getStackTrace(thrown);

        assertEquals(expectedFormatOutput, actualFormatOutput);
    } finally {
        System.setProperty(LINE_SEPARATOR_KEY, previousLineSeparatorProperty);
    }
}