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

The following examples show how to use java.io.IOException#getStackTrace() . 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: ClientSession.java    From Open-Lowcode with Eclipse Public License 2.0 7 votes vote down vote up
/**
 * Logs and displays on status bar an error
 * 
 * @param e exceptin to tread
 */
public void treatException(Exception e) {
	if (e instanceof OLcRemoteException) {
		OLcRemoteException remoteexception = (OLcRemoteException) e;
		this.getActiveClientDisplay().updateStatusBar(
				"Server Error :" + remoteexception.getRemoteErrorCode() + " " + remoteexception.getMessage(), true);
	} else {
		this.getActiveClientDisplay().updateStatusBar("Connectionerror " + e.getMessage(), true);
	}
	printException(e);
	try {
		this.connectiontoserver.stopConnection();
	} catch (IOException e2) {
		// will not print exception in screen as first exception is likely more useful
		// for user to figure out
		logger.warning(" Error in stopping connection " + e2.getMessage());
		for (int i = 0; i < e2.getStackTrace().length; i++) {
			logger.warning(e2.getStackTrace()[i].toString());
		}
	}
}
 
Example 2
Source File: ClientSession.java    From Open-Lowcode with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Stops the current connection
 */
public void stopconnection() {

	try {
		this.connectiontoserver.stopConnection();
	} catch (IOException e) {
		int i = 0;
		logger.warning("caught IO Exception " + e.getMessage());
		boolean exit = false;
		while (!exit) {
			logger.warning(e.getStackTrace()[i].toString());
			// only show stack trace until current class to get rid of the
			// very long javafx stacktrace
			if (e.getStackTrace()[i].toString().indexOf("ClientSession") != -1)
				exit = true;
			i++;
			if (i >= e.getStackTrace().length)
				exit = true;

		}
		this.getActiveClientDisplay().updateStatusBar("Connectionerror " + e.getMessage());

		setBusinessScreenFrozen(false, connectiontoserver);
	}

}
 
Example 3
Source File: Closeables.java    From phoenix with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public StackTraceElement[] getStackTrace() {
    if (!this.hasSetStackTrace) {
        ArrayList<StackTraceElement> frames = new ArrayList<StackTraceElement>(this.exceptions.size() * 20);
        
        int exceptionNum = 0;
        for (IOException exception : this.exceptions) {
            StackTraceElement header = new StackTraceElement(MultipleCausesIOException.class.getName(), 
                    "Exception Number " + exceptionNum, 
                    "<no file>",
                    0);
            
            frames.add(header);
            for (StackTraceElement ste : exception.getStackTrace()) {
                frames.add(ste);
            }
            exceptionNum++;
        }
        
        setStackTrace(frames.toArray(new StackTraceElement[frames.size()]));
        this.hasSetStackTrace = true;
    }        
    
    return super.getStackTrace();
}
 
Example 4
Source File: Closeables.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Override
public StackTraceElement[] getStackTrace() {
    if (!this.hasSetStackTrace) {
        ArrayList<StackTraceElement> frames = new ArrayList<StackTraceElement>(this.exceptions.size() * 20);
        
        int exceptionNum = 0;
        for (IOException exception : this.exceptions) {
            StackTraceElement header = new StackTraceElement(MultipleCausesIOException.class.getName(), 
                    "Exception Number " + exceptionNum, 
                    "<no file>",
                    0);
            
            frames.add(header);
            for (StackTraceElement ste : exception.getStackTrace()) {
                frames.add(ste);
            }
            exceptionNum++;
        }
        
        setStackTrace(frames.toArray(new StackTraceElement[frames.size()]));
        this.hasSetStackTrace = true;
    }        
    
    return super.getStackTrace();
}
 
Example 5
Source File: MainController.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/report", method = RequestMethod.POST)
@ResponseBody
String getReport(HttpServletRequest request, HttpServletResponse response) {

    //Get the Logged in User
    String name = getLoggedUser();

    String email = request.getParameter("email");
    RetrieveItems ri = new RetrieveItems();
    List<WorkItem> theList = ri.getItemsDataSQLReport(name);

    WriteExcel writeExcel = new WriteExcel();
    SendMessages sm = new SendMessages();
    java.io.InputStream is = writeExcel.exportExcel(theList);

    try {
        sm.sendReport(is, email);

    }catch (IOException e) {
      e.getStackTrace();
        }
    return "Report is created";
}
 
