Example usage for java.lang Exception getStackTrace

List of usage examples for java.lang Exception getStackTrace

Introduction

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

Prototype

public StackTraceElement[] getStackTrace() 

Source Link

Document

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

Usage

From source file:br.com.mv.modulo.utils.ModuloEmailSender.java

public void sendException(Exception exception) {
    StringBuilder str = new StringBuilder();
    str.append("Erro: " + exception.toString() + System.lineSeparator());
    str.append("Mensagem: " + exception.getLocalizedMessage() + System.lineSeparator());
    str.append("Stack: " + System.lineSeparator());
    for (StackTraceElement element : exception.getStackTrace()) {
        str.append(element.toString() + System.lineSeparator());
    }/*  w  ww. j  av  a 2s. co  m*/

    sendEmail(str.toString());
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.RestrictionRetryController.java

public void doGet(HttpServletRequest req, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(req, response, SimplePermission.EDIT_ONTOLOGY.ACTION)) {
        return;/*  w  w  w.j ava  2  s. c  o  m*/
    }

    VitroRequest request = new VitroRequest(req);

    try {

        EditProcessObject epo = createEpo(request);

        request.setAttribute("editAction", "addRestriction");
        epo.setAttribute("VClassURI", request.getParameter("VClassURI"));

        String restrictionTypeStr = request.getParameter("restrictionType");
        epo.setAttribute("restrictionType", restrictionTypeStr);
        request.setAttribute("restrictionType", restrictionTypeStr);

        // default to object property restriction
        boolean propertyType = ("data".equals(request.getParameter("propertyType"))) ? DATA : OBJECT;

        List<? extends ResourceBean> pList = (propertyType == OBJECT)
                ? request.getUnfilteredWebappDaoFactory().getObjectPropertyDao().getAllObjectProperties()
                : request.getUnfilteredWebappDaoFactory().getDataPropertyDao().getAllDataProperties();
        List<Option> onPropertyList = new LinkedList<Option>();
        sortForPickList(pList, request);
        for (ResourceBean p : pList) {
            onPropertyList.add(new Option(p.getURI(), p.getPickListName()));
        }

        epo.setFormObject(new FormObject());
        epo.getFormObject().getOptionLists().put("onProperty", onPropertyList);

        if (restrictionTypeStr.equals("someValuesFrom")) {
            request.setAttribute("specificRestrictionForm", "someValuesFromRestriction_retry.jsp");
            List<Option> optionList = (propertyType == OBJECT) ? getValueClassOptionList(request)
                    : getValueDatatypeOptionList(request);
            epo.getFormObject().getOptionLists().put("ValueClass", optionList);
        } else if (restrictionTypeStr.equals("allValuesFrom")) {
            request.setAttribute("specificRestrictionForm", "allValuesFromRestriction_retry.jsp");
            List<Option> optionList = (propertyType == OBJECT) ? getValueClassOptionList(request)
                    : getValueDatatypeOptionList(request);
            epo.getFormObject().getOptionLists().put("ValueClass", optionList);
        } else if (restrictionTypeStr.equals("hasValue")) {
            request.setAttribute("specificRestrictionForm", "hasValueRestriction_retry.jsp");
            if (propertyType == OBJECT) {
                request.setAttribute("propertyType", "object");
            } else {
                request.setAttribute("propertyType", "data");
            }
        } else if (restrictionTypeStr.equals("minCardinality") || restrictionTypeStr.equals("maxCardinality")
                || restrictionTypeStr.equals("cardinality")) {
            request.setAttribute("specificRestrictionForm", "cardinalityRestriction_retry.jsp");
        }

        RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
        request.setAttribute("bodyJsp", "/templates/edit/formBasic.jsp");
        request.setAttribute("formJsp", "/templates/edit/specific/restriction_retry.jsp");
        request.setAttribute("scripts", "/templates/edit/formBasic.js");
        request.setAttribute("title", "Add Restriction");
        request.setAttribute("_action", "insert");
        setRequestAttributes(request, epo);

        try {
            rd.forward(request, response);
        } catch (Exception e) {
            log.error(this.getClass().getName() + "PropertyRetryController could not forward to view.");
            log.error(e.getMessage());
            log.error(e.getStackTrace());
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:de.eorganization.crawler.server.servlets.JSONImportServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {/* w  w w .java  2  s. c  o m*/

        resp.setContentType("text/plain");

        InputStream stream = req.getInputStream();

        log.info("Got Upload " + req.getContentType() + " (" + req.getContentLength() + " bytes) from "
                + req.getRemoteAddr());

        String amiId = req.getHeader("AMI-ID");
        log.info("Got AMI ID:" + amiId);
        String repository = req.getHeader("REPO");
        log.info("Got REPO:" + repository);
        if (amiId == null || repository == null || "".equals(amiId) || "".equals(repository)) {
            log.severe("AMI ID and REPO HTTP Header required.");
            return;
        }

        // Gson gson = new Gson();
        // log.info("Parsed Gson " + gson.fromJson(new
        // InputStreamReader(stream), JsonObject.class));

        String jsonString = IOUtils.toString(stream);
        log.info("Got JSON String "
                + jsonString.substring(0, jsonString.length() > 128 ? 128 : jsonString.length() - 1));
        JSONObject json = new JSONObject();
        try {
            json = new JSONObject(jsonString);
            log.fine("Parsed Json " + json);
            log.finer("Json has keys: " + json.names());
        } catch (JSONException e) {
            log.severe("No JSON sent or wrong format.");
            return;
        }

        JSONObject software = json.optJSONObject("software");
        if (software != null) {
            log.finer("Software JSON " + software);

            JSONArray softwareNames = software.names();
            log.finer("Key Array JSON " + softwareNames);
            for (int i = 0; i < softwareNames.length(); i++) {
                log.fine("software " + softwareNames.getString(i) + " with version "
                        + software.getJSONObject(softwareNames.getString(i)).getString("version"));

                Map<String, String> softAttributes = new HashMap<String, String>();
                JSONArray softwareAttributes = software.getJSONObject(softwareNames.getString(i)).names();
                for (int j = 0; j < softwareAttributes.length(); j++)
                    softAttributes.put(softwareAttributes.getString(j),
                            software.getJSONObject(softwareNames.getString(i))
                                    .getString(softwareAttributes.getString(j)));

                Software soft = AmiManager.saveSoftware(amiId, repository, softwareNames.getString(i),
                        software.getJSONObject(softwareNames.getString(i)).getString("version"),
                        softAttributes);
                if (soft != null) {
                    log.fine("Saved/restored software " + soft);
                    // soft.getAttributes().putAll(softAttributes);
                    // AmiManager.updateSoftware(soft);
                    // log.fine("Saved object " + soft);
                } else
                    log.severe("Not able to save software information for given Ami Id " + amiId + "!");

            }
            List<String> names = new ArrayList<String>();
            for (int i = 0; i < softwareNames.length(); i++)
                names.add(softwareNames.getString(i));
            AmiManager.updateSoftwareNames(names);
            log.info("Saved " + softwareNames.length() + " software objects");

        }

        JSONObject languages = json.optJSONObject("languages");
        if (languages != null) {
            log.finer("Languages JSON " + languages);

            JSONArray languagesNames = languages.names();
            log.finer("Key Array JSON " + languagesNames);
            for (int i = 0; i < languagesNames.length(); i++) {
                log.fine("languages " + languagesNames.getString(i) + " with version "
                        + languages.getJSONObject(languagesNames.getString(i)).getString("version"));

                Map<String, String> langAttributes = new HashMap<String, String>();
                JSONArray languageAttributes = languages.getJSONObject(languagesNames.getString(i)).names();
                for (int j = 0; j < languageAttributes.length(); j++)
                    langAttributes.put(languageAttributes.getString(j),
                            languages.getJSONObject(languagesNames.getString(i))
                                    .getString(languageAttributes.getString(j)));

                Language lang = AmiManager.saveLanguage(amiId, repository, languagesNames.getString(i),
                        languages.getJSONObject(languagesNames.getString(i)).getString("version"),
                        langAttributes);
                if (lang != null) {
                    log.fine("Saved/restored programming language " + lang);
                    lang.getAttributes().putAll(langAttributes);
                    AmiManager.updateLanguage(lang);
                    log.fine("Saved object " + lang);
                } else
                    log.severe("Not able to save programming language information for given Ami Id " + amiId
                            + "!");

            }
            log.info("Saved " + languagesNames.length() + " programming language objects");
        }

        resp.getWriter().println(
                "Saving software packages and programming languages for " + amiId + " (" + repository + ").");

    } catch (JSONException e) {
        log.severe("Error while parsing JSON upload" + e.getMessage() + ", trace: " + e.getStackTrace());
        log.throwing(JSONImportServlet.class.getName(), "doPost", e);
        e.printStackTrace();

    } catch (Exception ex) {
        log.severe("Unexpected error" + ex.getMessage() + ", trace: " + ex.getStackTrace());
        log.throwing(JSONImportServlet.class.getName(), "doPost", ex);
        ex.printStackTrace();
    }

    // log.info("returning to referer " + req.getHeader("referer"));
    // resp.sendRedirect(req.getHeader("referer") != null &&
    // !"".equals(req.getHeader("referer")) ? req.getHeader("referer") :
    // "localhost:8088");
}

From source file:net.krautchan.data.KCThread.java

public void recalc() {
    try {//w w  w  . j  av a  2  s  .co  m
        Iterator<Entry<Long, KCPosting>> iter = postings.entrySet().iterator();
        if (iter.hasNext()) {
            Entry<Long, KCPosting> entry = iter.next();
            KCPosting posting = entry.getValue();
            if (null == digest) {
                makeDigest(posting);
            }
            if (null == firstPostDate) {
                firstPostDate = posting.getCreated();
            }
        }
        Assert.assertNotNull(this.getDbId());
    } catch (Exception e) {
        String trace = "Exception in KCThread " + kcNummer + " " + e.getClass().getCanonicalName() + "\n";
        for (StackTraceElement elem : e.getStackTrace()) {
            trace += " " + elem.toString() + "\n";
        }
        System.err.println(trace);
    }
}

From source file:org.openmrs.module.patientnarratives.web.controller.WebRtcMediaStreamController.java

@RequestMapping(FORM_PATH)
public ModelAndView handleRequest(HttpServletRequest request) throws Exception {

    if (request instanceof MultipartHttpServletRequest) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile videofile = (MultipartFile) multipartRequest.getFile("video");
        MultipartFile audiofile = (MultipartFile) multipartRequest.getFile("audio");

        /**/* w w  w.  java 2s.  c  o  m*/
         * Xuggler merge process of the two binary streams
         */
        try {
            tempMergedVideoFile = File.createTempFile("mergedVideoFile", ".flv");
            String mergedUrl = tempMergedVideoFile.getCanonicalPath();

            IMediaWriter mWriter = ToolFactory.makeWriter(mergedUrl); //output file

            IContainer containerVideo = IContainer.make();
            IContainer containerAudio = IContainer.make();

            InputStream videoInputStream = videofile.getInputStream();
            InputStream audioInputStream = audiofile.getInputStream();

            if (containerVideo.open(videoInputStream, null) < 0)
                throw new IllegalArgumentException("Cant find " + videoInputStream);

            if (containerAudio.open(audioInputStream, null) < 0)
                throw new IllegalArgumentException("Cant find " + audioInputStream);

            int numStreamVideo = containerVideo.getNumStreams();
            int numStreamAudio = containerAudio.getNumStreams();

            System.out.println("Number of video streams: " + numStreamVideo + "\n" + "Number of audio streams: "
                    + numStreamAudio);

            int videostreamt = -1; //this is the video stream id
            int audiostreamt = -1;

            IStreamCoder videocoder = null;

            for (int i = 0; i < numStreamVideo; i++) {
                IStream stream = containerVideo.getStream(i);
                IStreamCoder code = stream.getStreamCoder();

                if (code.getCodecType() == ICodec.Type.CODEC_TYPE_VIDEO) {
                    videostreamt = i;
                    videocoder = code;
                    break;
                }
            }

            for (int i = 0; i < numStreamAudio; i++) {
                IStream stream = containerAudio.getStream(i);
                IStreamCoder code = stream.getStreamCoder();

                if (code.getCodecType() == ICodec.Type.CODEC_TYPE_AUDIO) {
                    audiostreamt = i;
                    break;
                }
            }

            if (videostreamt == -1)
                throw new RuntimeException("No video steam found");
            if (audiostreamt == -1)
                throw new RuntimeException("No audio steam found");

            if (videocoder.open() < 0)
                throw new RuntimeException("Cant open video coder");
            IPacket packetvideo = IPacket.make();

            IStreamCoder audioCoder = containerAudio.getStream(audiostreamt).getStreamCoder();

            if (audioCoder.open() < 0)
                throw new RuntimeException("Cant open audio coder");
            mWriter.addAudioStream(1, 1, audioCoder.getChannels(), audioCoder.getSampleRate());

            mWriter.addVideoStream(0, 0, videocoder.getWidth(), videocoder.getHeight());

            IPacket packetaudio = IPacket.make();

            while (containerVideo.readNextPacket(packetvideo) >= 0
                    || containerAudio.readNextPacket(packetaudio) >= 0) {

                if (packetvideo.getStreamIndex() == videostreamt) {

                    //video packet
                    IVideoPicture picture = IVideoPicture.make(videocoder.getPixelType(), videocoder.getWidth(),
                            videocoder.getHeight());
                    int offset = 0;
                    while (offset < packetvideo.getSize()) {
                        int bytesDecoded = videocoder.decodeVideo(picture, packetvideo, offset);
                        if (bytesDecoded < 0)
                            throw new RuntimeException("bytesDecoded not working");
                        offset += bytesDecoded;

                        if (picture.isComplete()) {
                            System.out.println(picture.getPixelType());
                            mWriter.encodeVideo(0, picture);

                        }
                    }
                }

                if (packetaudio.getStreamIndex() == audiostreamt) {
                    //audio packet

                    IAudioSamples samples = IAudioSamples.make(512, audioCoder.getChannels(),
                            IAudioSamples.Format.FMT_S32);
                    int offset = 0;
                    while (offset < packetaudio.getSize()) {
                        int bytesDecodedaudio = audioCoder.decodeAudio(samples, packetaudio, offset);
                        if (bytesDecodedaudio < 0)
                            throw new RuntimeException("could not detect audio");
                        offset += bytesDecodedaudio;

                        if (samples.isComplete()) {
                            mWriter.encodeAudio(1, samples);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error(e);
            e.getStackTrace();
        }
    }

    saveAndTransferVideoComplexObs();

    returnUrl = request.getContextPath() + "/module/patientnarratives/patientNarrativesForm.form";
    return new ModelAndView(new RedirectView(returnUrl));
}

From source file:com.zinnia.nectar.regression.hadoop.primitive.jobs.SortJob.java

public Double[] call() throws NectarException {
    // TODO Auto-generated method stub
    JobControl jobControl = new JobControl("Sortjob");
    try {//from  w w  w  .j a v a2 s .c o m
        job = new Job();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    job.setJarByClass(SortJob.class);
    log.info("Sorting Job initialized");
    log.warn("Sorting job: Processing...Do not terminate/close");
    log.debug("Sorting job: Mapping process started");

    try {
        ChainMapper.addMapper(job, FieldSeperator.FieldSeperationMapper.class, LongWritable.class, Text.class,
                NullWritable.class, Text.class, job.getConfiguration());
        ChainMapper.addMapper(job, SortMapper.class, NullWritable.class, Text.class, DoubleWritable.class,
                DoubleWritable.class, job.getConfiguration());
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    job.getConfiguration().set("fields.spec", "" + column);
    job.setReducerClass(Reducer.class);

    try {
        FileInputFormat.addInputPath(job, new Path(inputFilePath));
        fs = FileSystem.get(job.getConfiguration());
        if (!fs.exists(new Path(inputFilePath))) {
            throw new NectarException("Exception occured:File " + inputFilePath + " not found ");
        }
    } catch (Exception e2) {
        // TODO Auto-generated catch block
        String trace = new String();
        log.error(e2.toString());
        for (StackTraceElement s : e2.getStackTrace()) {
            trace += "\n\t at " + s.toString();
        }
        log.debug(trace);
        log.debug("Sorting Job terminated abruptly\n");
        throw new NectarException();
    }
    FileOutputFormat.setOutputPath(job, new Path(outputFilePath));
    job.setMapOutputValueClass(DoubleWritable.class);
    job.setMapOutputKeyClass(DoubleWritable.class);
    job.setInputFormatClass(TextInputFormat.class);
    log.debug("Sorting job: Mapping process completed");

    log.debug("Sorting job: Reducing process started");
    try {
        controlledJob = new ControlledJob(job.getConfiguration());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    jobControl.addJob(controlledJob);
    Thread thread = new Thread(jobControl);
    thread.start();
    while (!jobControl.allFinished()) {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    try {
        FSDataInputStream in = fs.open(new Path(outputFilePath + "/part-r-00000"));
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
        String valueLine;
        while ((valueLine = bufferedReader.readLine()) != null) {
            String[] fields = valueLine.split("\t");
            value.add(Double.parseDouble(fields[1]));
        }
        bufferedReader.close();
        in.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        log.error("Exception occured: Output file cannot be read.");
        log.debug(e.getMessage());
        log.debug("Sorting Job terminated abruptly\n");
        throw new NectarException();
    }
    log.debug("Sorting job: Reducing process completed");
    log.info("Sorting Job completed\n");
    return value.toArray(new Double[value.size()]);
}

From source file:fsart.diffTools.gui.DiffToolsMainPanel.java

private void launchDiffTools(String[] args) {
    try {//ww w.j  av a 2 s  . c  om

        DiffToolsCalc.main(args);
        JOptionPane.showMessageDialog((Component) this.getPanel(), "Ok, output is generated"); //, JOptionPane.INFORMATION_MESSAGE);
    } catch (Exception e) {
        log.error(e.toString() + "\n" + strackTraceToString(e.getStackTrace()));
        JOptionPane.showMessageDialog((Component) this.getPanel(), e.toString()); //, JOptionPane.ERROR_MESSAGE);
    }
}

From source file:fr.paris.lutece.plugins.directory.web.action.DirectoryActionResult.java

/**
 * Build the error message for action results
 * @param e the exception/*from w ww .j a v  a  2s. co m*/
 * @return the error message
 */
private String buildErrorMessage(Exception e) {
    String strError = e.getMessage();

    if (StringUtils.isBlank(strError) && (e.getStackTrace() != null) && (e.getStackTrace().length > 0)) {
        StringBuilder sbError = new StringBuilder();

        for (StackTraceElement ele : e.getStackTrace()) {
            sbError.append(ele.toString());
            sbError.append("\n");
        }

        strError = sbError.toString();
    }

    return strError;
}

From source file:jenkins.plugins.ivyreport.IvyAccess.java

/**
 * // w w w . ja  va  2  s.c o  m
 * @return the Ivy instance based on the {@link #ivyConfName}
 * @throws AbortException
 * 
 * @throws ParseException
 * @throws IOException
 */
public Ivy getIvy() {
    Message.setDefaultLogger(new IvyMessageImpl());
    String ivySettingsFile = build.getProject().getIvySettingsFile();
    File settingsLoc = (ivySettingsFile == null) ? null
            : new File(build.getWorkspace().getRemote(), ivySettingsFile);

    if ((settingsLoc != null) && (!settingsLoc.exists())) {
        return null;
    }

    String ivySettingsPropertyFiles = build.getProject().getIvySettingsPropertyFiles();
    ArrayList<File> propertyFiles = new ArrayList<File>();
    if (StringUtils.isNotBlank(ivySettingsPropertyFiles)) {
        for (String file : ivySettingsPropertyFiles.split(",")) {
            File propertyFile = new File(build.getWorkspace().getRemote(), file.trim());
            if (!propertyFile.exists()) {
                LOGGER.warning("Skipped property file " + file);
            }
            propertyFiles.add(propertyFile);
        }
    }

    try {
        IvySettings ivySettings = new IvySettings();
        for (File file : propertyFiles) {
            ivySettings.loadProperties(file);
        }
        if (settingsLoc != null) {
            ivySettings.load(settingsLoc);
            LOGGER.fine("Configured Ivy using custom settings " + settingsLoc.getAbsolutePath());
        } else {
            ivySettings.loadDefault();
            LOGGER.fine("Configured Ivy using default 2.1 settings");
        }
        return Ivy.newInstance(ivySettings);
    } catch (Exception e) {
        LOGGER.severe("Error while reading the default Ivy 2.1 settings: " + e.getMessage());
        LOGGER.severe(Arrays.toString(e.getStackTrace()));
    }
    return null;
}

From source file:org.amplafi.jawr.maven.JawrMojo.java

private void setupJawrConfig(ServletConfig config, ServletContext context, final Map<String, Object> attributes,
        final Response respData) {
    expect(config.getServletContext()).andReturn(context).anyTimes();
    expect(config.getServletName()).andReturn("maven-jawr-plugin").anyTimes();

    context.log(isA(String.class));
    expectLastCall().anyTimes();/*from w  ww  .j a v a 2s.  com*/

    expect(context.getResourcePaths(isA(String.class))).andAnswer(new IAnswer<Set>() {

        public Set<String> answer() throws Throwable {
            final Set<String> set = new HashSet<String>();

            // hack to disallow orphan bundles
            Exception e = new Exception();
            for (StackTraceElement trace : e.getStackTrace()) {
                if (trace.getClassName().endsWith("OrphanResourceBundlesMapper")) {
                    return set;
                }
            }

            String path = (String) EasyMock.getCurrentArguments()[0];
            File file = new File(getRootPath() + path);

            if (file.exists() && file.isDirectory()) {
                for (String one : file.list()) {
                    set.add(path + one);
                }
            }

            return set;
        }

    }).anyTimes();

    expect(context.getResourceAsStream(isA(String.class))).andAnswer(new IAnswer<InputStream>() {

        public InputStream answer() throws Throwable {
            String path = (String) EasyMock.getCurrentArguments()[0];
            File file = new File(getRootPath(), path);
            return new FileInputStream(file);
        }

    }).anyTimes();

    expect(context.getAttribute(isA(String.class))).andAnswer(new IAnswer<Object>() {

        public Object answer() throws Throwable {
            return attributes.get(EasyMock.getCurrentArguments()[0]);
        }

    }).anyTimes();

    context.setAttribute(isA(String.class), isA(Object.class));
    expectLastCall().andAnswer(new IAnswer<Object>() {

        public Object answer() throws Throwable {
            String key = (String) EasyMock.getCurrentArguments()[0];
            Object value = EasyMock.getCurrentArguments()[1];
            attributes.put(key, value);
            return null;
        }

    }).anyTimes();

    expect(config.getInitParameterNames()).andReturn(new Enumeration<String>() {

        public boolean hasMoreElements() {
            return false;
        }

        public String nextElement() {
            return null;
        }

    }).anyTimes();

    expect(config.getInitParameter(JawrConstant.TYPE_INIT_PARAMETER)).andAnswer(new IAnswer<String>() {
        public String answer() throws Throwable {
            return respData == null ? null : respData.getType();
        }
    }).anyTimes();

    expect(config.getInitParameter("configLocation")).andReturn(getConfigLocation()).anyTimes();
    expect(config.getInitParameter("configPropertiesSourceClass")).andReturn(null).anyTimes();
}