Java Code Examples for java.io.IOException#setStackTrace()

The following examples show how to use java.io.IOException#setStackTrace() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ExceptionUtils.java    From cacheonix-core with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Added a socket address to a message of an IOException.
 *
 * @param channel channel for that the error occurred.
 * @param e       the I/O exception to enhance
 * @return the enhanced IOException
 */
public static IOException enhanceExceptionWithAddress(final SocketChannel channel, final IOException e) {

   try {

      if (channel == null) {
         return e;
      }

      final SocketAddress socketAddress = channel.socket().getRemoteSocketAddress();
      if (socketAddress == null) {

         return e;
      }
      @SuppressWarnings("ObjectToString") final String socketAddressAsString = socketAddress.toString();
      final IOException result = new IOException(e.getMessage() == null ? socketAddressAsString : socketAddressAsString + ':' + e.getMessage());
      result.setStackTrace(e.getStackTrace());
      return result;
   } catch (final Throwable ignored) {

      // If anything wrong happens, just return the original error
      return e;
   }
}
 
Example 2
Source File: JobHistory.java    From RDFS with Apache License 2.0 6 votes vote down vote up
/**
 * Helper function to encode the URL of the path of the job-history
 * log file. 
 * 
 * @param logFile path of the job-history file
 * @return URL encoded path
 * @throws IOException
 */
public static String encodeJobHistoryFilePath(String logFile)
throws IOException {
  Path rawPath = new Path(logFile);
  String encodedFileName = null;
  try {
    encodedFileName = URLEncoder.encode(rawPath.getName(), "UTF-8");
  } catch (UnsupportedEncodingException uee) {
    IOException ioe = new IOException();
    ioe.initCause(uee);
    ioe.setStackTrace(uee.getStackTrace());
    throw ioe;
  }
  
  Path encodedPath = new Path(rawPath.getParent(), encodedFileName);
  return encodedPath.toString();
}
 
Example 3
Source File: ARCReader.java    From webarchive-commons with Apache License 2.0 6 votes vote down vote up
/**
 * Create new arc record.
 *
 * 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();
}
 
Example 4
Source File: QueryResultsParser.java    From fosstrak-epcis with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * A helper method to parse and convert the XML representation of an EPCIS
 * query document into an QueryResults object.
 * 
 * @param xml
 *            The Reader containing the XML representation of an
 *            EPCISQueryDocumentType object.
 * @return The parsed QueryResults object.
 * @throws IOException
 *             If an error de-serializing the InputStream occurred.
 */