Example 6
Source File: Handler3.java    From aws-doc-sdk-examples with Apache License 2.0 6 votes vote down vote up
@Override
public String handleRequest(String event, Context context) {
    LambdaLogger logger = context.getLogger();
    String email = event ;

    // log execution details
    logger.log("Email value " + email);

    SendMessage msg = new SendMessage();
    try {
       msg.sendMessage(email);

   } catch (IOException e) {
       e.getStackTrace();
   }

    return "";

}
 
Example 7
Source File: JwtFilter.java    From hdw-dubbo with Apache License 2.0 6 votes vote down vote up
@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    httpResponse.setContentType("application/json;charset=utf-8");
    httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
    httpResponse.setHeader("Access-Control-Allow-Origin", httpRequest.getHeader("Origin"));
    try {
        //处理登录失败的异常
        Throwable throwable = e.getCause() == null ? e : e.getCause();

        Map<String, Object> par = new HashMap<>();
        par.put("code", HttpStatus.SC_UNAUTHORIZED);
        par.put("msg", throwable.getMessage());

        httpResponse.getWriter().print(JacksonUtil.toJson(par));
    } catch (IOException e1) {
        e1.getStackTrace();
    }

    return false;
}
 
Example 8
Source File: PrintOutGenerator.java    From Open-Lowcode with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * wrapper that creates the binary file around the core generate content method
 * 
 * @param object object to process
 * @param label  label of the file
 * @return a binary file
 */
public SFile generateContent(E object, String label) {
	try {
		logger.fine("starting generating pdf document with generator " + this.getClass().toString() + " for object "
				+ object.getName() + " id =" + object.getId());
		PDFDocument document = new PDFDocument();
		generateContent(object, document);
		ByteArrayOutputStream documentinmemory = new ByteArrayOutputStream();
		logger.fine("generated document of size " + documentinmemory.size());
		document.PrintAndSave(documentinmemory);
		SFile generatedfile = new SFile(label + ".pdf", documentinmemory.toByteArray());
		return generatedfile;

	} catch (IOException e) {
		logger.severe(" ---- Original IO Exception in generating content " + e.getMessage());
		int minithreaddumpindex = (e.getStackTrace().length < 5 ? e.getStackTrace().length : 5);
		for (int i = 0; i < minithreaddumpindex; i++)
			logger.severe("       - " + e.getStackTrace()[i]);
		throw new RuntimeException("Filesystem error in generating pdfcontent " + e.getMessage());
	}
}
 
Example 9
Source File: FlatFileExtractor.java    From Open-Lowcode with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Extracts to excel a tree of objects
 * 
 * @param objecttree object trees
 * @return the binary file
 */
public SFile extractToExcel(NodeTree<E> objecttree) {
	try {
		Workbook workbook = new XSSFWorkbook();
		Sheet sheet = workbook.createSheet("Export Data");
		loadWorkbook(sheet, objecttree);
		ByteArrayOutputStream documentinmemory = new ByteArrayOutputStream();
		workbook.write(documentinmemory);
		workbook.close();
		SFile returnresult = new SFile("OpenLowcodeExport-" + sdf.format(new Date()) + ".xlsx",
				documentinmemory.toByteArray());
		return returnresult;
	} catch (IOException e) {
		String exceptionstring = "Exception in extracting objects to array " + definition.getName()
				+ ", original IOException " + e.getMessage();
		logger.severe(exceptionstring);
		for (int i = 0; i < e.getStackTrace().length; i++) {
			logger.severe("    " + e.getStackTrace()[i]);
		}
		throw new RuntimeException(exceptionstring);
	}
}
 
Example 10
Source File: FlatFileExtractor.java    From Open-Lowcode with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * 
 * @param objectarray
 * @param specificaliaslist
 * @return
 */
public SFile extractToExcel(E[] objectarray, String[] specificaliaslist) {
	try {
		Workbook workbook = new XSSFWorkbook();
		Sheet sheet = workbook.createSheet("Export Data");
		Sheet referencessheet = workbook.createSheet("Reference Values");
		loadWorkbook(sheet,referencessheet, objectarray, specificaliaslist);
		workbook.setActiveSheet(0); // setting active sheet to export data
		ByteArrayOutputStream documentinmemory = new ByteArrayOutputStream();
		workbook.write(documentinmemory);
		workbook.close();

		SFile returnresult = new SFile("OpenLowcodeExport-" + sdf.format(new Date()) + ".xlsx",
				documentinmemory.toByteArray());
		return returnresult;
	} catch (IOException e) {
		String exceptionstring = "Exception in extracting objects to array " + definition.getName()
				+ ", original IOException " + e.getMessage();
		logger.severe(exceptionstring);
		for (int i = 0; i < e.getStackTrace().length; i++) {
			logger.severe("    " + e.getStackTrace()[i]);
		}
		throw new RuntimeException(exceptionstring);
	}
}
 
