Example usage for org.apache.commons.lang3.exception ExceptionUtils getStackTrace

List of usage examples for org.apache.commons.lang3.exception ExceptionUtils getStackTrace

Introduction

In this page you can find the example usage for org.apache.commons.lang3.exception ExceptionUtils getStackTrace.

Prototype

public static String getStackTrace(final Throwable throwable) 

Source Link

Document

Gets the stack trace from a Throwable as a String.

The result of this method vary by JDK version as this method uses Throwable#printStackTrace(java.io.PrintWriter) .

Usage

From source file:ke.co.tawi.babblesms.server.persistence.template.MessageTemplateDAO.java

/**
*
*//*  w w w. j ava 2  s  . c o m*/
@Override
public List<MessageTemplate> getTemplates(Account account) {
    List<MessageTemplate> list = null;

    BeanProcessor b = new BeanProcessor();

    try (Connection conn = dbCredentials.getConnection();
            PreparedStatement pstmt = conn.prepareStatement(
                    "SELECT * FROM MessageTemplate WHERE accountuuid=? ORDER BY title ASC;");) {

        pstmt.setString(1, account.getUuid());
        try (ResultSet rset = pstmt.executeQuery();) {

            list = b.toBeanList(rset, MessageTemplate.class);

        }
    } catch (SQLException e) {
        logger.error("SQL Exception when getting all messageTemplates" + account.getUuid());
        logger.error(ExceptionUtils.getStackTrace(e));
    }
    return list;
}

From source file:com.aurel.track.persist.ReflectionHelper.java

/**
 * This method replaces all occurrences of <code>ProjectType</code> 
 * value oldOID with project type value newOID going through all related
 * tables in the database./*from   w ww .ja v  a  2  s.c om*/
 * @param oldOID object identifier of list type to be replaced
 * @param newOID object identifier of replacement list type
 */
public static boolean hasDependentData(Class[] peerClasses, String[] fields, Integer oldOID) {
    // Do this using reflection.
    Criteria selectCriteria = new Criteria();
    for (int i = 0; i < peerClasses.length; ++i) {
        Class peerClass = peerClasses[i];
        String field = fields[i];
        selectCriteria.clear();
        selectCriteria.add(field, oldOID, Criteria.EQUAL);
        try {
            Class partypes[] = new Class[1];
            partypes[0] = Criteria.class;
            Method meth = peerClass.getMethod("doSelect", partypes);

            Object arglist[] = new Object[1];
            arglist[0] = selectCriteria;
            List results = (List) meth.invoke(peerClass, arglist);
            if (results != null && !results.isEmpty()) {
                return true;
            }
        } catch (Exception e) {
            LOGGER.error("Exception when trying to find dependent data for " + "oldOID " + oldOID
                    + " for class " + peerClass.toString() + " and field " + field + ": " + e.getMessage());
            LOGGER.debug(ExceptionUtils.getStackTrace(e));
        }
    }
    return false;
}

From source file:com.aurel.track.item.AddScreenshotAction.java

