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:py.edu.ucsa.voto.ws.service.VotoEndpoint.java

@PayloadRoot(localPart = VOTAR_REQUEST, namespace = NAMESPACE)
public VotarResponse votar(VotarRequest request) {
    //Date fecha = consultarTransaccionRequestDAO.getDataBaseTime(); //se obtiene la fecha
    //request.setFchins(fecha); //se setea la fecha

    VotarResponse response = new VotarResponse();

    try {/*from ww w.  j  ava2  s .  c  om*/
        // enviar a cola request
        //         String idMessageRequest = gfvJmsMessageManager
        //               .enviarObjectMessage(request);
        // recibir response
        votarRequestDAO.saveOrUpdate(request);

        response.setCodigo(new BigDecimal(_CODIGO_VOTO_OK));
        response.setDescripcion(_VOTO_OK_DESCRIPCION);
        response.setVotarRequest(request);

        Genero genero = new Genero();

        genero.setDescripcion("Masculino");

        generoDAO.save(genero);

    } catch (Exception e) {
        logger.error(e.getStackTrace(), e);

        response.setCodigo(new BigDecimal(_CODIGO_VOTO_OK));
        response.setDescripcion(_VOTO_OK_DESCRIPCION);
        response.setVotarRequest(request);
    }

    votarResponseDAO.saveOrUpdate(response);
    return response;
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.jena.JenaXMLFileUpload.java

/**
 * Each file will be converted to RDF/XML and loaded to the target model.
 * If any of the files fail, no data will be loaded.
 * //from  w  w w.  j  av a2  s.c  o  m
 * parameters:
 * targetModel - model to save to
 * defaultNamespace - namespace to use for elements in xml that lack a namespace
 * 
 */
@Override
public void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
    VitroRequest vreq = new VitroRequest(request);
    if (vreq.hasFileSizeException()) {
        throw new ServletException("Size limit exceeded: " + vreq.getFileSizeException().getLocalizedMessage());
    }
    if (vreq.isMultipart()) {
        log.debug("multipart content detected");
    } else {
        // TODO: forward to error message
        throw new ServletException("Must POST a multipart encoded request");
    }

    if (!isAuthorizedToDisplayPage(request, resp, SimplePermission.USE_ADVANCED_DATA_TOOLS_PAGES.ACTION)) {
        return;
    }

    ModelMaker modelMaker = getModelMaker(vreq);
    String targetModel = request.getParameter("targetModel");
    if (targetModel == null) {
        throw new ServletException("targetModel not specified.");
    }

    Model m = modelMaker.getModel(targetModel);
    if (m == null)
        throw new ServletException("targetModel '" + targetModel + "' was not found.");
    request.setAttribute("targetModel", targetModel);

    List<File> filesToLoad = saveFiles(vreq.getFiles());
    List<File> rdfxmlToLoad = convertFiles(filesToLoad);
    List<Model> modelsToLoad = loadRdfXml(rdfxmlToLoad);

    try {
        m.enterCriticalSection(Lock.WRITE);
        for (Model model : modelsToLoad) {
            m.add(model);
        }
    } finally {
        m.leaveCriticalSection();
    }

    long count = countOfStatements(modelsToLoad);
    request.setAttribute("statementCount", count);

    request.setAttribute("title", "Uploaded files and converted to RDF");
    request.setAttribute("bodyJsp", "/jenaIngest/xmlFileUploadSuccess.jsp");

    request.setAttribute("fileItems", vreq.getFiles());

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("css", "<link rel=\"stylesheet\" type=\"text/css\" href=\""
            + vreq.getAppBean().getThemeDir() + "css/edit.css\"/>");

    try {
        rd.forward(request, resp);
    } catch (Exception e) {
        System.out.println(this.getClass().getName() + " could not forward to view.");
        System.out.println(e.getMessage());
        System.out.println(e.getStackTrace());
    }
}

From source file:com.intel.xdk.contacts.Contacts.java

