Example usage for java.io IOException setStackTrace

List of usage examples for java.io IOException setStackTrace

Introduction

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

Prototype

public void setStackTrace(StackTraceElement[] stackTrace) 

Source Link

Document

Sets the stack trace elements that will be returned by #getStackTrace() and printed by #printStackTrace() and related methods.

Usage

From source file:org.mule.transport.telnet.TelnetClientWrapper.java

/**
 * /*  ww  w .j av a  2  s.  co  m*/
 * @param command
 * @param waitTime
 *            mill sec.
 * @return exec command result lines
 * @throws Exception 
 */
public String execCommand(MuleMessage _command) throws IOException, ResponseTimeoutException {
    logger.trace("execute command {" + _command + "}");
    String command;
    try {
        command = _command.getPayloadAsString();
    } catch (Exception e) {
        IOException exception = new IOException("can't transform Object {" + _command + "}");
        exception.setStackTrace(e.getStackTrace());
        throw exception;
    }

    this.command = _command;
    String[] result = null;
    StringBuilder sb = new StringBuilder();

    writeStream(command + "\n");

    // reading stream until matching prompt message. (e.g. "[user@localhost ~]$ ", "C:\Documents and Settings\Administrator>") 
    result = readStream("((.*)" + promptRegex + ")$").split("\\n");

    logger.trace("skip string - [" + result[0] + "]");

    for (int i = 1; i < result.length - 1; i++) {
        sb.append(result[i]).append("\n");
    }

    Pattern p2 = Pattern.compile(promptRegex + "$");
    Matcher m2 = p2.matcher(result[result.length - 1]);
    if (!m2.find()) {
        sb.append(result[result.length - 1]);
    } else {
        logger.trace("skip string - [" + result[result.length - 1] + "]");
    }

    if (logger.isTraceEnabled()) {
        logger.trace("command - " + command);
        logger.trace("command result - " + sb.toString());
    }

    setExitStatus();

    //Should there be return null if result == null?
    return sb.toString();
}

From source file:org.archive.io.arc.ARCReader.java

/**
 * Create new arc record.//from w  w w  . j  a va2  s. co  m
 *
 * Encapsulate housekeeping that has to do w/ creating a new record.
 *
 * <p>Call this method at end of constructor to read in the
 * arcfile header.  Will be problems reading subsequent arc records
 * if you don't since arcfile header has the list of metadata fields for
 * all records that follow.
 * 
 * <p>When parsing through ARCs writing out CDX info, we spend about
 * 38% of CPU in here -- about 30% of which is in getTokenizedHeaderLine
 * -- of which 16% is reading.
 *
 * @param is InputStream to use.
 * @param offset Absolute offset into arc file.
 * @return An arc record.
 * @throws IOException
 */
protected ARCRecord createArchiveRecord(InputStream is, long offset) throws IOException {
    try {
        String version = super.getVersion();
        ARCRecord record = new ARCRecord(is, getReaderIdentifier(), offset, isDigest(), isStrict(),
                isParseHttpHeaders(), isAlignedOnFirstRecord(), version);
        if (version != null && super.getVersion() == null)
            super.setVersion(version);
        currentRecord(record);
    } catch (IOException e) {
        if (e instanceof RecoverableIOException) {
            // Don't mess with RecoverableIOExceptions.  Let them out.
            throw e;
        }
        IOException newE = new IOException(e.getMessage() + " (Offset " + offset + ").");
        newE.setStackTrace(e.getStackTrace());
        throw newE;
    }
    return (ARCRecord) getCurrentRecord();
}

From source file:org.mule.transport.telnet.TelnetClientWrapper.java

public String sudoExecCommand(MuleMessage _command, String password)
        throws IOException, ResponseTimeoutException