public String saveScreenshot() {
    LOGGER.debug("Save screenshot workItemID=" + workItemID);
    List<LabelValueBean> errors = new ArrayList<LabelValueBean>();
    if (file == null || file.length() == 0) {
        String err = getText("common.err.required",
                new String[] { getText("report.export.manager.upload.file") });
        errors.add(new LabelValueBean(err, "file"));
        JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
        return null;
    }/*  w  w w  .j  a  v a  2 s  . c  o  m*/
    if (!file.endsWith(".png")) {
        file = file + ".png";
    }
    ApplicationBean applicationBean = (ApplicationBean) application.get(Constants.APPLICATION_BEAN);
    Double maxAttachmentSizeInMb = AttachBL.getMaxAttachmentSizeInMb(applicationBean);
    int MAXFILESIZE = AttachBL.getMaxFileSize(applicationBean);
    if (maxAttachmentSizeInMb != null && Double.compare(maxAttachmentSizeInMb.doubleValue(), 0.0) != 0) {
        MAXFILESIZE = (int) (maxAttachmentSizeInMb.doubleValue() * 1024 * 1024);
    } else {
        MAXFILESIZE = 4 * 1024 * 1024;
    }
    byte[] bytearray = null;
    try {
        bytearray = new Base64().decode(bytes);
    } catch (Exception e1) {
        // TODO Auto-generated catch block
        LOGGER.error(ExceptionUtils.getStackTrace(e1));
        errors.add(new LabelValueBean(e1.getMessage(), "file"));
        JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
        return null;
    }

    if (bytearray.length > MAXFILESIZE) {
        errors.add(new LabelValueBean(
                getText("attachment.maxLengthExceeded", new String[] { maxAttachmentSizeInMb + "" }), "file"));
        JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
        return null;
    }
    int maxDescriptionSize = ApplicationBean.getInstance().getDescriptionMaxLength();
    if (description.length() > maxDescriptionSize) {
        errors.add(new LabelValueBean(getText("item.err.tooLong",
                new String[] { getText("common.lbl.description"), Integer.toString(maxDescriptionSize) }),
                "description"));
        JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
        return null;

    }
    InputStream is = new ByteArrayInputStream(bytearray);
    ApplicationBean appBean = ApplicationBean.getInstance();
    if (appBean.isBackupInProgress()) {
        errors.add(new LabelValueBean(getText("item.tabs.attachment.err.backupInProgress"), "file"));
        JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
        return null;
    }
    if (workItemID == null/*||workItemID.intValue()==-1*/) {
        HttpServletRequest request = org.apache.struts2.ServletActionContext.getRequest();
        HttpSession httpSession = request.getSession();
        WorkItemContext ctx = (WorkItemContext) session.get("workItemContext");
        if (ctx == null) {
            LOGGER.error("No context on session");
            errors.add(new LabelValueBean("No context on session", "file"));
            JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
            return null;
        }
        List<TAttachmentBean> attachments = ctx.getAttachmentsList();
        if (attachments == null) {
            attachments = new ArrayList<TAttachmentBean>();
        }
        String sessionID = httpSession.getId();
        try {
            AttachBL.saveLocal(workItemID, description, file, is, attachments, sessionID, personID);
        } catch (AttachBLException e) {
            String err = "";
            if (e.getLocalizedKey() != null) {
                err = getText(e.getLocalizedKey(), e.getLocalizedParameteres());
            } else {
                err = e.getMessage();
            }
            errors.add(new LabelValueBean(err, "file"));
            JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
            return null;

        }
        ctx.setAttachmentsList(attachments);
    } else {
        try {
            AttachBL.save(workItemID, description, file, is, personID);
            //add to history
            HistorySaverBL.addAttachment(workItemID, personID, locale, file, description,
                    Long.valueOf(bytearray.length), false);
        } catch (AttachBLException e) {
            LOGGER.error("Can't save attachemnt", e);
            String err = "";
            if (e.getLocalizedKey() != null) {
                err = getText(e.getLocalizedKey(), e.getLocalizedParameteres());
            } else {
                err = e.getMessage();
            }
            errors.add(new LabelValueBean(err, "file"));
            JSONUtility.encodeJSONErrors(ServletActionContext.getResponse(), errors);
            return null;
        }
    }
    description = null;
    JSONUtility.encodeJSONSuccess(ServletActionContext.getResponse());
    return null;
}

From source file:ke.co.tawi.babblesms.server.utils.net.EmailUtil.java

/**
 * @see java.lang.Thread#run()// www.  j a  v a2 s  .c om
 */
@Override
public void run() {
    SimpleEmail email;

    try {
        email = new SimpleEmail();

        email.setHostName(outgoingEmailServer);
        email.setSmtpPort(outgoingEmailPort);
        //email.setAuthenticator(new DefaultAuthenticator(outgoingUsername, outgoingPassword));
        //email.setSSLOnConnect(true);

        email.setFrom(from);
        email.addTo(to);

        if (cc.length > 0) {
            email.addCc(cc);
        }

        if (bcc.length > 0) {
            email.addBcc(bcc);
        }

        email.setSubject(subject);
        email.setMsg(body);

        if (validateEmails(to)) {
            email.send();

        } else {
            logger.error("Invalid destinations in " + toString());
        }

    } catch (EmailException e) {
        logger.error("EmailException when trying to send out a SimpleEmail: " + this.toString());
        logger.error(ExceptionUtils.getStackTrace(e));
    }
}

From source file:com.aurel.track.admin.customize.category.filter.PredefinedQueryBL.java

/**
 * Gets the filter expression for all issues
 * @return/*  w  w  w.j a  v a 2  s .c o m*/
 */