public void removeContact(String contactId) {
    if (busy == true) {
        String js = "javascript: var e = document.createEvent('Events');e.initEvent('intel.xdk.contacts.busy',true,true);e.success=false;e.message='busy';document.dispatchEvent(e);";
        injectJS(js);//from   w ww  .j a v a 2 s  .c  o m
        return;
    }

    try {
        Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, contactId);
        int rowsDeleted = activity.getContentResolver().delete(uri, null, null);

        if (rowsDeleted > 0) {
            getAllContacts();
            String js = String.format(
                    "var e = document.createEvent('Events');e.initEvent('intel.xdk.contacts.remove',true,true);e.success=true;e.contactid='%s';document.dispatchEvent(e);",
                    contactId);
            injectJS("javascript: " + js);
        } else {
            String js = String.format(
                    "var e = document.createEvent('Events');e.initEvent('intel.xdk.contacts.remove',true,true);e.success=false;e.error='error deleting contact';e.contactid='%s';document.dispatchEvent(e);",
                    contactId);
            injectJS("javascript: " + js);
        }
        busy = false;
    } catch (Exception e) {
        System.out.println(e.getStackTrace());
        String errjs = String.format(
                "var e = document.createEvent('Events');e.initEvent('intel.xdk.contacts.remove',true,true);e.success=false;e.error='contact not found';e.contactid='%s';document.dispatchEvent(e);",
                contactId);
        injectJS("javascript: " + errjs);
        busy = false;
        return;
    }
}

From source file:eu.europa.esig.dss.DSSUtils.java

/**
 * This method returns the summary of the given exception. The analysis of the stack trace stops when the provided class is found.
 *
 * @param exception//from  w  w  w  .j av a 2s  .com
 *            {@code Exception} to summarize
 * @param javaClass
 *            {@code Class}
 * @return {@code String} containing the summary message
 */
public static String getSummaryMessage(final Exception exception, final Class<?> javaClass) {

    final String javaClassName = javaClass.getName();
    final StackTraceElement[] stackTrace = exception.getStackTrace();
    String message = "See log file for full stack trace.\n";
    message += exception.toString() + '\n';
    for (StackTraceElement element : stackTrace) {

        final String className = element.getClassName();
        if (className.equals(javaClassName)) {

            message += element.toString() + '\n';
            break;
        }
        message += element.toString() + '\n';
    }
    return message;
}

From source file:py.edu.ucsa.voto.ws.service.VotoEndpoint.java

@PayloadRoot(localPart = AUTENTICAR_REQUEST, namespace = NAMESPACE)
public AutenticarResponse autenticar(AutenticarRequest request) {
    //Date fecha = consultarTransaccionRequestDAO.getDataBaseTime(); //se obtiene la fecha
    //request.setFchins(fecha); //se setea la fecha

    AutenticarResponse response = new AutenticarResponse();

    try {/*from w  ww  .  jav a 2s . co  m*/
        // enviar a cola request
        //         String idMessageRequest = gfvJmsMessageManager
        //               .enviarObjectMessage(request);
        // recibir response
        autenticarRequestDAO.saveOrUpdate(request);

        //agregar consulta a la db preguntando por el user y pass
        //si encuntra ok sino no
        List<Users> autenticado = autenticarResponseDAO.getUserAutenticado(request.getUsuario(),
                request.getContrasenha());

        if (!autenticado.isEmpty()) {
            if (autenticado.get(0).getEs_admin() == true) {
                response.setCodigo(new BigDecimal(_CODIGO_OK_AUTENTICADO_ADMIN));
                response.setDescripcion(_DESCRIPCION_OK_AUTENTICADO_ADMIN);
                response.setAutenticarRequest(request);
            } else {
                response.setCodigo(new BigDecimal(_CODIGO_OK_AUTENTICADO_VOTANTE));
                response.setDescripcion(_DESCRIPCION_OK_AUTENTICADO_VOTANTE);
                response.setAutenticarRequest(request);
            }

        }

        else {
            response.setCodigo(new BigDecimal(_CODIGO_NO_AUTENTICADO));
            response.setDescripcion(_DESCRIPCION_NO_AUTENTICADO);
            response.setAutenticarRequest(request);

        }

    } catch (Exception e) {
        logger.error(e.getStackTrace(), e);

        response.setCodigo(new BigDecimal(_CODIGO_ERROR_DESCONOCIDO));
        response.setDescripcion(e.getMessage());
        response.setAutenticarRequest(request);

    }

    autenticarResponseDAO.saveOrUpdate(response);
    return response;
}