{
    logger.trace("execute sudo command {" + _command + "}");
    String command;//from w  ww .j  av  a 2  s.co  m
    try {
        command = _command.getPayloadAsString(encoding);
    } catch (Exception e) {
        //TODO
        IOException exception = new IOException("can't transform Object {" + _command + "}");
        exception.setStackTrace(e.getStackTrace());
        throw exception;
    }
    this.command = _command;
    String[] result = null;
    StringBuilder before = new StringBuilder();
    StringBuilder after = new StringBuilder();

    int marker = 0;

    writeStream(command + "\n");

    result = readStream("(.*)$").split("\\n");

    if (result != null) {
        for (int i = 0; i < result.length; i++) {
            before.append(result[i]).append("\\n");

        }

        if (logger.isTraceEnabled())
            logger.trace("sudo result 1 : " + before.toString());

        if (result[result.length - 1].matches(".*(Password:\\s*|:\\s*)")) {
            logger.debug("send password");
            result = send(password);
            marker += 1;
        } else {
            logger.trace("skip string - [" + result[marker] + "]");
            marker += 1; // if don't required Password, skip to next line.
        }

    } else {
        setExitStatus();
        return null;
    }

    Pattern p = Pattern.compile(promptRegex + command);

    if (result.length > marker) {
        Matcher m = p.matcher(result[marker]);
        if (m.find()) {
            logger.trace("skip string - [" + result[marker] + "]");
            marker += 1;
        }
    }
    for (int i = 0 + marker; i < result.length - 1; i++) {

        after.append(result[i]).append("\n");

    }

    Pattern p2 = Pattern.compile(promptRegex + "$");
    Matcher m2 = p2.matcher(result[result.length - 1]);
    if (!m2.find()) {
        after.append(result[result.length - 1]);
    }

    setExitStatus();
    try {
        logger.trace("result - '" + _command.getPayloadAsString() + "' : " + after.toString());
    } catch (Exception e) {

    }

    return after.toString();
}

From source file:com.aliasi.lingmed.medline.DownloadMedline.java

private void raiseIOException(String description) throws IOException {
    IOException ioe = new IOException(description + " FTP failure: " + ftpLastReply());
    ioe.setStackTrace(Thread.currentThread().getStackTrace());
    throw ioe;/*from   w w  w. j  a v a 2s  .  c om*/
}

From source file:com.spinn3r.api.BaseClient.java

protected URLConnection getConnection(String resource) throws IOException {

    URLConnection conn = null;//  w  w w .  ja v  a2 s  . c  o  m

    try {

        // create the HTTP connection.
        URL request = new URL(resource);
        conn = request.openConnection();

        // set the UserAgent so Spinn3r know which client lib is calling.
        conn.setRequestProperty(USER_AGENT_HEADER, USER_AGENT + "; " + getConfig().getCommandLine());
        conn.setRequestProperty(ACCEPT_ENCODING_HEADER, GZIP_ENCODING);
        conn.setConnectTimeout(20000);
        conn.connect();

    }

    catch (IOException ioe) {

        //create a custom exception message with the right error.
        String message = conn.getHeaderField(null);
        IOException ce = new IOException(message);
        ce.setStackTrace(ioe.getStackTrace());

        throw ce;
    }

    return conn;
}

From source file:com.cyberway.issue.io.arc.ARCReader.java

/**
 * Create new arc record./*ww  w  .j av  a  2 s  .com*/
 *
 * Encapsulate housekeeping that has to do w/ creating a new record.
 *
 * <p>Call this method at end of constructor to read in the
 * arcfile header.  Will be problems reading subsequent arc records
 * if you don't since arcfile header has the list of metadata fields for
 * all records that follow.
 * 
 * <p>When parsing through ARCs writing out CDX info, we spend about
 * 38% of CPU in here -- about 30% of which is in getTokenizedHeaderLine
 * -- of which 16% is reading.
 *
 * @param is InputStream to use.
 * @param offset Absolute offset into arc file.
 * @return An arc record.
 * @throws IOException
 */