public static String getAllIssuesExpression() {
    FilterFacade filterFacade = FilterFacadeFactory.getInstance()
            .getFilterFacade(TQueryRepositoryBean.QUERY_PURPOSE.TREE_FILTER, true);
    FilterUpperTO filterUpperTO = new FilterUpperTO();
    String filterExpression = null;
    try {
        filterExpression = filterFacade.getFilterExpression(null, filterUpperTO, null);
    } catch (Exception e) {
        LOGGER.info("Getting the all issues expression failed with " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
    }
    return filterExpression;
}

From source file:com.aurel.track.admin.customize.treeConfig.screen.ScreenAssignmentAction.java

/**
 * Save the zip file and import the data 
 * @return/*from  w w  w  .j a  va 2  s .  co m*/
 */
public String importScreens() {
    try {
        EntityImporter entityImporter = new EntityImporter();
        boolean clearChildren = overwriteExisting;
        ImportContext importContext = new ImportContext();
        importContext.setEntityType("TScreenBean");
        importContext.setOverrideExisting(overwriteExisting);
        importContext.setClearChildren(clearChildren);
        entityImporter.importFile(uploadFile, importContext);
    } catch (EntityImporterException e) {
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        JSONUtility.encodeJSONFailure(e.getMessage());
    } catch (Exception e) {
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        JSONUtility.encodeJSONFailure(e.getMessage());
    }
    JSONUtility.encodeJSONSuccess(servletResponse, false);
    return null;
}

From source file:io.galeb.router.handlers.completionListeners.StatsdCompletionListener.java

@Override
public void exchangeEvent(HttpServerExchange exchange, NextListener nextListener) {
    try {//from   w w w .  j  ava  2  s  .c  om
        String poolName = exchange.getAttachment(POOL_NAME);
        String virtualhost = exchange.getHostName();
        virtualhost = virtualhost != null ? virtualhost : UNDEF;
        String targetUri = exchange.getAttachment(HostSelector.REAL_DEST);
        targetUri = targetUri != null ? targetUri
                : virtualhost + "__" + extractUpstreamField(exchange.getResponseHeaders(), targetUri);
        final boolean targetIsUndef = UNDEF.equals(targetUri);

        final Integer statusCode = exchange.getStatusCode();
        final String method = exchange.getRequestMethod().toString();
        final Integer responseTime = getResponseTime(exchange);
        final String statsdKeyFull = cleanUpKey(VH_PREFIX + virtualhost) + "." + cleanUpKey(targetUri);
        final String statsdKeyVirtualHost = cleanUpKey(VH_PREFIX + virtualhost);
        final String statsdKeyEnvironmentName = ENV_PREFIX + ENVIRONMENT_NAME;

        Set<String> keys = new HashSet<>();
        keys.add(statsdKeyFull);
        keys.add(statsdKeyVirtualHost);
        keys.add(statsdKeyEnvironmentName);
        if (poolName != null) {
            final String statsdKeyPool = cleanUpKey(POOL_PREFIX + poolName);
            final String statsdKeyPoolTarget = cleanUpKey(POOL_PREFIX + poolName + "." + cleanUpKey(targetUri));
            final String statsdKeyVirtualHostPool = cleanUpKey(statsdKeyVirtualHost + "." + poolName);
            final String statsdKeyVirtualHostPoolTarget = cleanUpKey(
                    statsdKeyVirtualHost + "." + poolName + "." + cleanUpKey(targetUri));
            keys.add(statsdKeyPool);
            keys.add(statsdKeyPoolTarget);
            keys.add(statsdKeyVirtualHostPool);
            keys.add(statsdKeyVirtualHostPoolTarget);
        }

        sendStatusCodeCount(keys, statusCode, targetIsUndef);
        sendHttpMethodCount(keys, method);
        sendResponseTime(keys, responseTime, targetIsUndef);

        if (sendOpenconnCounter) {
            final Integer clientOpenConnection = exchange.getAttachment(ClientStatisticsMarker.TARGET_CONN);
            final String statsdKeyEnvironmentNameFull = statsdKeyEnvironmentName + "." + virtualhost;
            Set<String> keysToConnCount = new HashSet<>();
            keysToConnCount.add(statsdKeyFull);
            keysToConnCount.add(statsdKeyEnvironmentName);
            keysToConnCount.add(statsdKeyEnvironmentNameFull);
            sendActiveConnCount(keysToConnCount, clientOpenConnection, targetIsUndef);
        }

    } catch (Exception e) {
        logger.error(ExceptionUtils.getStackTrace(e));
    } finally {
        nextListener.proceed();
    }
}

From source file:com.aurel.track.persist.THistoryTransactionPeer.java

/**
 * Loads the HistoryTransactions by itemID and fields changed since
 * @param itemID/*from  w w w  . ja v  a 2s.  c o  m*/
 * @param fieldIDs
 * @param since
 * @return
 */
@Override
public List<THistoryTransactionBean> loadByItemAndFieldsSince(Integer itemID, List<Integer> fieldIDs,
        Date since) {
    if (fieldIDs != null && !fieldIDs.isEmpty() && itemID != null) {
        Criteria criteria = new Criteria();
        criteria.add(WORKITEM, itemID);
        criteria.add(LASTEDIT, since, Criteria.GREATER_THAN);
        criteria.addDescendingOrderByColumn(THistoryTransactionPeer.LASTEDIT);
        criteria.addJoin(OBJECTID, TFieldChangePeer.HISTORYTRANSACTION);
        criteria.addIn(TFieldChangePeer.FIELDKEY, fieldIDs);
        try {
            return convertTorqueListToBeanList(doSelect(criteria));
        } catch (TorqueException e) {
            LOGGER.error("Loading the history transactions by itemID  " + itemID + " for  fieldIDs " + fieldIDs
                    + " since " + since + " failed with " + e.getMessage());
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug(ExceptionUtils.getStackTrace(e));
            }
        }
    }
    return null;
}

