|
Hello there. I am trying to implement Observer Pattern . I get notified, successfully, whenever a thread completes. I can start the same thread again when I get notified (through TaskListener I have implemented). But how do I start it again if there was some exception? Example
static MyWork objMyWork = null;
static Thread objThread = null;
public static void main(String[] args) throws
{
TaskListener listener = new TaskListener()
{
@Override
public void threadComplete()
{
try
{
objMyWork = new MyWork();
objMyWork.SetData1(int data);
objMyWork.SetData2(String data);
objMyWork.addListener(this);
objThread = new Thread(objMyWork);
objThread.start();
objThread.join();
}
catch(Exception ex)
{
}
}
}
objMyWork = new MyWork();
objMyWork.SetData1(int data);
objMyWork.SetData2(String data);
objMyWork.addListener(listener);
objThread = new Thread(objMyWork);
objThread.start();
objThread.join();
}
1- What changes do I make in MyWork so that control always comes back in the
catch section of TaskListener::threadComplete() whenever there was exception?
2- Once control is there, how do I start this thread again (I dont want to nest another try-catch block and then another in the nested one and then another .... and so on).
Thanks for anything you share
|
|
|
|
|
|
Hi expert,
I have the following method but no matter what I did to the line pstmt.executeUpdate or change it to if (pstmt.executeUpdate() != -1), it just gave me the error - No value specified for parameter 2..., earlier it was No value specified for parameter 1....
Hope someone can tell me where I had go wrong in my code. Tks.
public static int writeTutorId() throws Exception {
openConnection();
String qry = INSERT_QRY;
int tutor_id = 0;
PreparedStatement pstmt = connection.prepareStatement(qry, new String[] { "tutor_id" });
pstmt.setInt(1, tutor_id);
if (pstmt.executeUpdate() != -1) {
ResultSet rs = pstmt.getGeneratedKeys();
if (null != rs && rs.next()) {
tutor_id = rs.getInt(1);
}
pstmt.close();
connection.close();
}
return tutor_id;
}
|
|
|
|
|
Your query - which you haven't shown - has at least two parameters.
You are only passing one parameter.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hi Richard,
Here's the query :-
private final static String INSERT_QRY = "INSERT INTO project.tutor"
+ "(tutorName, tutorIC, tutorEmail, tutorAddress1, tutorAddress2, zipcode, tutorContactNo, tutorAge, tutorGender, tutorQualification, tutorQualificationDetail) values"
+ "(?,?,?,?,?,?,?,?,?,?,?);";
I did not put in the tutorId cos it is supposed to be generated out by the method I have written.
Initially, I did not include the pstmt.setInt(1, tutor_id) but when I googled, it said I must add it in. Futhermore, I have another insert method whereby all the infor like tutorName etc are inserted.
This method is to solely get the generatedKeys out...
What went wrong ?
modified 3-Jul-17 11:40am.
|
|
|
|
|
Your query has 11 parameters.
You are passing 1 parameter.
Have a guess what the problem might be.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Yes. It is easy to guess the problem.
I was thinking that (if) there is only a way I do not have to repeat the code with the ps.set blah blah blah for all the rest of the parameters and just on the Id alone. There is a lot of repeating code. Alas, I do not know how to overcome something like this.
The problem now is that I got a java.lang.NullPointerException on the line - Integer parameter - Age.
tutor m = new tutor();
int tutor_id = m.getTutor_id();
PreparedStatement pstmt = connection.prepareStatement(qry, new String[] { "tutor_id" });
pstmt.setInt(1, m.getTutor_id());
pstmt.setString(2, m.getName());
pstmt.setString(3, m.getNRIC());
pstmt.setString(4, m.getEmail());
pstmt.setString(5, m.getAddress2());
pstmt.setString(6, m.getZipcode());
pstmt.setString(7, m.getContactNo());
pstmt.setInt(8, m.getAge());
What causes the problem cos I have double checked I have indeed entered the value into the form....
I don't think I can find out anything like this via googling except asking in forum....
|
|
|
|
|
karengsh wrote: don't think I can find out anything like this via googling except asking in forum. You could try using your debugger and learning how to diagnose simple problems for yourself. Which field on that line is null and how did it become so after all the previous statements worked correctly?
|
|
|
|
|
Ok. Tks for the tip. I think now I got a bigger problem which I think it is due to my code and there is no answer at all. I really need help for this one.
Cos now the error is com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException : Column 'tutorIC' cannot be null
After thinking of a long time, I think it should be because of the 2nd prepared Statement there is no controller so it becomes null.
I hope to know for my case, how to avoid the above since I have to repeat the similar prepared Statement in my generating keys Ids ?
public void insertTutor(tutor m) throws MyDataException {
openConnection();
try {
connection.setAutoCommit(false);
} catch (SQLException e1) {
e1.printStackTrace();
}
String qry = INSERT_QRY;
try (
PreparedStatement ps = connection.prepareStatement(qry)) {
;
ps.setString(1, m.getName());
ps.setString(2, m.getNRIC());
ps.setString(3, m.getEmail());
ps.setString(4, m.getAddress1());
ps.setString(5, m.getAddress2());
ps.setString(6, m.getZipcode());
ps.setString(7, m.getContactNo());
ps.setInt(8, m.getAge());
ps.setString(9, m.getGender());
blah blah blah
ps.executeUpdate();
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
throw new MyDataException("DB Error");
} finally {
if (ps != null) {
closeConnection();
}
}
}
public static int writeTutorId() throws Exception {
openConnection();
String qry = INSERT_QRY;
tutor m = new tutor();
int tutor_id = m.getTutor_id();
PreparedStatement pstmt = connection.prepareStatement(qry, new String[] { "tutor_id" });
pstmt.setInt(1, m.getTutor_id());
pstmt.setString(2, m.getName());
pstmt.setString(3, m.getNRIC());
pstmt.setString(4, m.getEmail());
pstmt.setString(5, m.getAddress2());
pstmt.setString(6, m.getZipcode());
pstmt.setString(7, m.getContactNo());
pstmt.setInt(8, m.getAge());
pstmt.setString(9, m.getGender());
blah blah blah
if (pstmt.executeUpdate() != -1) {
ResultSet rs = pstmt.getGeneratedKeys();
if (null != rs && rs.next()) {
tutor_id = rs.getInt(1);
}
pstmt.close();
connection.close();
}
return tutor_id;
}
<pre lang="java">
My 2nd method in which it returns the generated key ids will be used in another insertion for my 3rd table and so I would still need this method to be in.
My controller :
<pre lang="java">
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
Statement stmt = null;
tutor m4 = new tutor();
manager mgr = new manager();
try {
String name = request.getParameter("name");
if (name != null){
m4.setName(name);
}
String NRIC = request.getParameter("nric");
if (NRIC != null){
m4.setNRIC(NRIC);
}
String email = request.getParameter("email");
if (email != null){
m4.setEmail(email);
String address1 = request.getParameter("address1");
if (address1 != null){
m4.setAddress1(address1);
}
String address2 = request.getParameter("address2");
if (address2 != null){
m4.setAddress2(address2);
}
String zipcode = request.getParameter("zipcode");
if (zipcode != null){
m4.setZipcode(zipcode);
}
String contactNo = request.getParameter("contactNo");
if (contactNo != null){
m4.setContactNo(contactNo);
}
int age = Integer.parseInt(request.getParameter("age"));
if (age != 0){
m4.setAge(age);
}
String gender = request.getParameter("Gender");
if (gender != null){
m4.setGender(gender);
}
so on and so for...
}
mgr.insertTutor(m4);
} }catch (Exception ex) {
ex.printStackTrace();
}
Subject s = new Subject();
try{
String[] sub = request.getParameterValues("subject");
List<String> subjName = Arrays.asList(sub);
mgr.insertSubject(subjName);
}catch (Exception ex) {
ex.printStackTrace();
}
try{
tutor_id = tutorDAOImpl.writeTutorId();
subj_id = subjectDAOImpl.Idlist();
tutor_SubjectDAOImpl.insertTutor_Subject(tutor_id, subj_id);
}
catch (Exception ex) {
ex.printStackTrace();
}
}
}
|
|
|
|
|
I'm new to Java.
In writeTutorID you create a new tutor and then update the dataset with that variable (m). Does the class give default values? If not you are passing a null string.
|
|
|
|
|
I have to do the same thing over and over again with firefox so I'd like to find a way through java.
How do I do that? I heard in the past about selenium. Is there a full explanation of how to use it? Please help
|
|
|
|
|
Member 13290460 wrote: Please help With what? We have no idea what you are trying to do. If you think Java and Selenium are the tools you need then go to their websites and study the documentation.
|
|
|
|
|
Hello there. I am trying to send images (byte[] data) to web browser using java. I am doing this in a while(true) loop. My ClientThread sends one image only. After that, it starts producing this exception. Here is what I have tried so far
Overview
1- MainThread starts ServerThread
2- ServerThread start ClientThread
3- ClientThread has a loop. In this loop, I read next image and pass it to MovieWriter (which writes it to DataOutputStream of clientSocket) with a delay of 50ms
class ClientThread extends Thread
{
@Overrie
public void run()
{
OutputStream outStream = clientSocket.getOutputStream();
DataOutputStream dataOutStream = new DataOutputStream(outStream);
MovieWriter mv = new MovieWriter(dataOutStream);
mv.WriterHttpHeader();
while(true)
{
Thread.sleep(50);
ByteArrayOutputStream image = ReadImage.GetNext();
mv.WriteNextImage(image.toByteArray());
}
}
}
class MovieWriter
{
public MovieWriter(DataOutputStream)
{
}
public void WriterHttpHeader()
{
String header = "HTTP/1.1 200 OK \r\n Content-Type: multipart/x-mixed-replace; boundary=--boundary";
dataOutputStream.write(GetBytes(header));
}
public void WriteNextImage(byte[] data)
{
try
{
String response = "Content-Type: image/jpg \r\n" + "Content-Length: " + String.ValueOf(data.length);
dataOutputStream.write(GetBytes(response));
dataOutputStream.write(data);
} catch(Exception ex) {
ex.printStackTrace();
}
}
}
Again, when the while loop in ClientThread runs, MovieWriter sends one image only. After that, it raises the said exception. What am I doing wrong? Thanks for anything you share
NOTE: I cut this code short for better understanding. If you need more code, I can provide
|
|
|
|
|
It seems to me that your logic is the wrong way round. A web browser is a client application that requests information form a web server. So your 'client' should be a server, which sends images based on requests from the browser, rather than trying to push them to a browser that is not expecting them.
|
|
|
|
|
Richard MacCutchan wrote: So your 'client' should be a server .....
- I have a 'ServerThread' (one and only one server thread)
- The piece of code that serves images, upon request, is known as 'ClientThread'
- This 'ServerThread' can start N number of 'ClientThread', against N number of requests from web browser.
And YES. Good naming conventions help understand better. 'ClientThread' could better be named as 'RequestThread'.
But the problem still remains. My browser display ONE picture, sent from my server. After that ONE picture, it starts throwing said exception.
|
|
|
|
|
Well, as I suggested above, that is because the browser is not expecting it. Your server thread should only be sending an image when the browser sends it a request.
|
|
|
|
|
Richard MacCutchan wrote: Well, as I suggested above, that is because the browser is not expecting it.
Perhaps I am having tough time understanding you. Please bear with me. To the best of my knowledge, I am sending only the images and nothing else. I also tried removing the header just before I transmit the image, even that does not help.
|
|
|
|
|
At the risk of repeatedly repeating myself ...
You cannot send unsolicited messages to a web browser, they do not work that way.
|
|
|
|
|
THIS IS MY CODE BUT IT IS NOT GIVING THE RIGHT OUTPUT
package main;
import java.util.*;
public class Year_Conversion {
public static void main(String[] args) {
String s1;
System.out.println("Input string in the following format dd-mm-yy:");
Scanner sc=new Scanner(System.in) ;
s1=sc.next();
convertDate(s1);
}
public static String convertDate(String s1)
{
String ans = null;
String[] parts=s1.split("-");
int d=Integer.parseInt(parts[0]);
int m=Integer.parseInt(parts[1]);
int y=Integer.parseInt(parts[2]);
if(d<10)
{
ans=ans+"0"+d;
}
else
{
ans=ans+d;
}
if(m<10)
{
ans=ans+"0"+m;
}
else
{
ans=ans+m;
}
ans=ans+"19"+y;
return ans;
}
}
|
|
|
|
|
What output do you get?
Rather than convert to integer to determine if you need to prefix a zero why not use strings length, if it is 1 you need a zero...
|
|
|
|
|
1) DON'T SHOUT! Typing in all capitals on the internet is considered shouting. Typing your entire message in capitals is rather rude.
2) If you want someone to help you get the "right output", then you need to tell us what the "right output" is.
Show us several examples of what you type in, what the expected output is, and what the actual output is.
Without that information, we can't help you.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Member 13276968 wrote: String ans = null;
Should be empty string not null
Also noting that the code you have is not printing the result.
|
|
|
|
|
Dear experts,
I understand now that I have to get Generated Key in order to obtain my auto-incremental Id from a table.
However, after getting the generated key and set it to the model. I am stuck as to how to give it to my third table.
public void insertTutor(tutor m) throws MyDataException {
openConnection();
try {
connection.setAutoCommit(false);
} catch (SQLException e1) {
e1.printStackTrace();
}
String qry = INSERT_QRY;
try (
PreparedStatement ps = connection.prepareStatement(qry)) { ;
ps.setString(1, m.getName());
ps.setString(2, m.getNRIC());
ps.executeUpdate();
ResultSet tableKeys = ps.getGeneratedKeys();
tableKeys.next();
int tutor_id = tableKeys.getInt(1);
m.setTutor_id(tutor_id);
System.out.println(tutor_id);
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
....
}}}}
And I do the same for my 2nd table.
My third table I need to make use of the Ids from the first and 2nd table.
So, do I create an insert like this ?
String qry = "INSERT INTO project.tutor_subject" + "(tutor_id, sub_id) values"
+ "(?,?)";
And how do I go about doing the third DAOImpl and the controller to get the Ids to go into the third table ?
I have read that JPA and using MyBatis is better for many to many table insertion.
Should I do it via JPA and MyBatis ?
|
|
|
|
|
karengsh,
It looks like you have most of your framework built out already, but JPA or MyBatis could also be used if you wish.
The advantage of using JPA is it handles almost all of the boilerplate database CRUD operations, but there is a learning curve to using it.
If you wish to continue on your current path, don't worry about a DAO for the tutor_subject join table, just put the logic in a manager class for the tutor entity.
Given the pattern I see in your code, you would simply use the getId() methods on the objects passed to your insertTutor and insertSubject methods
tutor tmpTutor = new tutor("Fred Flintstone","NRIC value");
subject tmpSubject = new subject("Java");
boolean success = false;
try {
insertTutor(tmpTutor);
insertSubject(tmpSubject);
success = true;
}
catch (MyDataException mde){
}
if (success){
try {
associateTutorToSubject(tmpTutor.getId(), tmpSubject.getId());
}
catch (MyDataException mde2){
}
}
|
|
|
|
|
Hi Mike,
My problem is how do I make the tmpTutor.getId() and tmpSubject.getId() mehtod static so that I could implement in my controller ?
Cos right now, I can only insert the tutorDAOImpl when I do the preparedStatement for tutor.
When I want to do the associateTutorToSubject, I can't do it the way like yo said cos tutorDAOImpl and SubjectDAOImpl are both separate classes. And so there is no way for the controller to read the getId from the tutorDAOImpl etc.
|
|
|
|
|