public static QueryResults parseQueryDocResults(final Reader r) throws IOException {
    // de-serialize the XML
    try {
        JAXBContext context = JAXBContext.newInstance(EPCISQueryDocumentType.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        JAXBElement<?> results = (JAXBElement<?>) unmarshaller.unmarshal(r);
        EPCISQueryDocumentType doc = (EPCISQueryDocumentType) results.getValue();
        return doc.getEPCISBody().getQueryResults();
    } catch (JAXBException e) {
        // wrap JAXBException into IOException to keep the interface
        // JAXB-free
        IOException ioe = new IOException(e.getMessage());
        ioe.setStackTrace(e.getStackTrace());
        throw ioe;
    }
}
 
Example 5
Source File: QueryResultsParser.java    From fosstrak-epcis with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * A helper method to parse and convert the XML representation of an EPCIS
 * query results into a QueryResults object.
 * 
 * @param xml
 *            The InputStream containing the XML representation of a
 *            QueryResults object.
 * @return The parsed QueryResults object.
 * @throws IOException
 *             If an error de-serializing the InputStream occurred.
 */
public static QueryResults parseResults(final InputStream xml) throws IOException {
    // de-serialize the XML
    try {
        JAXBContext context = JAXBContext.newInstance(QueryResults.class);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        // setting schema to null will turn XML validation off
        // unmarshaller.setSchema(null);
        JAXBElement<?> results = (JAXBElement<?>) unmarshaller.unmarshal(xml);
        return (QueryResults) results.getValue();
    } catch (JAXBException e) {
        // wrap JAXBException into IOException to keep the interface
        // JAXB-free
        IOException ioe = new IOException(e.getMessage());
        ioe.setStackTrace(e.getStackTrace());
        throw ioe;
    }
}
 
Example 6
Source File: SocketListener.java    From jolie with GNU Lesser General Public License v2.1 6 votes vote down vote up
public SocketListener(
	Interpreter interpreter,
	CommProtocolFactory protocolFactory,
	InputPort inputPort )
	throws IOException {
	super(
		interpreter,
		protocolFactory,
		inputPort );

	serverChannel = ServerSocketChannel.open();
	final ServerSocket socket = serverChannel.socket();
	try {
		socket.bind( new InetSocketAddress( inputPort.location().getPort() ) );
	} catch( IOException e ) {
		final IOException exception =
			new IOException( e.getMessage() + " [with location: " + inputPort.location().toString() + "]" );
		exception.setStackTrace( e.getStackTrace() );
		throw exception;
	}
}
 
Example 7
Source File: FileNameIndexUtils.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Helper function to encode the URL of the filename of the job-history 
 * log file.
 * 
 * @param logFileName file name of the job-history file
 * @return URL encoded filename
 * @throws IOException
 */
public static String encodeJobHistoryFileName(String logFileName)
throws IOException {
  String replacementDelimiterEscape = null;

  // Temporarily protect the escape delimiters from encoding
  if (logFileName.contains(DELIMITER_ESCAPE)) {
    replacementDelimiterEscape = nonOccursString(logFileName);

    logFileName = logFileName.replaceAll(DELIMITER_ESCAPE, replacementDelimiterEscape);
  }

  String encodedFileName = null;
  try {
    encodedFileName = URLEncoder.encode(logFileName, "UTF-8");
  } catch (UnsupportedEncodingException uee) {
    IOException ioe = new IOException();
    ioe.initCause(uee);
    ioe.setStackTrace(uee.getStackTrace());
    throw ioe;
  }

  // Restore protected escape delimiters after encoding
  if (replacementDelimiterEscape != null) {
    encodedFileName = encodedFileName.replaceAll(replacementDelimiterEscape, DELIMITER_ESCAPE);
  }

  return encodedFileName;
}
 
Example 8
Source File: JobHistory.java    From RDFS with Apache License 2.0 5 votes vote down vote up
/**
 * Helper function to encode the URL of the filename of the job-history 
 * log file.
 * 
 * @param logFileName file name of the job-history file
 * @return URL encoded filename
 * @throws IOException
 */
public static String encodeJobHistoryFileName(String logFileName)
throws IOException {
  String encodedFileName = null;
  try {
    encodedFileName = URLEncoder.encode(logFileName, "UTF-8");
  } catch (UnsupportedEncodingException uee) {
    IOException ioe = new IOException();
    ioe.initCause(uee);
    ioe.setStackTrace(uee.getStackTrace());
    throw ioe;
  }
  return encodedFileName;
}
 
Example 9
Source File: BlockSender.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Converts an IOExcpetion (not subclasses) to SocketException.
 * This is typically done to indicate to upper layers that the error 
 * was a socket error rather than often more serious exceptions like 
 * disk errors.
 */
private static IOException ioeToSocketException(IOException ioe) {
  if (ioe.getClass().equals(IOException.class)) {
    // "se" could be a new class in stead of SocketException.
    IOException se = new SocketException("Original Exception : " + ioe);
    se.initCause(ioe);
    /* Change the stacktrace so that original trace is not truncated
     * when printed.*/ 
    se.setStackTrace(ioe.getStackTrace());
    return se;
  }
  // otherwise just return the same exception.
  return ioe;
}
 
Example 10
Source File: MMapDirectory.java    From lucene-solr with Apache License 2.0 5 votes vote down vote up
private IOException convertMapFailedIOException(IOException ioe, String resourceDescription, int bufSize) {
  final String originalMessage;
  final Throwable originalCause;
  if (ioe.getCause() instanceof OutOfMemoryError) {
    // nested OOM confuses users, because it's "incorrect", just print a plain message:
    originalMessage = "Map failed";
    originalCause = null;
  } else {
    originalMessage = ioe.getMessage();
    originalCause = ioe.getCause();
  }
  final String moreInfo;
  if (!Constants.JRE_IS_64BIT) {
    moreInfo = "MMapDirectory should only be used on 64bit platforms, because the address space on 32bit operating systems is too small. ";
  } else if (Constants.WINDOWS) {
    moreInfo = "Windows is unfortunately very limited on virtual address space. If your index size is several hundred Gigabytes, consider changing to Linux. ";
  } else if (Constants.LINUX) {
    moreInfo = "Please review 'ulimit -v', 'ulimit -m' (both should return 'unlimited'), and 'sysctl vm.max_map_count'. ";
  } else {
    moreInfo = "Please review 'ulimit -v', 'ulimit -m' (both should return 'unlimited'). ";
  }
  final IOException newIoe = new IOException(String.format(Locale.ENGLISH,
      "%s: %s [this may be caused by lack of enough unfragmented virtual address space "+
      "or too restrictive virtual memory limits enforced by the operating system, "+
      "preventing us to map a chunk of %d bytes. %sMore information: "+
      "http://blog.thetaphi.de/2012/07/use-lucenes-mmapdirectory-on-64bit.html]",
      originalMessage, resourceDescription, bufSize, moreInfo), originalCause);
  newIoe.setStackTrace(ioe.getStackTrace());
  return newIoe;
}
 
Example 11
Source File: MMapFile.java    From fastText4j with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private IOException convertMapFailedIOException(IOException ioe, String resourceDescription, int bufSize) {
  final String originalMessage;
  final Throwable originalCause;
  if (ioe.getCause() instanceof OutOfMemoryError) {
    // nested OOM confuses users, because it's "incorrect", just print a plain message:
    originalMessage = "Map failed";
    originalCause = null;
  } else {
    originalMessage = ioe.getMessage();
    originalCause = ioe.getCause();
  }
  final String moreInfo;
  if (!Constants.JRE_IS_64BIT) {
    moreInfo = "MMapDirectory should only be used on 64bit platforms, because the address space on 32bit operating systems is too small. ";
  } else if (Constants.WINDOWS) {
    moreInfo = "Windows is unfortunately very limited on virtual address space. If your index size is several hundred Gigabytes, consider changing to Linux. ";
  } else if (Constants.LINUX) {
    moreInfo = "Please review 'ulimit -v', 'ulimit -m' (both should return 'unlimited'), and 'sysctl vm.max_map_count'. ";
  } else {
    moreInfo = "Please review 'ulimit -v', 'ulimit -m' (both should return 'unlimited'). ";
  }
  final IOException newIoe = new IOException(String.format(Locale.ENGLISH,
    "%s: %s [this may be caused by lack of enough unfragmented virtual address space "+
      "or too restrictive virtual memory limits enforced by the operating system, "+
      "preventing us to map a chunk of %d bytes." +
    originalMessage, resourceDescription, bufSize, moreInfo), originalCause);
  newIoe.setStackTrace(ioe.getStackTrace());
  return newIoe;
}
 
Example 12
Source File: BlockSender.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Converts an IOExcpetion (not subclasses) to SocketException.
 * This is typically done to indicate to upper layers that the error 
 * was a socket error rather than often more serious exceptions like 
 * disk errors.
 */
private static IOException ioeToSocketException(IOException ioe) {
  if (ioe.getClass().equals(IOException.class)) {
    // "se" could be a new class in stead of SocketException.
    IOException se = new SocketException("Original Exception : " + ioe);
    se.initCause(ioe);
    /* Change the stacktrace so that original trace is not truncated
     * when printed.*/ 
    se.setStackTrace(ioe.getStackTrace());
    return se;
  }
  // otherwise just return the same exception.
  return ioe;
}
 
Example 13
Source File: FileNameIndexUtils.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Helper function to decode the URL of the filename of the job-history 
 * log file.
 * 
 * @param logFileName file name of the job-history file
 * @return URL decoded filename
 * @throws IOException
 */
public static String decodeJobHistoryFileName(String logFileName)
throws IOException {
  String decodedFileName = null;
  try {
    decodedFileName = URLDecoder.decode(logFileName, "UTF-8");
  } catch (UnsupportedEncodingException uee) {
    IOException ioe = new IOException();
    ioe.initCause(uee);
    ioe.setStackTrace(uee.getStackTrace());
    throw ioe;
  }
  return decodedFileName;
}
 
Example 14
Source File: BlockSender.java    From hadoop-gpu with Apache License 2.0 5 votes vote down vote up
/**
 * Converts an IOExcpetion (not subclasses) to SocketException.
 * This is typically done to indicate to upper layers that the error 
 * was a socket error rather than often more serious exceptions like 
 * disk errors.
 */
private static IOException ioeToSocketException(IOException ioe) {
  if (ioe.getClass().equals(IOException.class)) {
    // "se" could be a new class in stead of SocketException.
    IOException se = new SocketException("Original Exception : " + ioe);
    se.initCause(ioe);
    /* Change the stacktrace so that original trace is not truncated
     * when printed.*/ 
    se.setStackTrace(ioe.getStackTrace());
    return se;
  }
  // otherwise just return the same exception.
  return ioe;
}
 
Example 15
Source File: JobHistory.java    From RDFS with Apache License 2.0 5 votes vote down vote up
/**
 * Helper function to decode the URL of the filename of the job-history 
 * log file.
 * 
 * @param logFileName file name of the job-history file
 * @return URL decoded filename
 * @throws IOException
 */
public static String decodeJobHistoryFileName(String logFileName)
throws IOException {
  String decodedFileName = null;
  try {
    decodedFileName = URLDecoder.decode(logFileName, "UTF-8");
  } catch (UnsupportedEncodingException uee) {
    IOException ioe = new IOException();
    ioe.initCause(uee);
    ioe.setStackTrace(uee.getStackTrace());
    throw ioe;
  }
  return decodedFileName;
}
 
Example 16
Source File: BlockSender.java    From RDFS with Apache License 2.0 5 votes vote down vote up
/**
 * Converts an IOExcpetion (not subclasses) to SocketException.
 * This is typically done to indicate to upper layers that the error 
 * was a socket error rather than often more serious exceptions like 
 * disk errors.
 */
protected static IOException ioeToSocketException(IOException ioe) {
  if (ioe.getClass().equals(IOException.class)) {
    // "se" could be a new class in stead of SocketException.
    IOException se = new SocketException("Original Exception : " + ioe);
    se.initCause(ioe);
    /* Change the stacktrace so that original trace is not truncated
     * when printed.*/ 
    se.setStackTrace(ioe.getStackTrace());
    return se;
  }
  // otherwise just return the same exception.
  return ioe;
}
 
Example 17
Source File: UndertowServletMessages_$bundle.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public final IOException deleteFailed(final Path file) {
    final IOException result = new IOException(String.format(getLoggingLocale(), deleteFailed$str(), file));
    final StackTraceElement[] st = result.getStackTrace();
    result.setStackTrace(Arrays.copyOfRange(st, 1, st.length));
    return result;
}
 
Example 18
Source File: Native.java    From netty4.0.27Learn with Apache License 2.0 4 votes vote down vote up
private static IOException newConnectionResetException(String method, int errnoNegative) {
    IOException exception = newIOException(method, errnoNegative);
    exception.setStackTrace(EmptyArrays.EMPTY_STACK_TRACE);
    return exception;
}
 
Example 19
Source File: QueryResultsParser.java    From fosstrak-epcis with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Marshals the given QueryResults object to its XML representations and
 * serializes it to the given OutputStream. Use as follows for printing a
 * QueryResults instance to standard output:
 * 
 * <pre>
 * QueryResults results = ...
 * QueryResultsParser.queryResultsToXml(results, System.out);
 * </pre>
 * 
 * @param results
 *            The QueryResults object to marshal into XML.
 * @param out
 *            The OutputStream to which the XML representation will be
 *            written to.
 * @throws IOException
 *             If an error marshaling the QueryResults object occurred.
 */
public static void queryResultsToXml(final QueryResults results, OutputStream out) throws IOException {
    // serialize the response
    try {
        JAXBElement<QueryResults> item = factory.createQueryResults(results);
        JAXBContext context = JAXBContext.newInstance(QueryResults.class);
        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
        marshaller.marshal(item, out);
    } catch (JAXBException e) {
        IOException ioe = new IOException(e.getMessage());
        ioe.setStackTrace(e.getStackTrace());
        throw ioe;
    }
}
 
Example 20
Source File: FileUtils.java    From tectonicus with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * This function will copy files or directories from one location to
 * another. note that the source and the destination must be mutually
 * exclusive. This function can not be used to copy a directory to a sub
 * directory of itself. The function will also have problems if the
 * destination files already exist.
 * 
 * @param src
 *            -- A File object that represents the source for the copy
 * @param dest
 *            -- A File object that represnts the destination for the copy.
 * @throws IOException
 *             if unable to copy.
 */
public static void copyFiles(File src, File dest, Set<String> excludeExtensions) throws IOException
{
	// Check to ensure that the source is valid...
	if (!src.exists())
	{
		throw new IOException("copyFiles: Can not find source: " + src.getAbsolutePath() + ".");
	}
	else if (!src.canRead())
	{
		// check to ensure we have rights to the source...
		throw new IOException("copyFiles: No right to source: " + src.getAbsolutePath() + ".");
	}
	
	// is this a directory copy?
	if (src.isDirectory())
	{
		if (!dest.exists())
		{ // does the destination already exist?
			// if not we need to make it exist if possible (note this is
			// mkdirs not mkdir)
			if (!dest.mkdirs())
			{
				throw new IOException("copyFiles: Could not create direcotry: " + dest.getAbsolutePath() + ".");
			}
		}
		// get a listing of files...
		String list[] = src.list();
		// copy all the files in the list.
		for (int i = 0; i < list.length; i++)
		{
			File dest1 = new File(dest, list[i]);
			File src1 = new File(src, list[i]);
			copyFiles(src1, dest1, excludeExtensions);
		}
	}
	else
	{
		String extension = getExtension(src.getName());
		if (!excludeExtensions.contains(extension))
		{
			// This was not a directory, so lets just copy the file
			try
			{
				Files.copy(src.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
			}
			catch (IOException e)
			{
				// Error copying file...
				IOException wrapper = new IOException("copyFiles: Unable to copy file: "
														+ src.getAbsolutePath() + "to"
														+ dest.getAbsolutePath() + ".");
				wrapper.initCause(e);
				wrapper.setStackTrace(e.getStackTrace());
				throw wrapper;
			}
		}
		else
		{
			System.out.println("Skipping "+src.getAbsolutePath());
		}
	}
}