From source file:com.baasbox.service.push.providers.APNServer.java

@Override
public boolean send(String message, List<String> deviceid, JsonNode bodyJson) throws Exception {
    PushLogger pushLogger = PushLogger.getInstance();
    pushLogger.addMessage("............ APN Push Message: -%s- to the device(s) %s", message, deviceid);
    ApnsService service = null;/*from w  ww .  ja v a 2 s  .  co  m*/
    try {
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("APN Push message: " + message + " to the device " + deviceid);
        if (!isInit) {
            pushLogger.addMessage("............ APNS is not initialized!");
            return true;
        }

        String payload = null;
        try {
            service = getService();
        } catch (com.notnoop.exceptions.InvalidSSLConfig e) {
            pushLogger.addMessage("Error sending push notification ...");
            pushLogger.addMessage("   Exception is: %s ", ExceptionUtils.getStackTrace(e));
            BaasBoxLogger.error("Error sending push notification");
            throw new PushNotInitializedException(
                    "Error decrypting certificate.Verify your password for given certificate");
            //icallbackPush.onError(ExceptionUtils.getMessage(e));
        }

        JsonNode contentAvailableNode = bodyJson.findValue("content-available");
        Integer contentAvailable = null;
        if (!(contentAvailableNode == null)) {
            if (!(contentAvailableNode.isInt()))
                throw new PushContentAvailableFormatException(
                        "Content-available MUST be an Integer (1 for silent notification)");
            contentAvailable = contentAvailableNode.asInt();
        }

        JsonNode categoryNode = bodyJson.findValue("category");
        String category = null;
        if (!(categoryNode == null)) {
            if (!(categoryNode.isTextual()))
                throw new PushCategoryFormatException("Category MUST be a String");
            category = categoryNode.asText();
        }

        JsonNode soundNode = bodyJson.findValue("sound");
        String sound = null;
        if (!(soundNode == null)) {
            if (!(soundNode.isTextual()))
                throw new PushSoundKeyFormatException("Sound value MUST be a String");
            sound = soundNode.asText();
        }

        JsonNode actionLocKeyNode = bodyJson.findValue("actionLocalizedKey");
        String actionLocKey = null;

        if (!(actionLocKeyNode == null)) {
            if (!(actionLocKeyNode.isTextual()))
                throw new PushActionLocalizedKeyFormatException("ActionLocalizedKey MUST be a String");
            actionLocKey = actionLocKeyNode.asText();
        }

        JsonNode locKeyNode = bodyJson.findValue("localizedKey");
        String locKey = null;

        if (!(locKeyNode == null)) {
            if (!(locKeyNode.isTextual()))
                throw new PushLocalizedKeyFormatException("LocalizedKey MUST be a String");
            locKey = locKeyNode.asText();
        }

        JsonNode locArgsNode = bodyJson.get("localizedArguments");

        List<String> locArgs = new ArrayList<String>();
        if (!(locArgsNode == null)) {
            if (!(locArgsNode.isArray()))
                throw new PushLocalizedArgumentsFormatException(
                        "LocalizedArguments MUST be an Array of String");
            for (JsonNode locArgNode : locArgsNode) {
                if (locArgNode.isNumber())
                    throw new PushLocalizedArgumentsFormatException(
                            "LocalizedArguments MUST be an Array of String");
                locArgs.add(locArgNode.toString());
            }
        }

        JsonNode customDataNodes = bodyJson.get("custom");

        Map<String, JsonNode> customData = new HashMap<String, JsonNode>();

        if (!(customDataNodes == null)) {
            customData.put("custom", customDataNodes);
        }

        JsonNode badgeNode = bodyJson.findValue("badge");
        int badge = 0;
        if (!(badgeNode == null)) {
            if (!(badgeNode.isNumber()))
                throw new PushBadgeFormatException("Badge value MUST be a number");
            else
                badge = badgeNode.asInt();
        }

        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("APN Push message: " + message + " to the device " + deviceid + " with sound: "
                    + sound + " with badge: " + badge + " with Action-Localized-Key: " + actionLocKey
                    + " with Localized-Key: " + locKey);
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Localized arguments: " + locArgs.toString());
        if (BaasBoxLogger.isDebugEnabled())
            BaasBoxLogger.debug("Custom Data: " + customData.toString());

        pushLogger.addMessage("APN Push message: " + message + " to the device " + deviceid + " with sound: "
                + sound + " with badge: " + badge + " with Action-Localized-Key: " + actionLocKey
                + " with Localized-Key: " + locKey);
        pushLogger.addMessage("Localized arguments: " + locArgs.toString());
        pushLogger.addMessage("Custom Data: " + customData.toString());
        pushLogger.addMessage("Timeout: " + timeout);

        PayloadBuilder payloadBuilder = APNS.newPayload().alertBody(message).sound(sound)
                .actionKey(actionLocKey).localizedKey(locKey).localizedArguments(locArgs).badge(badge)
                .customFields(customData).category(category);
        if (contentAvailable != null && contentAvailable.intValue() == 1) {
            payloadBuilder.instantDeliveryOrSilentNotification();
        }
        payload = payloadBuilder.build();

        Collection<? extends ApnsNotification> result = null;
        if (timeout <= 0) {
            try {
                result = service.push(deviceid, payload);
            } catch (NetworkIOException e) {
                pushLogger.addMessage("Error sending push notification ...");
                pushLogger.addMessage("   Exception is: %s ", ExceptionUtils.getStackTrace(e));
                BaasBoxLogger.error("Error sending push notification");
                BaasBoxLogger.error(ExceptionUtils.getStackTrace(e));
                throw new PushNotInitializedException("Error processing certificate, maybe it's revoked");
                //icallbackPush.onError(ExceptionUtils.getMessage(e));
            }
        } else {
            try {
                Date expiry = new Date(Long.MAX_VALUE);
                pushLogger.addMessage("Timeout is > 0 (%d), expiration date is set to %s", timeout,
                        expiry.toString());
                result = service.push(deviceid, payload, expiry);
            } catch (NetworkIOException e) {
                pushLogger.addMessage("Error sending push notification ...");
                pushLogger.addMessage("   Exception is: %s ", ExceptionUtils.getStackTrace(e));
                BaasBoxLogger.error("Error sending enhanced push notification");
                BaasBoxLogger.error(ExceptionUtils.getStackTrace(e));
                throw new PushNotInitializedException("Error processing certificate, maybe it's revoked");
                //icallbackPush.onError(ExceptionUtils.getMessage(e));
            }

        }
        if (result != null) {
            Iterator<? extends ApnsNotification> it = result.iterator();
            while (it.hasNext()) {
                ApnsNotification item = it.next();
                //item.
            }

        }
        //icallbackPush.onSuccess();
        return false;
    } catch (Exception e) {
        pushLogger.addMessage("Error sending push notification (APNS)...");
        pushLogger.addMessage(ExceptionUtils.getMessage(e));
        throw e;
    } finally {
        if (service != null)
            service.stop();
    }
}

From source file:ke.co.tawi.babblesms.server.persistence.contacts.ContactDAO.java

/**
 * @see ke.co.tawi.babblesms.server.persistence.contacts.BabbleContactDAO#getContacts(ke.co.tawi.babblesms.server.beans.account.Account)
 *//*from  w  ww.j a v a  2  s  .c  o m*/
@Override
public List<Contact> getContacts(Account account) {
    List<Contact> list = new ArrayList<>();

    try (Connection conn = dbCredentials.getConnection();
            PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM Contact WHERE accountuuid = ?;");) {

        pstmt.setString(1, account.getUuid());
        ResultSet rset = pstmt.executeQuery();

        list = beanProcessor.toBeanList(rset, Contact.class);

        rset.close();

    } catch (SQLException e) {
        logger.error("SQLException when getting contacts of " + account);
        logger.error(ExceptionUtils.getStackTrace(e));
    }

    Collections.sort(list);
    return list;
}