Example 11
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 12
Source File: UndertowServletMessages_$bundle.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public final IOException streamIsClosed() {
    final IOException result = new IOException(String.format(getLoggingLocale(), streamIsClosed$str()));
    final StackTraceElement[] st = result.getStackTrace();
    result.setStackTrace(Arrays.copyOfRange(st, 1, st.length));
    return result;
}
 
Example 13
Source File: Utils.java    From gito-github-client with Apache License 2.0 5 votes vote down vote up
public static void openFeedback(Activity activity) {
    try {
        throw new IOException();
    } catch (IOException e) {
        ApplicationErrorReport report = new ApplicationErrorReport();
        report.packageName = report.processName = activity.getApplication()
                .getPackageName();
        report.time = System.currentTimeMillis();
        report.type = ApplicationErrorReport.TYPE_CRASH;
        report.systemApp = false;
        ApplicationErrorReport.CrashInfo crash = new ApplicationErrorReport.CrashInfo();
        crash.exceptionClassName = e.getClass().getSimpleName();
        crash.exceptionMessage = e.getMessage();
        StringWriter writer = new StringWriter();
        PrintWriter printer = new PrintWriter(writer);
        e.printStackTrace(printer);
        crash.stackTrace = writer.toString();
        StackTraceElement stack = e.getStackTrace()[0];
        crash.throwClassName = stack.getClassName();
        crash.throwFileName = stack.getFileName();
        crash.throwLineNumber = stack.getLineNumber();
        crash.throwMethodName = stack.getMethodName();
        report.crashInfo = crash;
        Intent intent = new Intent(Intent.ACTION_APP_ERROR);
        intent.putExtra(Intent.EXTRA_BUG_REPORT, report);
        activity.startActivity(intent);
    }
}
 
Example 14
Source File: InterfaceBWebsideController.java    From yawl with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Logs the failure of a client to contact the YAWL engine.
 * gives some suggestion of why?
 * @param e the thrown exception
 * @param backEndURIStr the uri of the engine
 */
public static void logContactError(IOException e, String backEndURIStr) {
    LogManager.getLogger(InterfaceBWebsideController.class).error(
            "[error] problem contacting YAWL engine at URI [" + backEndURIStr + "]");
    if (e.getStackTrace() != null) {
        LogManager.getLogger(InterfaceBWebsideController.class).error("line of code := " +
                e.getStackTrace()[0].toString());
    }
}
 
Example 15
Source File: TestRaftLogReadWrite.java    From incubator-ratis with Apache License 2.0 4 votes vote down vote up
/**
 * corrupt the padding by inserting non-zero bytes. Make sure the reader
 * throws exception.
 */
@Test
public void testReadWithCorruptPadding() throws IOException {
  final RaftStorage storage = new RaftStorage(storageDir, StartupOption.REGULAR);
  File openSegment = storage.getStorageDir().getOpenLogFile(0);

  LogEntryProto[] entries = new LogEntryProto[10];
  final SegmentedRaftLogOutputStream out = new SegmentedRaftLogOutputStream(openSegment, false,
      16 * 1024 * 1024, 4 * 1024 * 1024, ByteBuffer.allocateDirect(bufferSize));
  for (int i = 0; i < 10; i++) {
    SimpleOperation m = new SimpleOperation("m" + i);
    entries[i] = ServerProtoUtils.toLogEntryProto(m.getLogEntryContent(), 0, i);
    out.write(entries[i]);
  }
  out.flush();

  // make sure the file contains padding
  Assert.assertEquals(4 * 1024 * 1024, openSegment.length());

  try (FileOutputStream fout = new FileOutputStream(openSegment, true)) {
    ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[]{-1, 1});
    fout.getChannel()
        .write(byteBuffer, 16 * 1024 * 1024 - 10);
  }

  List<LogEntryProto> list = new ArrayList<>();
  try (SegmentedRaftLogInputStream in = new SegmentedRaftLogInputStream(openSegment, 0,
      RaftServerConstants.INVALID_LOG_INDEX, true)) {
    LogEntryProto entry;
    while ((entry = in.nextEntry()) != null) {
      list.add(entry);
    }
    Assert.fail("should fail since we corrupt the padding");
  } catch (IOException e) {
    boolean findVerifyTerminator = false;
    for (StackTraceElement s : e.getStackTrace()) {
      if (s.getMethodName().equals("verifyTerminator")) {
        findVerifyTerminator = true;
        break;
      }
    }
    Assert.assertTrue(findVerifyTerminator);
  }
  Assert.assertArrayEquals(entries,
      list.toArray(new LogEntryProto[list.size()]));
}
 
