Example usage for java.io IOException getStackTrace

List of usage examples for java.io IOException getStackTrace

Introduction

In this page you can find the example usage for java.io IOException getStackTrace.

Prototype

public StackTraceElement[] getStackTrace() 

Source Link

Document

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

Usage

From source file:argendata.web.controller.DatasetController.java

@RequestMapping(method = RequestMethod.GET)
public void exportDatasets(HttpServletRequest request, HttpServletResponse response) {

    response.setContentType("application/octet-stream");

    Iterable<Dataset> listDataset = this.datasetService.getAllApprovedDatasets();

    String text = "";
    for (Dataset d : listDataset) {
        String line = "";
        line = d.getTitle() + ";";
        line += d.getLicense() + ";";
        Set<String> myTags = d.getKeyword();
        for (String s : myTags) {
            line += s + ",";
        }/*from  www . ja v a 2  s .c  o m*/
        line = line.substring(0, line.length() - 1);
        line += ";";
        line += d.getDataQuality() + ";";
        line += d.getModified().substring(0, 10) + ";";
        line += d.getSpatial() + ";";
        line += d.getTemporal() + ";";
        line += d.getPublisherName() + ";";
        line += d.getAccessURL() + ";";
        line += d.getSize() + ";";
        line += d.getFormat() + ";";
        if (d.getDistribution() instanceof Feed) {
            line += "Feed,";
        } else if (d.getDistribution() instanceof WebService) {
            line += "Web Service;";
        } else {
            line += "Download;";
        }
        line += d.getLocation() + ";";
        line += d.getDescription();
        line += "\n";
        text += line;
    }
    response.setHeader("Content-Disposition", "attachment; filename=\"Datasets.csv");
    response.setContentLength(text.length());

    ServletOutputStream out = null;
    try {
        out = response.getOutputStream();
        out.write(text.getBytes());
    } catch (IOException e) {
        logger.error(e.getMessage());
        logger.error(e.getStackTrace());
    }

}

From source file:org.apache.lucene.gdata.storage.lucenestorage.StorageImplementation.java

/**
 * @see org.apache.lucene.gdata.storage.Storage#storeEntry(org.apache.lucene.gdata.data.ServerBaseEntry)
 *//*from  www .  ja va 2s  .c o  m*/
public BaseEntry storeEntry(final ServerBaseEntry entry) throws StorageException {
    if (entry == null)
        throw new StorageException("entry is null");
    if (entry.getFeedId() == null)
        throw new StorageException("feed-id is null");
    if (entry.getVersion() != 1)
        throw new StorageException("entry version must be 1");
    if (entry.getServiceConfig() == null)
        throw new StorageException("ProvidedService must not be null");
    StorageModifier modifier = this.controller.getStorageModifier();
    String id = this.controller.releaseId();
    entry.setId(entry.getFeedId() + id);
    if (LOG.isInfoEnabled())
        LOG.info("Store entry " + id + " -- feed: " + entry.getFeedId());

    try {
        StorageEntryWrapper wrapper = new StorageEntryWrapper(entry, StorageOperation.INSERT);
        modifier.insertEntry(wrapper);
    } catch (IOException e) {
        StorageException ex = new StorageException("Can't create Entry -- " + e.getMessage(), e);
        ex.setStackTrace(e.getStackTrace());
        throw ex;

    }

    return entry.getEntry();
}

From source file:com.excilys.ebi.gatling.recorder.ui.component.RunningFrame.java

private void dumpRequestBody(int idEvent, String content) {
    File dir = null;/*from  w w w .  j  a v  a 2s  . c om*/
    if (configuration.getRequestBodiesFolder() == null)
        dir = new File(getOutputFolder(),
                ResultType.FORMAT.format(startDate) + "_" + GATLING_REQUEST_BODIES_DIRECTORY_NAME);
    else
        dir = getFolder("request bodies", configuration.getRequestBodiesFolder());

    if (!dir.exists())
        dir.mkdir();

    FileWriter fw = null;
    try {
        fw = new FileWriter(
                new File(dir, ResultType.FORMAT.format(startDate) + "_request_" + idEvent + ".txt"));
        fw.write(content);
    } catch (IOException ex) {
        logger.error("Error, while dumping request body... {}", ex.getStackTrace());
    } finally {
        closeQuietly(fw);
    }
}