protected ARCRecord createArchiveRecord(InputStream is, long offset) throws IOException {
    ArrayList<String> firstLineValues = new ArrayList<String>(20);
    getTokenizedHeaderLine(is, firstLineValues);
    int bodyOffset = 0;
    if (offset == 0 && isAlignedOnFirstRecord()) {
        // If offset is zero and we were aligned at first record on
        // creation (See #alignedOnFirstRecord for more on this), then no
        // records have been read yet and we're reading our first one, the
        // record of ARC file meta info.  Its special.  In ARC versions
        // 1.x, first record has three lines of meta info. We've just read
        // the first line. There are two more.  The second line has misc.
        // info.  We're only interested in the first field, the version
        // number.  The third line is the list of field names. Here's what
        // ARC file version 1.x meta content looks like:
        //
        // filedesc://testIsBoundary-JunitIAH200401070157520.arc 0.0.0.0 \\
        //      20040107015752 text/plain 77
        // 1 0 InternetArchive
        // URL IP-address Archive-date Content-type Archive-length
        //
        ArrayList<String> secondLineValues = new ArrayList<String>(20);
        bodyOffset += getTokenizedHeaderLine(is, secondLineValues);
        setVersion((String) secondLineValues.get(0) + "." + (String) secondLineValues.get(1));
        // Just read over the 3rd line.  We used to parse it and use
        // values found here but now we just hardcode them to avoid
        // having to read this 3rd line even for random arc file accesses.
        bodyOffset += getTokenizedHeaderLine(is, null);
    }

    try {
        currentRecord(
                new ARCRecord(is,
                        (ArchiveRecordHeader) computeMetaData(this.headerFieldNameKeys, firstLineValues,
                                getVersion(), offset),
                        bodyOffset, isDigest(), isStrict(), isParseHttpHeaders()));
    } catch (IOException e) {
        if (e instanceof RecoverableIOException) {
            // Don't mess with RecoverableIOExceptions.  Let them out.
            throw e;
        }
        IOException newE = new IOException(e.getMessage() + " (Offset " + offset + ").");
        newE.setStackTrace(e.getStackTrace());
        throw newE;
    }
    return (ARCRecord) getCurrentRecord();
}

From source file:de.innovationgate.wgpublisher.services.WGACoreServicesImpl.java

public DataSource createContentStoreDump(RemoteSession session, String dbKey, final boolean includeACL,
        final boolean includeSystemAreas) throws WGAServiceException {
    if (!isAdminServiceEnabled()) {
        throw new WGAServiceException("Administrative services are disabled");
    }//  www.  j a  v  a2  s .c om

    if (!isAdminSession(session)) {
        throw new WGAServiceException("You need an administrative login to access this service.");
    }

    try {
        final WGDatabase db = retrieveAndOpenDB(session, dbKey);
        if (db != null && db.isSessionOpen()) {
            return new DataSource() {

                public OutputStream getOutputStream() throws IOException {
                    return null;
                }

                public String getName() {
                    return "Dump '" + db.getDbReference() + "'";
                }

                public InputStream getInputStream() throws IOException {
                    try {
                        return _core.dumpContentStore(db, "", true, _core.getLog(), includeACL,
                                includeSystemAreas);
                    } catch (WGAPIException e) {
                        IOException ioe = new IOException(e.getMessage());
                        ioe.setStackTrace(e.getStackTrace());
                        throw ioe;
                    }
                }

                public String getContentType() {
                    return "application/zip";
                }
            };
        } else {
            throw new WGAServiceException("Unable to open database '" + dbKey + "'.");
        }
    } catch (Exception e) {
        throw new WGAServiceException("Import of content store dump failed for database '" + dbKey + "'.", e);
    }
}

From source file:org.apache.hadoop.hbase.ipc.ScheduleHBaseServer.java