From source file:nz.co.fortytwo.signalk.handler.GitHandler.java

private void runNpmInstall(final File output, File destDir) throws Exception {
    FileUtils.writeStringToFile(output, "\nBeginning npm install", true);
    ProcessBuilder pb = new ProcessBuilder("npm", "install");
    Map<String, String> env = System.getenv();
    if (env.containsKey("PATH")) {
        pb.environment().put("PATH", env.get("PATH"));
    }//from  ww w  . j a  v  a2 s  . c o  m
    if (env.containsKey("Path")) {
        pb.environment().put("Path", env.get("Path"));
    }
    if (env.containsKey("path")) {
        pb.environment().put("path", env.get("path"));
    }
    pb.directory(destDir);
    pb.redirectErrorStream(true);
    pb.redirectOutput(output);
    final Process p = pb.start();
    Thread t = new Thread() {

        @Override
        public void run() {
            try {
                p.waitFor();
                FileUtils.writeStringToFile(output, "\nDONE: Npm ended sucessfully", true);
            } catch (Exception e) {
                try {
                    logger.error(e);
                    FileUtils.writeStringToFile(output, "\nNpm ended badly:" + e.getMessage(), true);
                    FileUtils.writeStringToFile(output, "\n" + e.getStackTrace(), true);
                } catch (IOException e1) {
                    logger.error(e1);
                }
            }
        }

    };
    t.start();
}

From source file:$.NewOperator.java

@Override
    protected void execute(ExecutionContext context) {

        RecordInput recordInput = getInput().getInput(context);
        RecordOutput recordOutput = getOutput().getOutput(context);
        RecordOutput recordReject = getReject().getOutput(context);

        ScalarValued[] allInputs = recordInput.getFields();
        ScalarSettable[] outputs = TokenUtils.selectFields(recordOutput, recordInput.getType().getNames());
        ScalarSettable[] rejects = TokenUtils.selectFields(recordReject, recordInput.getType().getNames());

        // Quit early if the operator configuration isn't valid
        if (checkConfig() == false) {
            recordOutput.pushEndOfData();
            recordReject.pushEndOfData();
            return;
        }/*from  w  ww  .j  av  a  2s . com*/

        while (recordInput.stepNext()) {
            try {

                // Copy the original input record fields to the corresponding output record fields
                TokenUtils.transfer(allInputs, outputs);
                StringSettable outputField = (StringSettable) recordOutput.getField("OutputString");
                outputField.set(outputString);
                recordOutput.push();
            } catch (Exception e) {
                // Copy the original input record fields to the corresponding reject record fields
                TokenUtils.transfer(allInputs, rejects);
                StringSettable errorField = (StringSettable) recordReject.getField("ErrorText");
                errorField.set(e.getMessage() + "${symbol_escape}n" + Arrays.toString(e.getStackTrace()));
                recordReject.push();

            }
        }

        recordOutput.pushEndOfData();
        recordReject.pushEndOfData();
    }

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