Example 16
Source File: TestRaftLogReadWrite.java    From ratis with Apache License 2.0 4 votes vote down vote up
/**
 * corrupt the padding by inserting non-zero bytes. Make sure the reader
 * throws exception.
 */
@Test
public void testReadWithCorruptPadding() throws IOException {
  final RaftStorage storage = new RaftStorage(storageDir, StartupOption.REGULAR);
  File openSegment = storage.getStorageDir().getOpenLogFile(0);

  LogEntryProto[] entries = new LogEntryProto[10];
  LogOutputStream out = new LogOutputStream(openSegment, false,
      16 * 1024 * 1024, 4 * 1024 * 1024, bufferSize);
  for (int i = 0; i < 10; i++) {
    SimpleOperation m = new SimpleOperation("m" + i);
    entries[i] = ServerProtoUtils.toLogEntryProto(m.getLogEntryContent(), 0, i);
    out.write(entries[i]);
  }
  out.flush();

  // make sure the file contains padding
  Assert.assertEquals(4 * 1024 * 1024, openSegment.length());

  try (FileOutputStream fout = new FileOutputStream(openSegment, true)) {
    ByteBuffer byteBuffer = ByteBuffer.wrap(new byte[]{-1, 1});
    fout.getChannel()
        .write(byteBuffer, 16 * 1024 * 1024 - 10);
  }

  List<LogEntryProto> list = new ArrayList<>();
  try (LogInputStream in = new LogInputStream(openSegment, 0,
      RaftServerConstants.INVALID_LOG_INDEX, true)) {
    LogEntryProto entry;
    while ((entry = in.nextEntry()) != null) {
      list.add(entry);
    }
    Assert.fail("should fail since we corrupt the padding");
  } catch (IOException e) {
    boolean findVerifyTerminator = false;
    for (StackTraceElement s : e.getStackTrace()) {
      if (s.getMethodName().equals("verifyTerminator")) {
        findVerifyTerminator = true;
        break;
      }
    }
    Assert.assertTrue(findVerifyTerminator);
  }
  Assert.assertArrayEquals(entries,
      list.toArray(new LogEntryProto[list.size()]));
}
 
Example 17
Source File: SimpleRadiusConnection.java    From Open-Lowcode with Eclipse Public License 2.0 4 votes vote down vote up
/**
 * @param userid user id for security check
 * @param otp    one time password
 * @return true if the authentication was confirmed, false else
 * @throws UnknownHostException         if the server is not known
 * @throws UnsupportedEncodingException if UTF-8 is not installed on the server
 * @throws IOException                  if anything bad happens and connection
 *                                      could not be retried
 */
public boolean checkOTP(String userid, String otp)
		throws UnknownHostException, UnsupportedEncodingException, IOException {
	RequestSummary requestsummary = generateRequestPacket(userid, otp);
	DatagramPacket reply = new DatagramPacket(new byte[MAX_PACKET_SIZE], MAX_PACKET_SIZE);

	DatagramSocket socket = new DatagramSocket();
	socket.setSoTimeout(TIMEOUT);
	int retrycount = 0;
	boolean success = false;
	while (retrycount <= RETRY & !success) {
		try {
			socket.send(requestsummary.getPayload());
			socket.receive(reply);
			success = true;
		} catch (IOException e) {
			logger.warning("Exception in communicating with Radius server "+e.getMessage());
			for (int i=0;i<e.getStackTrace().length;i++) logger.warning("   - "+e.getStackTrace()[i]);
			try {
				Thread.sleep(300);
			} catch (InterruptedException e1) {
				logger.warning("Interrupted Exception " + e1.getMessage());
			}
		}
	}
	socket.close();
	ByteArrayInputStream in = new ByteArrayInputStream(reply.getData());
	int responsetype = in.read() & 0x0ff;
	int serverid = in.read() & 0x0ff;
	int messagelength = (in.read() & 0x0ff) << 8 | (in.read() & 0x0ff);
	byte[] authenticator = new byte[16];
	byte[] attributepayload = new byte[messagelength - HEADER_LENGTH];
	in.read(authenticator);
	in.read(attributepayload);
	in.close();
	checkReplyAuthenticator(secret, responsetype, serverid, messagelength, attributepayload,
			requestsummary.getAuthenticator(), authenticator);
	if (responsetype == ACCESS_ACCEPT)
		return true;
	return false;

}