@Override
public Writable call(Writable param, long receivedTime) throws IOException {
    try {//from ww  w.j  a v a2  s. c om
        Invocation call = (Invocation) param;
        if (call.getMethodName() == null) {
            throw new IOException("Could not find requested method, the usual "
                    + "cause is a version mismatch between client and server.");
        }

        Method method = implementation.getMethod(call.getMethodName(), call.getParameterClasses());

        long startTime = System.currentTimeMillis();

        Object value = method.invoke(instance, call.getParameters());
        /**
         * do with openScanner option, added by ScheduleHBaseServer
         */
        if (call.getMethodName().endsWith("openScanner")) {
            this.initScannerPri(call, value);
        }

        int processingTime = (int) (System.currentTimeMillis() - startTime);
        int qTime = (int) (startTime - receivedTime);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Served: " + call.getMethodName() + " queueTime= " + qTime + " procesingTime= "
                    + processingTime);
        }
        rpcMetrics.rpcQueueTime.inc(qTime);
        rpcMetrics.rpcProcessingTime.inc(processingTime);
        rpcMetrics.inc(call.getMethodName(), processingTime);

        return new HbaseObjectWritable(method.getReturnType(), value);

    } catch (InvocationTargetException e) {
        Throwable target = e.getTargetException();
        if (target instanceof IOException) {
            throw (IOException) target;
        }
        IOException ioe = new IOException(target.toString());
        ioe.setStackTrace(target.getStackTrace());
        throw ioe;
    } catch (Throwable e) {
        IOException ioe = new IOException(e.toString());
        ioe.setStackTrace(e.getStackTrace());
        throw ioe;
    }
}

From source file:com.ibm.team.build.internal.hjplugin.util.HttpUtils.java

/**
 * Log the error that occurred and provide an exception that encapsulates the failure as best as
 * possible. This means parsing the output and if its from RTC extract the stack trace from 
 * there./*w  ww  .  j  av a  2s. c om*/
 * @param fullURI The URI requested
 * @param httpResponse The response from the request
 * @param message A message for the failure if nothing can be detected from the response
 * @return An exception representing the failure
 */
@SuppressWarnings("rawtypes")
private static IOException logError(String fullURI, CloseableHttpResponse httpResponse, String message) {
    printMessageHeaders(httpResponse);

    IOException error = new IOException(message);
    try {
        InputStreamReader inputStream = new InputStreamReader(httpResponse.getEntity().getContent(), UTF_8);
        try {
            String response = IOUtils.toString(inputStream);
            // this is one lonnnng string if its a stack trace.
            // try to get it as JSON so we can output it in a more friendly way.
            try {
                JSON json = JSONSerializer.toJSON(response);
                response = json.toString(4);
                if (json instanceof JSONObject) {
                    // see if we have a stack trace
                    JSONObject jsonObject = (JSONObject) json;
                    String errorMessage = jsonObject.getString("errorMessage"); //$NON-NLS-1$
                    error = new IOException(errorMessage);
                    JSONArray trace = jsonObject.getJSONArray("errorTraceMarshall"); //$NON-NLS-1$
                    List<StackTraceElement> stackElements = new ArrayList<StackTraceElement>(trace.size());
                    for (Iterator iterator = trace.iterator(); iterator.hasNext();) {
                        Object element = iterator.next();
                        if (element instanceof JSONObject) {
                            JSONObject jsonElement = (JSONObject) element;
                            String cls = jsonElement.getString("errorTraceClassName"); //$NON-NLS-1$
                            String method = jsonElement.getString("errorTraceMethodName"); //$NON-NLS-1$
                            String file = jsonElement.getString("errorTraceFileName"); //$NON-NLS-1$
                            int line = jsonElement.getInt("errorTraceLineNumber"); //$NON-NLS-1$
                            StackTraceElement stackElement = new StackTraceElement(cls, method, file, line);
                            stackElements.add(stackElement);
                        }
                    }
                    error.setStackTrace(stackElements.toArray(new StackTraceElement[stackElements.size()]));

                    // our RTC responses have the stack trace in there twice. Remove 1 copy of it.
                    jsonObject.remove("errorTraceMarshall"); //$NON-NLS-1$
                    response = jsonObject.toString(4);
                }
            } catch (JSONException e) {
                // not JSON or not a RTC stack trace in the JSONObject so just log what we have
            }
            LOGGER.finer(response);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                LOGGER.finer("Failed to close the result input stream for request: " + fullURI); //$NON-NLS-1$
            }
        }
    } catch (IOException e) {
        LOGGER.finer("Unable to capture details of the failure"); //$NON-NLS-1$
    }
    return error;
}