public void doGet(HttpServletRequest request, HttpServletResponse response) {
    if (!isAuthorizedToDisplayPage(request, response, SimplePermission.DO_BACK_END_EDITING.ACTION)) {
        return;/*w ww. j  a v a  2  s.  co  m*/
    }

    String entURI = request.getParameter("uri");
    VitroRequest vreq = (new VitroRequest(request));
    ApplicationBean application = vreq.getAppBean();

    //Individual ent = vreq.getWebappDaoFactory().getIndividualDao().getIndividualByURI(entURI);
    Individual ent = vreq.getUnfilteredAssertionsWebappDaoFactory().getIndividualDao()
            .getIndividualByURI(entURI);
    if (ent == null) {
        try {
            RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
            request.setAttribute("bodyJsp", "/jenaIngest/notfound.jsp");
            request.setAttribute("title", "Individual Not Found");
            request.setAttribute("css", "<link rel=\"stylesheet\" type=\"text/css\" href=\""
                    + application.getThemeDir() + "css/edit.css\"/>");
            rd.forward(request, response);
        } catch (Exception e) {
            log.error("EntityEditController could not forward to view.");
            log.error(e.getMessage());
            log.error(e.getStackTrace());
        }
    }

    Individual inferredEnt = vreq.getUnfilteredWebappDaoFactory().getIndividualDao().getIndividualByURI(entURI);
    if (inferredEnt == null) {
        inferredEnt = new IndividualImpl(entURI);
    }

    request.setAttribute("entity", ent);

    ArrayList<String> results = new ArrayList<String>();
    int colCount = 4;
    results.add("Name");
    results.add("class");
    results.add("display level");
    results.add("edit level");
    results.add("last updated");
    colCount++;
    results.add("URI");
    colCount++;
    results.add("publish level");
    colCount++;

    String rName = null;
    if (ent.getName() != null && ent.getName().length() > 0) {
        rName = ent.getName();
    } else if (ent.getLocalName() != null && ent.getLocalName().length() > 0) {
        rName = ent.getLocalName();
    } else if (ent.isAnonymous()) {
        rName = "[anonymous resource]";
    } else {
        rName = "[resource]";
    }
    results.add(rName);

    String classStr = "";
    List<VClass> classList = inferredEnt.getVClasses(false);
    sortForPickList(classList, vreq);
    if (classList != null) {
        for (Iterator<VClass> classIt = classList.iterator(); classIt.hasNext();) {
            VClass vc = classIt.next();
            String rClassName = "";
            try {
                rClassName = "<a href=\"vclassEdit?uri=" + URLEncoder.encode(vc.getURI(), "UTF-8") + "\">"
                        + vc.getPickListName() + "</a>";
            } catch (Exception e) {
                rClassName = vc.getLocalNameWithPrefix();
            }
            classStr += rClassName;
            if (classIt.hasNext()) {
                classStr += ", ";
            }
        }
    }
    results.add(classStr);

    results.add(ent.getHiddenFromDisplayBelowRoleLevel() == null ? "unspecified"
            : ent.getHiddenFromDisplayBelowRoleLevel().getDisplayLabel());
    results.add(ent.getProhibitedFromUpdateBelowRoleLevel() == null ? "unspecified"
            : ent.getProhibitedFromUpdateBelowRoleLevel().getUpdateLabel());

    String rModTime = (ent.getModTime() == null) ? "" : publicDateFormat.format(ent.getModTime());
    results.add(rModTime);
    results.add((ent.getURI() == null) ? "[anonymous individual]" : ent.getURI());
    results.add(ent.getHiddenFromPublishBelowRoleLevel() == null ? "unspecified"
            : ent.getHiddenFromPublishBelowRoleLevel().getDisplayLabel());
    request.setAttribute("results", results);
    request.setAttribute("columncount", colCount);
    request.setAttribute("suppressquery", "true");

    EditProcessObject epo = super.createEpo(request, FORCE_NEW);
    request.setAttribute("epo", epo);

    FormObject foo = new FormObject();
    HashMap<String, List<Option>> OptionMap = new HashMap<String, List<Option>>();

    List<VClass> types = ent.getVClasses(false);
    sortForPickList(types, vreq);
    request.setAttribute("types", types); // we're displaying all assertions, including indirect types

    try {
        List<Option> externalIdOptionList = new LinkedList<Option>();
        if (ent.getExternalIds() != null) {
            Iterator<DataPropertyStatement> externalIdIt = ent.getExternalIds().iterator();
            while (externalIdIt.hasNext()) {
                DataPropertyStatement eid = externalIdIt.next();
                String multiplexedString = new String(
                        "DatapropURI:" + new String(Base64.encodeBase64(eid.getDatapropURI().getBytes())) + ";"
                                + "Data:" + new String(Base64.encodeBase64(eid.getData().getBytes())));
                externalIdOptionList.add(new Option(multiplexedString, eid.getData()));
            }
        }
        OptionMap.put("externalIds", externalIdOptionList);
    } catch (Exception e) {
        log.error(e, e);
    }

    try {
        OptionMap.put("VClassURI",
                FormUtils.makeOptionListFromBeans(
                        vreq.getUnfilteredWebappDaoFactory().getVClassDao().getAllVclasses(), "URI",
                        "PickListName", ent.getVClassURI(), null, false));
    } catch (Exception e) {
        log.error(e, e);
    }

    PropertyInstanceDao piDao = vreq.getUnfilteredWebappDaoFactory().getPropertyInstanceDao();
    // existing property statements
    try {
        List epiOptionList = new LinkedList();
        Collection<PropertyInstance> epiColl = piDao.getExistingProperties(ent.getURI(), null);
        Iterator<PropertyInstance> epiIt = epiColl.iterator();
        while (epiIt.hasNext()) {
            PropertyInstance pi = epiIt.next();
            String multiplexedString = new String("PropertyURI:"
                    + new String(Base64.encodeBase64(pi.getPropertyURI().getBytes())) + ";" + "ObjectEntURI:"
                    + new String(Base64.encodeBase64(pi.getObjectEntURI().getBytes())));
            epiOptionList.add(new Option(multiplexedString, pi.getDomainPublic() + " " + pi.getObjectName()));
        }
        OptionMap.put("ExistingPropertyInstances", epiOptionList);
    } catch (Exception e) {
        log.error(e, e);
    }
    // possible property statements
    try {
        Collection piColl = piDao.getAllPossiblePropInstForIndividual(ent.getURI());
        List piList = new ArrayList();
        piList.addAll(piColl);
        OptionMap.put("PropertyURI", FormUtils.makeOptionListFromBeans(piList, "PropertyURI", "DomainPublic",
                (String) null, (String) null, false));
    } catch (Exception e) {
        log.error(e, e);
    }

    foo.setOptionLists(OptionMap);

    epo.setFormObject(foo);

    RequestDispatcher rd = request.getRequestDispatcher(Controllers.BASIC_JSP);
    request.setAttribute("epoKey", epo.getKey());
    request.setAttribute("entityWebapp", ent);
    request.setAttribute("bodyJsp", "/templates/edit/specific/ents_edit.jsp");
    request.setAttribute("title", "Individual Control Panel");
    request.setAttribute("css", "<link rel=\"stylesheet\" type=\"text/css\" href=\"" + application.getThemeDir()
            + "css/edit.css\"/>");
    request.setAttribute("scripts", "/templates/edit/specific/ents_edit_head.jsp");

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

}

