I ask an help to understand why this difference of behavior.
public class Test3 {
public static void main(String[] args) {
Double d = new Test3().findPrice$withoutFinally();
//Double d = new Test3().findPrice$withFinally();
System.out.println(d);
}
private double findPrice$withoutFinally() {
double price = -1.0;
int attempt = 0;
do {
try {
price = getPrice();
}
catch (MyException e) {
System.out.println("Caught MyException!");
}
attempt++;
} while (attempt < 3);
return price;
}
private double findPrice$withFinally() {
double price = -1.0;
int attempt = 0;
do {
boolean retry = false;
try {
price = getPrice();
}
catch (MyException e) {
System.out.println("Caught MyException!");
}
finally {
System.out.println("finally");
if (retry) {
System.out.println("retrying...");
attempt++;
} else {
break;
}
}
} while (attempt < 3);
return price;
}
private Double getPrice() throws MyException {
if (true) {
throw new RuntimeException("Testing RE");
}
return null;
}
}
I mean this, running findPrice$withoutFinally() method I got:
Exception in thread "main" java.lang.RuntimeException: Testing RE
that is the behaviour thah I expect. But running findPrice$withFinally() method I got this unexpected (for me!) behaviour:
finally
-1.0
findPrice$withFinally() should not behave as findPrice$withoutFinally() and then stop execution because of the exception?
Thanks!
finally block is executed ALWAYS - when there is an exception and when there is no exception
Related
Trying to add divide by zero exception in my calculator project through the try/catch block:
private class Calculate implements ActionListener {
public void actionPerformed(ActionEvent e) {
try {
if (operation.equals("/")) {
display.setText(Double.toString(getResult() / Double.parseDouble(display.getText())));
setResult(Double.parseDouble(display.getText()));
}
else if (operation.equals("*")) {
display.setText(Double.toString(getResult() * Double.parseDouble(display.getText())));
setResult(Double.parseDouble(display.getText()));
}
else if (operation.equals("-")) {
display.setText(Double.toString(getResult() - Double.parseDouble(display.getText())));
setResult(Double.parseDouble(display.getText()));
}
else if (operation.equals("+")) {
display.setText(Double.toString(getResult() + Double.parseDouble(display.getText())));
setResult(Double.parseDouble(display.getText()));
}
if (display.getText().endsWith(".0")) {
display.setText(display.getText().replace(".0", ""));
}
calculationMade = true;
operation = "";
}
catch (IllegalArgumentException exc) {
display.setText("You cannot divide by zero!");
}
}
}
But in this way it still writes me "Infinity" in a text field. Can anybody suggest where i'm wrong please?
When working with double, zero division returns Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY (depending on operand signs)
System.out.println(1.0d/0d);
System.out.println(-1.0d/0d);
System.out.println(1.0d/-0d);
System.out.println(-1.0d/-0d);
Only non-decimal arithmetic throws an exception on zero division. And the exception is not an IllegalArgumentException but an ArithmeticException.
I am writing a Java application which reads the data from MySQL and stores it in Cassandra as Sqoop does not support a direct import to Cassandra. I am using Producer-Consumer framework to achieve the same due to high number of records (in millions) in MySQL. But I am getting ReadTimeOut Exception (com.datastax.driver.core.exceptions.DriverException: Timeout during read). I have one Producer class which reads the data from MySQL and puts it into one queue. There is one consumer class which reads the data from that queue and pushes it to Cassndra. There is one manager class which acts as a coordination bridge between these two classes.
Producer class :-
public class MySQLPrintJobProducer implements Runnable {
private BlockingQueue<PrintJobDAO> printerJobQueue = null;
private Connection conn = null;
public MySQLPrintJobProducer(BlockingQueue<PrintJobDAO> printerJobQueue) throws MySQLClientException {
this.printerJobQueue = printerJobQueue;
connect();
}
private void connect() throws MySQLClientException {
try {
Class.forName(MySQLClientConstants.MYSQL_JDBC_DRIVER);
conn = DriverManager.getConnection("jdbc:mysql://mysqlserverhose/mysqldb?user=mysqluser&password=mysqlpasswd");
} catch (ClassNotFoundException e) {
throw new MySQLClientException(ExceptionUtils.getStackTrace(e));
} catch (SQLException e) {
throw new MySQLClientException(ExceptionUtils.getStackTrace(e));
}
}
public void run() {
ResultSet rs = null;
Statement stmt = null;
PreparedStatement pStmt = null;
try {
stmt = conn.createStatement();
// Get total number of print jobs stored.
rs = stmt.executeQuery(MySQLClientConstants.PRINT_JOB_COUNT_QUERY);
int totalPrintJobs = 0;
if(rs != null) {
while(rs.next()) {
totalPrintJobs = rs.getInt(1);
}
}
// Determine the number of iterations.
int rowOffset = 1;
int totalIteration = ((totalPrintJobs / ExportManagerConstants.DATA_TRANSFER_BATCH_SIZE) + 1);
pStmt = conn.prepareStatement(MySQLClientConstants.PRINT_JOB_FETCH_QUERY);
int totalRecordsFetched = 0;
// Iterate over to fetch Print Job Records in bathces and put it into the queue.
for(int i = 1; i <= totalIteration; i++) {
pStmt.setInt(1, rowOffset);
pStmt.setInt(2, ExportManagerConstants.DATA_TRANSFER_BATCH_SIZE);
System.out.println("In iteration : " + i + ", Row Offset : " + rowOffset);
rs = pStmt.executeQuery();
synchronized (this.printerJobQueue) {
if(this.printerJobQueue.remainingCapacity() > 0) {
while(rs.next()) {
totalRecordsFetched = rs.getRow();
printerJobQueue.offer(new PrintJobDAO(rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getDate(4),
rs.getTimestamp(5), rs.getInt(6), rs.getInt(7), rs.getInt(8), rs.getInt(9),
rs.getInt(10), rs.getFloat(11), rs.getFloat(12), rs.getInt(13), rs.getFloat(14), rs.getInt(15),
rs.getDouble(16), rs.getDouble(17), rs.getDouble(18), rs.getDouble(19), rs.getDouble(20),
rs.getFloat(21)));
this.printerJobQueue.notifyAll();
}
System.out.println("In iteration : " + i + ", Records Fetched : " + totalRecordsFetched +
", Queue Size : " + printerJobQueue.size());
rowOffset += ExportManagerConstants.DATA_TRANSFER_BATCH_SIZE;
} else {
System.out.println("Print Job Queue is full, waiting for Consumer thread to clear.");
this.printerJobQueue.wait();
}
}
}
} catch (SQLException e) {
System.err.println(ExceptionUtils.getStackTrace(e));
} catch (InterruptedException e) {
System.err.println(ExceptionUtils.getStackTrace(e));
} finally {
try {
if(null != rs) {
rs.close();
}
if(null != stmt) {
stmt.close();
}
if(null != pStmt) {
pStmt.close();
}
} catch (SQLException e) {
System.err.println(ExceptionUtils.getStackTrace(e));
}
}
ExportManager.setProducerCompleted(true);
}
}
Consumer Class :-
public class CassandraPrintJobConsumer implements Runnable {
private Cluster cluster = null;
private Session session = null;
private BlockingQueue<PrintJobDAO> printerJobQueue = null;
public CassandraPrintJobConsumer(BlockingQueue<PrintJobDAO> printerJobQueue) throws CassandraClientException {
this.printerJobQueue = printerJobQueue;
cluster = Cluster.builder().withPort(9042).addContactPoint("http://cassandrahost").build();
}
public void run() {
int printJobConsumed = 0;
int batchInsertCount = 1;
if(cluster.isClosed()) {
connect();
}
session = cluster.connect();
PreparedStatement ps = session.prepare(CassandraClientConstants.INSERT_PRINT_JOB_DATA);
BatchStatement batch = new BatchStatement();
synchronized (this.printerJobQueue) {
while(true) {
if(!this.printerJobQueue.isEmpty()) {
for(int i = 1; i <= ExportManagerConstants.DATA_TRANSFER_BATCH_SIZE; i++) {
PrintJobDAO printJob = printerJobQueue.poll();
batch.add(ps.bind(printJob.getJobID(), printJob.getUserID(), printJob.getType(), printJob.getGpDate(), printJob.getDateTimes(),
printJob.getAppName(), printJob.getPrintedPages(), printJob.getSavedPages(), printJob.getPrinterID(), printJob.getWorkstationID(),
printJob.getPrintedCost(), printJob.getSavedCost(), printJob.getSourcePrinterID(), printJob.getSourcePrinterPrintedCost(),
printJob.getJcID(), printJob.getCoverageC(), printJob.getCoverageM(), printJob.getCoverageY(), printJob.getCoverageK(),
printJob.getCoverageTotal(), printJob.getPagesAnalyzed()));
printJobConsumed++;
}
session.execute(batch);
System.out.println("After Batch - " + batchInsertCount + ", record insert count : " + printJobConsumed);
batchInsertCount++;
this.printerJobQueue.notifyAll();
} else {
System.out.println("Print Job Queue is empty, nothing to export.");
try {
this.printerJobQueue.wait();
} catch (InterruptedException e) {
System.err.println(ExceptionUtils.getStackTrace(e));
}
}
if(ExportManager.isProducerCompleted() && this.printerJobQueue.isEmpty()) {
break;
}
}
}
}
}
Manager Class :-
public class ExportManager {
private static boolean isInitalized = false;
private static boolean producerCompleted = false;
private static MySQLPrintJobProducer printJobProducer = null;
private static CassandraPrintJobConsumer printJobConsumer = null;
private static BlockingQueue<PrintJobDAO> printJobQueue = null;
public static boolean isProducerCompleted() {
return producerCompleted;
}
public static void setProducerCompleted(boolean producerCompleted) {
ExportManager.producerCompleted = producerCompleted;
}
private static void init() throws MySQLClientException, CassandraClientException {
if(!isInitalized) {
printJobQueue = new LinkedBlockingQueue<PrintJobDAO>(ExportManagerConstants.DATA_TRANSFER_BATCH_SIZE * 2);
printJobProducer = new MySQLPrintJobProducer(printJobQueue);
printJobConsumer = new CassandraPrintJobConsumer(printJobQueue);
isInitalized = true;
}
}
public static void exportPrintJobs() throws ExportException {
try {
init();
} catch (MySQLClientException e) {
throw new ExportException("Print Job Export failed.", e);
} catch (CassandraClientException e) {
throw new ExportException("Print Job Export failed.", e);
}
Thread producerThread = new Thread(printJobProducer);
Thread consumerThread = new Thread(printJobConsumer);
consumerThread.start();
producerThread.start();
}
}
TestNG class :-
public class TestExportManager {
#Test
public void testExportPrintJobs() {
try {
ExportManager.exportPrintJobs();
Thread.currentThread().join();
} catch (ExportException e) {
Assert.fail("ExportManager.exportPrintJobs() failed.", e);
} catch (InterruptedException e) {
Assert.fail("ExportManager.exportPrintJobs() failed.", e);
}
}
}
I have also made some configuration changes by following this link. Still I am getting following exception after inserting 18000 - 20000 records.
Exception in thread "Thread-2" com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: /192.168.10.80
(com.datastax.driver.core.exceptions.DriverException: Timeout during read))
at com.datastax.driver.core.exceptions.NoHostAvailableException.copy(NoHostAvailableException.java:64)
at com.datastax.driver.core.DefaultResultSetFuture.extractCauseFromExecutionException(DefaultResultSetFuture.java:256)
at com.datastax.driver.core.DefaultResultSetFuture.getUninterruptibly(DefaultResultSetFuture.java:172)
at com.datastax.driver.core.SessionManager.execute(SessionManager.java:91)
at com.incendiary.ga.client.cassandra.CassandraPrintJobConsumer.run(CassandraPrintJobConsumer.java:108)
at java.lang.Thread.run(Unknown Source)
Caused by: com.datastax.driver.core.exceptions.NoHostAvailableException: All host(s) tried for query failed (tried: /192.168.10.80 (com.datastax.drive
r.core.exceptions.DriverException: Timeout during read))
at com.datastax.driver.core.RequestHandler.sendRequest(RequestHandler.java:100)
at com.datastax.driver.core.RequestHandler$1.run(RequestHandler.java:171)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
... 1 more
I am not able to figure out the actual reason for the issue. I could not find any exception in Cassandra system log. I am using Apache Cassandra 2.0.7 and cassandra-driver-core 2.0.1.
You can increase read time out in you driver side . By using withSocket method in this you have SocketOption class using that you can read time out .By default is read time out is 10 millisecond .
I'm implementing a function that detects if there is a webcam. This piece of code works fine in windows and I had no problem with it in linux centos OS. Now I'm trying to run the same code in Ubuntu, here an exception is thrown.
Exception in thread "main" java.lang.NullPointerException
at CameraProperties.CheckForCameraPlugin.check(CheckForCameraPlugin.java:51)
at Main.Main.main(Main.java:39)
The code is given below.
public boolean check()
{
boolean b = true;
service = Executors.newFixedThreadPool(1);
task = service.submit(new InitialCameraChecker());
try
{
final String str;
// waits the 10 seconds for the Callable.call to finish.
str = task.get();
if (str.matches("nodevice"))
{
b = false;//Return false if no camera device found
}
else
{
b = true;
}
}
catch (InterruptedException | ExecutionException ex)
{
msgbox.showJoptionPane(15);
}
service.shutdownNow();
return b;
}
The callable class is given below
class InitialCameraChecker implements Callable<String>
{
private List<Integer> devices = new ArrayList<Integer>();
private final static String VERSION_ID = "1.0.0";
private String res;
//Checking for the Camera
public String call()
{
try
{
loadWebcam();
discoverDevices();
if (devices.isEmpty())
{
res = "nodevice";//No we cam device found
}
else
{
res = "founddevice";//Found Web Cam Device
}
}
catch (Exception ex)
{
System.out.println("Exception_logout" + ex.toString());
}
return res;
}
//Discovering the camera device
private void discoverDevices()
{
for (int i = 0; i < 10; i++)
{
CvCapture cap = null;
try
{
cap = cvCreateCameraCapture(i);
int res = cvGrabFrame(cap);
if (res > 0)
{
devices.add(i);
break;
}
}
catch (Exception e)
{
System.out.println("Exception in camaracheck Thread1");
}
finally
{
if (cap != null)
{
try
{
cvReleaseCapture(cap.pointerByReference());
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
}
//Loading the dlls for starting the camera
private void loadWebcam()
{
String tmpDir = System.getProperty("java.io.tmpdir");
File faPath = new File(tmpDir + File.separator + "WebcamApplet_" + VERSION_ID.replaceAll("\\.", "-"));
System.setProperty("jna.library.path", faPath.getAbsolutePath());
}
}
Please tell me what is the problem. This works fine in windows.
This is my first post here. I am trying to create a singly link list. I am using AtEnd and AtStart methods to insert values at the end or in the beginning of the list and using display method to print all the values. The insertion methods seems to be working fine (at least I think so) but whenever I call display method it shows only the first value and then there is a null pointer exception. For example when I run this code I see only 9 and then there is the NPE despite the fact that I have put a check on the display method for "not null".
class node {
private int data;
private node next;
node() {
}
node(int data) {
this.data = data;
this.next = null;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data=data;
}
public node getNext() {
return next;
}
public void setNext(node next) {
this.next = next;
}
}
public class list extends node {
node head;
list() {
}
public void AtStart(int val) {
node n = new node(val);
if (head == null) {
head=n;
} else {
n.setNext(head);
int temp = head.getData();
head.setData(val);
n.setData(temp);
//n = head;
}
}
public void AtEnd(int val) {
if (head == null) {
node n = new node(val);
head = n;
} else {
node t = head;
for(; t.getNext() != null; ) {
if(t.getNext() == null) {
t.setNext(new node (val));
}
t = t.getNext();
}
}
}
public void display() {
node t = head;
for(; t.getNext() == null;) {
if (t !=null) {
System.out.println(t.getData());
t = t.getNext();
}
}
}
}
public static void main(String args[]) {
list l = new list();
l.AtStart(16);
l.AtEnd(6);
l.AtEnd(36);
l.AtStart(9);
l.AtEnd(22);
l.display();
}
i dont get what your AtStart function does, it should be much simpler:
public void AtStart(int val){
if(head==null){
head=n;
}
else{
head.setnext(head);
head.setData(val);
}
}
I have added a document listener to a JTextPane. I want to know what text has been added or removed so I can take action if certain key words are entered. The insert part works just fine, but I do not know how to detect what text was deleted.
The insert works because the text is there and I can select it, but the delete has already removed the text so I get bad location exceptions sometimes.
I want to make reserved words that are not inside quotes bold so I need to know what has been removed, removing even one character (like a quote) could have a huge impact.
My code follows:
#Override
public void insertUpdate(DocumentEvent e)
{
Document doc = e.getDocument();
String i = "";
try
{
i = doc.getText(e.getOffset(), e.getLength());
}
catch(BadLocationException e1)
{
e1.printStackTrace();
}
System.out.println("INSERT:" + e + ":" + i);
}
#Override
public void removeUpdate(DocumentEvent e)
{
Document doc = e.getDocument();
String i = "";
try
{
i = doc.getText(e.getOffset(), e.getLength());
}
catch(BadLocationException e1)
{
e1.printStackTrace();
}
System.out.println("REMOVE:" + e + ":" + i);
}
This is strange that there is no simple way to get this information.
I've looked at the source code of Swing libraries for this. Of course - there is this information in DocumentEvent, which is of class AbstractDocument$DefaultDocumentEvent, which contains protected Vector<UndoableEdit> edits, which contains one element of type GapContent$RemoveUndo, which contains protected String string that is used only in this class (no other "package" classes get this) and this RemoveUndo class have no getter for this field.
Even toString didn't show it (because RemoveUndo hasn't overrided toString method):
[javax.swing.text.GapContent$RemoveUndo#6303ddfd hasBeenDone: true alive: true]
This is so strange for me that I belive that there is some other easy way to get the removed string and that I just don't know how to accomplish it.
One thing you can do is the most obvious:
final JTextArea textArea = new JTextArea();
textArea.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
previousText = textArea.getText();
}
});
textArea.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
if(previousText != null) {
String removedStr = previousText.substring(e.getOffset(), e.getOffset() + e.getLength());
System.out.println(removedStr);
}
}
#Override
public void insertUpdate(DocumentEvent e) {
}
#Override
public void changedUpdate(DocumentEvent e) {
}
});
where previousText is an instance variable.
or (the most nasty ever):
textArea.getDocument().addDocumentListener(new DocumentListener() {
#Override
public void removeUpdate(DocumentEvent e) {
String removedString = getRemovedString(e);
System.out.println(removedString);
}
#Override
public void insertUpdate(DocumentEvent e) {
}
#Override
public void changedUpdate(DocumentEvent e) {
}
});
plus this method:
public static String getRemovedString(DocumentEvent e) {
try {
Field editsField = null;
Field[] fields = CompoundEdit.class.getDeclaredFields();
for(Field f : fields) {
if(f.getName().equals("edits")) {
editsField = f;
break;
}
}
editsField.setAccessible(true);
List edits = (List) editsField.get(e);
if(edits.size() != 1) {
return null;
}
Class<?> removeUndo = null;
for(Class<?> c : GapContent.class.getDeclaredClasses()) {
if(c.getSimpleName().equals("RemoveUndo")) {
removeUndo = c;
break;
}
}
Object removeUndoInstance = edits.get(0);
fields = removeUndo.getDeclaredFields();
Field stringField = null;
for(Field f : fields) {
if(f.getName().equals("string")) {
stringField = f;
break;
}
}
stringField.setAccessible(true);
return (String) stringField.get(removeUndoInstance);
}
catch(SecurityException e1) {
e1.printStackTrace();
}
catch(IllegalArgumentException e1) {
e1.printStackTrace();
}
catch(IllegalAccessException e1) {
e1.printStackTrace();
}
return null;
}
I had the same problem than you. And what Xeon explained help me a lot too. But after, i found a way to do that. In my case, i created a custom StyledDocument class that extends DefaultStyledDocument:
public class CustomStyledDocument extends DefaultStyledDocument
{
public CustomStyledDocument () {
super();
}
#Override
public void insertString(int offset, String string, AttributeSet as) throws BadLocationException {
super.insertString(offset, string, as);
}
#Override
public void remove(int offset, int i1) throws BadLocationException {
String previousText = getText(offset, i1);
super.remove(offset, i1);
}
}
So if you call getText method before you call super.remove(...), you will get the previous text.