From source file:seleniumAutomation.Selenium.java

public void InitializeChrome() {
    File file = null;/*from  w  ww .j  a v a  2s  .  c o  m*/
    try {
        file = new File(new File("").getCanonicalPath().toString() + "/Data/chromedriver.exe");
    } catch (IOException ex) {
        Logger.getLogger(Selenium.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.setProperty("webdriver.chrome.driver", file.getAbsolutePath());
    this.driver = null;
    try {
        this.driver = new ChromeDriver();
    } catch (NoClassDefFoundError ex) {
        System.err.println("error: " + ex.getStackTrace());
    }
    this.driver.manage().timeouts().pageLoadTimeout(120, TimeUnit.SECONDS);
    this.efwd = new EventFiringWebDriver(driver);
}

From source file:seleniumAutomation.Selenium.java

public void InitializeIE() {
    File file = null;/*from  w  ww  .j  av  a2s.co m*/
    try {
        file = new File(new File("").getCanonicalPath().toString() + "/Data/iedriverserver.exe");
    } catch (IOException ex) {
        Logger.getLogger(Selenium.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.setProperty("webdriver.ie.driver", file.getAbsolutePath());
    this.driver = null;
    try {
        this.driver = new InternetExplorerDriver();
    } catch (NoClassDefFoundError ex) {
        System.err.println("error: " + ex.getStackTrace());
    }
    this.driver.manage().timeouts().pageLoadTimeout(120, TimeUnit.SECONDS);
    this.efwd = new EventFiringWebDriver(driver);
}

From source file:org.opencb.commons.datastore.mongodb.MongoDBCollection.java

public QueryResult<Document> aggregate(List<? extends Bson> operations, QueryOptions options) {
    long start = startQuery();
    QueryResult<Document> queryResult;

    // we need to be sure that the List is mutable
    List<Bson> bsonOperations = new ArrayList<>(operations);
    if (options != null && options.containsKey("limit")) {
        bsonOperations.add(Aggregates.limit(options.getInt("limit")));
    }/*from w  ww. ja v a2  s  .co m*/
    AggregateIterable output = mongoDBNativeQuery.aggregate(bsonOperations, options);
    MongoCursor<Document> iterator = output.iterator();
    List<Bson> list = new LinkedList<>();
    if (queryResultWriter != null) {
        try {
            queryResultWriter.open();
            while (iterator.hasNext()) {
                queryResultWriter.write(iterator.next());
            }
            queryResultWriter.close();
        } catch (IOException e) {
            queryResult = endQuery(list, start);
            queryResult.setErrorMsg(e.getMessage() + " " + Arrays.toString(e.getStackTrace()));
            return queryResult;
        }
    } else {
        while (iterator.hasNext()) {
            list.add(iterator.next());
        }
    }
    queryResult = endQuery(list, start);
    return queryResult;
}

From source file:org.opencb.commons.datastore.mongodb.MongoDBCollection.java

public <T> QueryResult<T> aggregate(List<? extends Bson> operations,
        ComplexTypeConverter<T, Document> converter, QueryOptions options) {
    long start = startQuery();
    QueryResult<T> queryResult;/*from ww  w  . j a v  a  2  s  . c  o m*/
    AggregateIterable output = mongoDBNativeQuery.aggregate(operations, options);
    MongoCursor<Document> iterator = output.iterator();
    List<T> list = new LinkedList<>();
    if (queryResultWriter != null) {
        try {
            queryResultWriter.open();
            while (iterator.hasNext()) {
                queryResultWriter.write(iterator.next());
            }
            queryResultWriter.close();
        } catch (IOException e) {
            queryResult = endQuery(list, start);
            queryResult.setErrorMsg(e.getMessage() + " " + Arrays.toString(e.getStackTrace()));
            return queryResult;
        }
    } else {
        if (converter != null) {
            while (iterator.hasNext()) {
                list.add(converter.convertToDataModelType(iterator.next()));
            }
        } else {
            while (iterator.hasNext()) {
                list.add((T) iterator.next());
            }
        }
    }
    queryResult = endQuery(list, start);
    return queryResult;
}

From source file:com.datatorrent.contrib.hdht.HDHTWalManager.java

/**
 * Delete old parent WAL files which are already copied to new WAL location
 * @param alreadyCopiedWals/*from www. j a v  a 2s .c o m*/
 */
public void deletePreviousWalFiles(Set<PreviousWALDetails> alreadyCopiedWals) {
    try {
        for (Iterator<PreviousWALDetails> it = alreadyCopiedWals.iterator(); it.hasNext();) {
            PreviousWALDetails parentWal = it.next();
            // TODO: If using file APIs, delete entire folder for old WAL files
            logger.debug("Deleting WAL file {}", parentWal.getWalKey());
            // delete WAL Files if not already deleted
            for (long i = parentWal.getStartPosition().fileId; i <= parentWal.getEndPosition().fileId; i++) {
                if (bfs.exists(parentWal.getWalKey(), WAL_FILE_PREFIX + i)) {
                    bfs.delete(parentWal.getWalKey(), WAL_FILE_PREFIX + i);
                }
            }
            alreadyCopiedWals.remove(it);
        }
    } catch (IOException e) {
        logger.warn("Exception occurred while deleting old WAL files {}:{}", e.getMessage(), e.getStackTrace());
    }
}

From source file:org.asqatasun.emailsender.EmailSender.java

/**
 *
 * @param emailFrom//ww w . j  a va 2s  . c om
 * @param emailToSet
 * @param emailBccSet (can be null)
 * @param replyTo (can be null)
 * @param emailSubject
 * @param emailContent
 */
public void sendEmail(String emailFrom, Set<String> emailToSet, Set<String> emailBccSet, String replyTo,
        String emailSubject, String emailContent) {
    boolean debug = false;

    // Set the host smtp address
    Properties props = new Properties();
    props.put("mail.smtp.host", smtpHost);
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");

    // create some properties and get the default Session
    Session session = Session.getInstance(props);
    session.setDebug(debug);
    try {
        Transport t = session.getTransport("smtp");
        t.connect(smtpHost, userName, password);

        // create a message
        MimeMessage msg = new MimeMessage(session);

        // set the from and to address
        InternetAddress addressFrom;
        try {
            // Used default from address is passed one is null or empty or
            // blank
            addressFrom = (StringUtils.isNotBlank(emailFrom)) ? new InternetAddress(emailFrom)
                    : new InternetAddress(from);
            msg.setFrom(addressFrom);
            Address[] recipients = new InternetAddress[emailToSet.size()];
            int i = 0;
            for (String emailTo : emailToSet) {
                recipients[i] = new InternetAddress(emailTo);
                i++;
            }

            msg.setRecipients(Message.RecipientType.TO, recipients);

            if (CollectionUtils.isNotEmpty(emailBccSet)) {
                Address[] bccRecipients = new InternetAddress[emailBccSet.size()];
                i = 0;
                for (String emailBcc : emailBccSet) {
                    bccRecipients[i] = new InternetAddress(emailBcc);
                    i++;
                }
                msg.setRecipients(Message.RecipientType.BCC, bccRecipients);
            }

            if (StringUtils.isNotBlank(replyTo)) {
                Address[] replyToRecipients = { new InternetAddress(replyTo) };
                msg.setReplyTo(replyToRecipients);
            }

            // Setting the Subject
            msg.setSubject(emailSubject, CHARSET_KEY);

            // Setting content and charset (warning: both declarations of
            // charset are needed)
            msg.setHeader(CONTENT_TYPE_KEY, FULL_CHARSET_KEY);
            LOGGER.debug("emailContent  " + emailContent);
            msg.setContent(emailContent, FULL_CHARSET_KEY);
            try {
                LOGGER.debug("emailContent from message object " + msg.getContent().toString());
            } catch (IOException ex) {
                LOGGER.error(ex.getMessage());
            } catch (MessagingException ex) {
                LOGGER.error(ex.getMessage());
            }
            for (Address addr : msg.getAllRecipients()) {
                LOGGER.debug("addr " + addr);
            }
            t.sendMessage(msg, msg.getAllRecipients());
        } catch (AddressException ex) {
            LOGGER.warn("AddressException " + ex.getMessage());
            LOGGER.warn("AddressException " + ex.getStackTrace());
        }
    } catch (NoSuchProviderException e) {
        LOGGER.warn("NoSuchProviderException " + e.getMessage());
        LOGGER.warn("NoSuchProviderException " + e.getStackTrace());
    } catch (MessagingException e) {
        LOGGER.warn("MessagingException " + e.getMessage());
        LOGGER.warn("MessagingException " + e.getStackTrace());
    }
}

From source file:com.cisco.iwe.services.util.EmailMonitor.java

/**
 * This method returns the corresponding JSON response.'Success = true' in case the Mail contents get stored in the database successfully. 'Success = false' in case of any errors 
 **/// w w  w . j a va 2 s . c o  m

public String monitorEmailAndLoadDB() {
    License license = new License();
    license.setLicense(EmailParseConstants.ocrLicenseFile);
    Store emailStore = null;
    Folder folder = null;
    Properties props = new Properties();
    logger.info("EmailMonitor monitorEmailAndLoadDB Enter (+)");
    // Setting session and Store information
    // MailServerConnectivity - get the email credentials based on the environment
    String[] mailCredens = getEmailCredens();
    final String username = mailCredens[0];
    final String password = mailCredens[1];
    logger.info("monitorEmailAndLoadDB : Email ID : " + username);

    try {
        logger.info("EmailMonitor.monitorEmailAndLoadDB get the mail server properties");
        props.put(EmailParseConstants.emailAuthKey, "true");
        props.put(EmailParseConstants.emailHostKey, prop.getProperty(EmailParseConstants.emailHost));
        props.put(EmailParseConstants.emailPortKey, prop.getProperty(EmailParseConstants.emailPort));
        props.put(EmailParseConstants.emailTlsKey, "true");

        logger.info("EmailMonitor.monitorEmailAndLoadDB create the session object with mail server properties");
        Session session = Session.getDefaultInstance(props, new Authenticator() {
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });
        // Prod-MailServerConnectivity - create the POP3 store object and
        // connect with the pop server
        logger.info("monitorEmailAndLoadDB : create the POP3 store object");
        emailStore = (Store) session.getStore(prop.getProperty(EmailParseConstants.emailType));
        logger.info("monitorEmailAndLoadDB : Connecting to Store :" + emailStore.toString());
        emailStore.connect(prop.getProperty(EmailParseConstants.emailHost),
                Integer.parseInt(prop.getProperty(EmailParseConstants.emailPort)), username, password);
        logger.info("monitorEmailAndLoadDB : Connection Status:" + emailStore.isConnected());

        // create the folder object
        folder = emailStore.getFolder(prop.getProperty(EmailParseConstants.emailFolder));
        // Check if Inbox exists
        if (!folder.exists()) {
            logger.error("monitorEmailAndLoadDB : No INBOX exists...");
            System.exit(0);
        }
        // Open inbox and read messages
        logger.info("monitorEmailAndLoadDB : Connected to Folder");
        folder.open(Folder.READ_WRITE);

        // retrieve the messages from the folder in an array and process it
        Message[] msgArr = folder.getMessages();
        // Read each message and delete the same once data is stored in DB
        logger.info("monitorEmailAndLoadDB : Message length::::" + msgArr.length);

        SimpleDateFormat sdf2 = new SimpleDateFormat(EmailParseConstants.dateFormat);

        Date sent = null;
        String emailContent = null;
        String contentType = null;
        // for (int i = 0; i < msg.length; i++) {
        for (int i = msgArr.length - 1; i > msgArr.length - 2; i--) {
            Message message = msgArr[i];
            if (!message.isSet(Flags.Flag.SEEN)) {
                try {
                    sent = msgArr[i].getSentDate();
                    contentType = message.getContentType();
                    String fileType = null;
                    byte[] byteArr = null;
                    String validAttachments = EmailParseConstants.validAttachmentTypes;
                    if (contentType.contains("multipart")) {
                        Multipart multiPart = (Multipart) message.getContent();
                        int numberOfParts = multiPart.getCount();
                        for (int partCount = 0; partCount < numberOfParts; partCount++) {
                            MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount);
                            InputStream inStream = (InputStream) part.getInputStream();
                            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
                            int nRead;
                            byte[] data = new byte[16384];
                            while ((nRead = inStream.read(data, 0, data.length)) != -1) {
                                buffer.write(data, 0, nRead);
                            }
                            buffer.flush();
                            byteArr = buffer.toByteArray();
                            if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) {
                                fileType = part.getFileName().substring(part.getFileName().lastIndexOf("."),
                                        part.getFileName().length());
                                String fileDir = part.getFileName();
                                if (validAttachments.contains(fileType)) {
                                    part.saveFile(fileDir);
                                    saveAttachmentAndText(message.getFrom()[0].toString(), message.getSubject(),
                                            byteArr, emailContent.getBytes(), fileType, sent,
                                            fileType.equalsIgnoreCase(".PDF") ? scanPDF(fileDir)
                                                    : scanImage(fileDir).toString());
                                    deleteFile(fileDir);
                                } else {
                                    sendNotification();
                                }

                            } else {
                                // this part may be the message content
                                emailContent = part.getContent().toString();
                            }
                        }
                    } else if (contentType.contains("text/plain") || contentType.contains("text/html")) {
                        Object content = message.getContent();
                        if (content != null) {
                            emailContent = content.toString();
                        }
                    }
                    message.setFlag(Flags.Flag.DELETED, false);
                    logger.info(
                            "monitorEmailAndLoadDB : loadSuccess : Mail Parsed for : " + message.getSubject());
                    logger.info("monitorEmailAndLoadDB : loadSuccess : Created at : " + sdf2.format(sent));
                    logger.info("Message deleted");
                } catch (IOException e) {
                    logger.error("IO Exception in email monitoring: " + e);
                    logger.error(
                            "IO Exception in email monitoring message: " + Arrays.toString(e.getStackTrace()));
                } catch (SQLException sexp) {
                    logger.error("SQLException Occurred GetSpogDetails-db2 :", sexp);
                    buildErrorJson(ExceptionConstants.sqlErrCode, ExceptionConstants.sqlErrMsg);
                } catch (Exception e) {
                    logger.error("Unknown Exception in email monitoring: " + e);
                    logger.error("Unknown Exception in email monitoring message: "
                            + Arrays.toString(e.getStackTrace()));
                }
            }
        }

        // Close folder and store
        folder.close(true);
        emailStore.close();

    } catch (NoSuchProviderException e) {
        logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring: " + e);
        logger.error("monitorEmailAndLoadDB : NoSuchProviderException in email monitoring message: "
                + Arrays.toString(e.getStackTrace()));
    } catch (MessagingException e) {
        logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e);
        logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring message: "
                + Arrays.toString(e.getStackTrace()));
    } finally {
        if (folder != null && folder.isOpen()) {
            // Close folder and store
            try {
                folder.close(true);
                emailStore.close();
            } catch (MessagingException e) {
                logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: " + e);
                logger.error("monitorEmailAndLoadDB : MessagingException in email monitoring: "
                        + Arrays.toString(e.getStackTrace()));
            }
        }
    }
    logger.info("EmailMonitor monitorEmailAndLoadDB Exit (-)");
    return buildSuccessJson().toString();
}