From source file:de.mpg.escidoc.services.extraction.ExtractionChain.java

public ExtractionResult doExtract(String infileName, String outfileName) {
    File outfile = new File(outfileName);

    Date stepStart = new Date();
    Date current;//w ww .  j  a  v a 2s.  co m

    logger.info("Extracting PDF content ----------------------------------------");
    logger.info("Infile: " + infileName);
    logger.info("Outfile: " + outfileName);

    logger.info(stepStart + " -- started");

    // xPDF

    try {
        logger.info("Extracting with xPDF");

        StringBuffer command = new StringBuffer(2048);
        command.append(System.getProperty("os.name").contains("Windows") ? pdftotext + " -enc UTF-8 "
                : "/usr/bin/pdftotext -enc UTF-8 ");
        command.append(infileName);
        command.append(" ");
        command.append(outfileName);

        Process proc = Runtime.getRuntime().exec(command.toString());

        StreamGobbler inputGobbler = new StreamGobbler(proc.getInputStream(), "xPDF");
        StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "xPDF");

        inputGobbler.start();
        errorGobbler.start();

        int exitCode = proc.waitFor();

        if (proc.exitValue() == 0) {

            if (verbose) {
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(new FileInputStream(outfile), "UTF-8"));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    logger.info(line);
                }
                bufferedReader.close();
            }
            current = new Date();
            logger.info(current + " -- finished successfully");
            logger.info("Extraction took " + (current.getTime() - stepStart.getTime()));

            return ExtractionResult.OK;
        }
    } catch (Exception e) {
        logger.warn("Error extracting PDF with xPDF:");
        logger.warn(e.getStackTrace());
    }

    current = new Date();
    logger.info(current + " -- finished unsuccessfully");
    logger.info("Extraction attempt took " + (current.getTime() - stepStart.getTime()));

    // PDFBox
    try {
        logger.info("Extracting with PDFBox");
        stepStart = new Date();

        StringBuffer command = new StringBuffer(1024);
        command.append(System.getProperty("os.name").contains("Windows")
                ? "java -Dfile.encoding=UTF-8 -jar " + pdfboxAppJar + " ExtractText "
                : "/usr/bin/java -Dfile.encoding=UTF-8 -jar " + pdfboxAppJar + " ExtractText ");
        command.append(infileName);
        command.append(" ");
        command.append(outfileName);

        Process proc = Runtime.getRuntime().exec(command.toString());
        StreamGobbler inputGobbler = new StreamGobbler(proc.getInputStream(), "PDFBox");
        StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), "PDFBox");

        inputGobbler.start();
        errorGobbler.start();

        int exitCode = proc.waitFor();

        if (exitCode == 0) {

            if (verbose) {
                BufferedReader bufferedReader = new BufferedReader(
                        new InputStreamReader(new FileInputStream(outfile), "UTF-8"));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    logger.info(line);
                }
                bufferedReader.close();
            }
            current = new Date();
            logger.info(current + " -- finished successfully");
            logger.info("Extraction took " + (current.getTime() - stepStart.getTime()));

            return ExtractionResult.OK;
        }
    } catch (Exception e) {
        logger.warn("Error extracting PDF with PDFBox:");
        logger.warn(e.getStackTrace());
    }

    current = new Date();
    logger.info(current + " -- finished unsuccessfully");
    logger.info("Extraction attempt took " + (current.getTime() - stepStart.getTime()));

    // iText
    try {
        logger.info("Extracting with iText");
        stepStart = new Date();

        PdfReader reader = new PdfReader(infileName);
        int numberOfPages = reader.getNumberOfPages();

        outputStreamWriter = new OutputStreamWriter(new FileOutputStream(outfile), "UTF-8");
        for (int i = 0; i < numberOfPages; i++) {
            outputStreamWriter.write(PdfTextExtractor.getTextFromPage(reader, i + 1));
        }

        if (verbose) {
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(outfile), "UTF-8"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                logger.info(line);
            }
            bufferedReader.close();
        }

        current = new Date();
        logger.info(current + " -- finished successfully");
        logger.info("Extraction took " + (current.getTime() - stepStart.getTime()));

        return ExtractionResult.OK;

    } catch (Exception e) {
        logger.warn("Error extracting PDF with iText:", e);
    }

    // tika

    InputStream stream = null;

    try {
        logger.info("Extracting with Tika");
        stepStart = new Date();

        stream = TikaInputStream.get(new File(infileName));

        ContentHandler handler = new BodyContentHandler(TIKA_CONTENT_SIZE);

        new AutoDetectParser().parse(stream, handler, new Metadata(), new ParseContext());

        String content = handler.toString();

        FileUtils.writeStringToFile(outfile, content);

        stream.close();

        if (verbose) {
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(new FileInputStream(outfile), "UTF-8"));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                logger.info(line);
            }
            bufferedReader.close();
        }

        current = new Date();
        logger.info(current + " -- finished successfully");
        logger.info("Extraction took " + (current.getTime() - stepStart.getTime()));

        return ExtractionResult.OK;

    } catch (Exception e) {
        logger.warn("Error extracting Tika:", e);
        try {
            stream.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    current = new Date();
    logger.warn(current + " -- finished unsuccessfully");
    logger.info("Extraction attempt took " + (current.getTime() - stepStart.getTime()));

    logger.info("... giving up");

    return ExtractionResult.FAILURE;
}

From source file:org.alfresco.repo.action.AsynchronousActionExecutionQueueImpl.java

@SuppressWarnings("unchecked")
public void executeAction(RuntimeActionService actionService, Action action, NodeRef actionedUponNodeRef,
        boolean checkConditions, Set<String> actionChain, NodeRef actionExecutionHistoryNodeRef) {
    if (logger.isDebugEnabled()) {
        StringBuilder msg = new StringBuilder();
        msg.append("Received request to execute async action ").append(action.getActionDefinitionName())
                .append(" on ").append(actionedUponNodeRef);
        logger.debug(msg.toString());//from w w w .ja  va 2  s  .c  om

        msg = new StringBuilder();
        msg.append("ThreadPool's active count = ").append(this.threadPoolExecutor.getActiveCount());
        logger.debug(msg.toString());

        msg = new StringBuilder();
        msg.append("ThreadPool's queue size = ").append(this.threadPoolExecutor.getQueue().size());
        logger.debug(msg.toString());
    }

    Set<RuleServiceImpl.ExecutedRuleData> executedRules = (Set<RuleServiceImpl.ExecutedRuleData>) AlfrescoTransactionSupport
            .getResource("RuleServiceImpl.ExecutedRules");
    Runnable runnable = new ActionExecutionWrapper(actionService, action, actionedUponNodeRef, checkConditions,
            actionChain, executedRules);

    // Consider whether this action should be filtered out by one of the registered filters.
    boolean newActionShouldBeFilteredOut = false;
    OngoingAsyncAction nodeBeingNewlyActioned = new OngoingAsyncAction(actionedUponNodeRef, action);

    for (Entry<String, AbstractAsynchronousActionFilter> entry : actionFilters.entrySet()) {
        AbstractAsynchronousActionFilter comparator = entry.getValue();
        String actionDefinitionName = comparator.getActionDefinitionName();

        if (actionDefinitionName.equals(action.getActionDefinitionName()) == false) {
            // We're only interested in registered actions with the same name as this one.
            continue;
        } else {
            // Now we've found a registered action that matches the current one.
            // So we'll go through the actions that are ongoing and consider them for matches with this one.
            // Need to synchronize to prevent changes to ongoingActions whilst iterating. Assume that ongoingActions
            // is not going to be too big and the loop will execute quite quickly, so that the synchronization 
            // will not impact concurrency too much.
            synchronized (this.ongoingActions) {
                for (OngoingAsyncAction ongoingAction : this.ongoingActions) {
                    if (comparator.compare(ongoingAction, nodeBeingNewlyActioned) == 0) {
                        newActionShouldBeFilteredOut = true;
                        break;
                    }
                }
            }
        }
    }
    if (newActionShouldBeFilteredOut) {
        if (logger.isDebugEnabled()) {
            StringBuilder msg = new StringBuilder();
            msg.append("Dropping action ").append(action).append(" as equivalent is ongoing.");
            logger.debug(msg.toString());
        }
        return;
    } else {
        if (logger.isDebugEnabled()) {
            StringBuilder msg = new StringBuilder();
            msg.append("Executing action ").append(action);
            logger.debug(msg.toString());
        }

        // Queue it and do it.
        ongoingActions.add(nodeBeingNewlyActioned);
        threadPoolExecutor.execute(runnable);
    }

    // Done
    if (logger.isDebugEnabled()) {
        // get the stack trace
        Exception e = new Exception();
        e.fillInStackTrace();
        StackTraceElement[] trace = e.getStackTrace();
        StringBuilder sb = new StringBuilder();
        sb.append("\n").append("Placed action on execution queue: \n").append("   Action:     " + action);
        String msg = sb.toString();
        sb = new StringBuilder();
        StackTraceUtil.buildStackTrace(msg, trace, sb, -1);
        logger.debug(sb);
    }
}