Java Code never entering try block in try-catch - java

I am currently creating a project to write a client and service that give information from a music database.
I have created a MusicService.java file which is deploying fine. I am not sure if the code is right however. I then needed to create a client. When I run the client I keep getting Error Faults thrown from my try catch in my MusicService.java class saying("Unable to find composer") or ("unable to find disc") From doing some basic debugging, I know that the try methods in getByComposer and getByDisc are never being entered and going straight to catch.
I also know in my client.java method that the try is being entered due to my print statement being returned in console. However the code is never executing and going straight to the catch exception and I can't work out why.
I know there is a mistake somewhere perhaps I am not calling but I have spent hours on this and can't seem to find the problem.
I will leave the 2 methods underneath, if anyone could help it would be greatly appreciated.
MusicService.java method
package music;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class MusicService extends MusicServiceSkeleton {
private final static String databaseHost = "mysql0.cs.stir.ac.uk";
private final static String databaseName = "CSCU9YW";
private final static String databasePassword = "rtk1";
private final static String databaseUser = "rtk1";
private final static String discTable = "music";
//define methods to implement the WSDL opeartions getByComposer() and getByDisc()
public music.MultipleTracks getByComposer(music.Composer composer)throws ErrorFault
{
try {
TrackDetail[]info=getByField("composer",composer.getComposer());
MultipleTracks multiTrack = new MultipleTracks();
TrackDetails multiRetrieve = new TrackDetails();
multiRetrieve.setTracklist(info);
multiTrack.setMultipleTracks(multiRetrieve);
return multiTrack;
}
catch(Exception e)
{
throw(new ErrorFault("Unable to find composer"));
}
}
public music.MultipleTracks getByDisc(music.Disc disc)throws ErrorFault
{
try {
System.out.println("hello in getbbydisc");
TrackDetail[]info=getByField("disc",disc.getDisc());
MultipleTracks multiTrack = new MultipleTracks();
TrackDetails multiRetrieve = new TrackDetails();
multiRetrieve.setTracklist(info);
multiTrack.setMultipleTracks(multiRetrieve);
return multiTrack;
}
catch(Exception e)
{
throw(new ErrorFault("Unable to find disc"));
}
}
private TrackDetail[] getByField(String field, String value) throws ErrorFault {
try {
if (value.length() == 0)
throw (new Exception(field + " is empty"));
Class.forName("com.mysql.jdbc.Driver").newInstance();
String databaseDesignation = "jdbc:mysql://" + databaseHost + "/" + databaseName + "?user=" + databaseUser
+ "&password=" + databasePassword;
Connection connection = DriverManager.getConnection(databaseDesignation);
Statement statement = connection.createStatement();
String query = "SELECT disc, track, composer, work, title " + "FROM " + discTable + " " + "WHERE " + field
+ " LIKE '%" + value + "%'";
ResultSet result = statement.executeQuery(query);
result.last();
int resultCount = result.getRow();
if (resultCount == 0)
throw (new Exception(field + " '" + value + "' not found"));
TrackDetail[] trackDetails = new TrackDetail[resultCount];
result.beforeFirst();
int resultIndex = 0;
while (result.next()) {
TrackDetail receiver = detailsReceived(result);
trackDetails[resultIndex++]= receiver;
}
connection.close();
return (trackDetails);
} catch (Exception exception) {
String errorMessage = "database access error - " + exception.getMessage();
throw (new ErrorFault(errorMessage, exception));
}
}
private TrackDetail detailsReceived(ResultSet current)throws SQLException
{
TrackDetail details = new TrackDetail();
details.setDiscNumber(current.getString(1));
details.setTrackNumber(current.getString(2));
details.setComposerName(current.getString(3));
details.setWorkName(current.getString(4));
details.setTitleName(current.getString(5));
return details;
}
}
The Client.java method
package music;
import music.MusicServiceStub.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Client extends JFrame implements ActionListener {
private final static int contentInset = 5;
private final static int trackColumns = 130;
private final static int trackRows = 20;
private final static int gridLeft = GridBagConstraints.WEST;
private final static String programTitle = "Music Album";
private GridBagConstraints contentConstraints = new GridBagConstraints();
private GridBagLayout contentLayout = new GridBagLayout();
private Container contentPane = getContentPane();
private JButton discButton = new JButton("Check");
private JLabel discLabel = new JLabel("Disc Number:");
private JTextField discText = new JTextField(5);
private JButton nameButton = new JButton("Check");
private JLabel nameLabel = new JLabel("Composer/Artiste Name:");
private JTextField nameText = new JTextField(16);
private Font trackFont = new Font(Font.MONOSPACED, Font.PLAIN, 12);
private JLabel trackLabel = new JLabel("Tracks:");
private JTextArea trackArea = new JTextArea(trackRows, trackColumns);
private JScrollPane trackScroller = new JScrollPane(trackArea);
private MultipleTracks tracks;
// define here private variable for your Client Stub
public Client() throws Exception {
contentPane.setLayout(contentLayout);
addComponent(0, 0, gridLeft, nameLabel);
addComponent(1, 0, gridLeft, nameText);
addComponent(2, 0, gridLeft, nameButton);
addComponent(0, 1, gridLeft, discLabel);
addComponent(1, 1, gridLeft, discText);
addComponent(2, 1, gridLeft, discButton);
addComponent(0, 2, gridLeft, trackLabel);
addComponent(0, 3, gridLeft, trackScroller);
nameButton.addActionListener(this);
discButton.addActionListener(this);
trackArea.setFont(trackFont);
trackArea.setEditable(false);
// instantiate your Client Stub and assign to private class variable declared above
}
public static void main(String[] args) throws Exception {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int screenWidth = screenSize.width;
int screenHeight = screenSize.height;
Client window = new Client();
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setTitle(programTitle);
window.pack();
int windowWidth = window.getWidth();
int windowHeight = window.getHeight();
int windowX = (screenWidth - windowWidth) / 2;
int windowY = (screenHeight - windowHeight) / 2;
window.setLocation(windowX, windowY);
window.setVisible(true);
}
private void addComponent(int x, int y, int position, JComponent component) {
Insets contentInsets = new Insets(contentInset, contentInset, contentInset, contentInset);
contentConstraints.gridx = x;
contentConstraints.gridy = y;
contentConstraints.anchor = position;
contentConstraints.insets = contentInsets;
if (component == trackArea || component == trackLabel)
contentConstraints.gridwidth = GridBagConstraints.REMAINDER;
contentLayout.setConstraints(component, contentConstraints);
contentPane.add(component);
}
public void actionPerformed(ActionEvent event) {
String trackRows = "";
TrackDetail[] tracks;
try {
//System.out.println("Hello");
if (event.getSource() == nameButton)
tracks = getField("composer", nameText.getText());
else if (event.getSource() == discButton)
tracks = getField("disc", discText.getText());
else
return;
trackRows += String.format("%4s %5s %-32s %-40s %-40s\n", "Disc", "Track", "Composer/Artist", "Work", "Title");
for (int i = 0; i < tracks.length; i++) {
TrackDetail trackDetail = tracks[i];
trackRows += extractMusicData(trackDetail);
// extract the data for a track and append to trackRows variable
}
} catch (Exception exception) {
String error = exception.getMessage();
if (error == null) error = exception.toString();
error = "could not get track - " + error;
trackRows += error;
}
trackArea.setText(trackRows);
}
private String extractMusicData(TrackDetail track )
{
String albumName= track.getWorkName();
String composer = track.getComposerName();
String title= track.getTitleName();
String trackNo= track.getTrackNumber().toString();
String discNo= track.getDiscNumber().toString();
String extractMusicTracks= String.format("%4s %5s %-32s %-40s %-40s\n", discNo, trackNo, composer, albumName, title);
return extractMusicTracks;
}
private TrackDetail[] getField(String field, String value) throws Exception {
// define behaviour for method getField() to call the web service methods and receive the results
try
{
TrackDetail[] multiTrack;
MusicServiceStub stub=new MusicServiceStub();
if(field.equals("disc"))
{
MusicServiceStub.Disc requestDisc = new MusicServiceStub.Disc();
requestDisc.setDisc(value);
MusicServiceStub.MultipleTracks message= stub.getByDisc(requestDisc);
multiTrack= extractedTracks(message);
return multiTrack;
} else if(field.equals("composer"));
{
MusicServiceStub.Composer requestComposer = new MusicServiceStub.Composer();
requestComposer.setComposer(value);
MusicServiceStub.MultipleTracks message= stub.getByComposer(requestComposer);
multiTrack= extractedTracks(message);
return multiTrack;
}
} catch(Exception e)
{
System.out.println(e);
}
return null;
}
private TrackDetail[] extractedTracks(MultipleTracks tracks)
{
TrackDetails track= tracks.getMultipleTracks();
TrackDetail[] multiTrack= track.getTracklist();
return multiTrack;
}
}

Your error handling is way off:
Idiomatic java dictates that exceptions end in the word 'Exception'. Don't use the name 'ErrorFault'. Aside from being non-idiomatic, that's a tautology.
When rethrowing, pass the cause, and lose the parens: throw new ErrorFault("Unable to find composer", e); except don't name it ErrorFault. Now you can check what is causing java to jump to the catch block.
Note that java does not randomly jump to catch blocks for no reason. Something in that try block is throwing, and you're hiding the cause by throwing something else without passing the original along as cause.
Don't ever catch exceptions and just do 'System.out.println(e)' - code is going to continue afterwards, even though clearly the process is now in an invalid state. If you have no idea how to handle an exception, your best bet is to just add a 'throws' clause on your method to throw it onwards. If that is just not an option and you also don't feel like wrapping it in an appropriate exception either, the absolute fallback is throw new RuntimeException(e), not e.printStackTrace(), or even worse, the information-obliterating System.out.println(e); - update your IDE's templates!
Once you apply the above advice, the problem should be clear. If it is not, at least now you get a stack trace that includes a lot more detail; post that as a question here (or update your question) with that info and perhaps someone can help you figure out what's going on.

Related

How to save an instance of a JavaFX javafx.scene.shape.Path to a file

I am trying to save a javafx.scene.shape.Path to a file (at least its elements) however since Path is non-serializable and its PathElement as well it has proven very difficult.
Could someone inform me of a way to either convert the object to a String (preferred), JSON or something else?
Here are all the ways I have tried saving the object:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import javafx.scene.shape.Path;
import javafx.scene.shape.Polygon;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.Shape;
class Test {
public static void main(String[] args) {
GsonBuilder builder = new GsonBuilder();
Path path;
Gson gson = builder.create();
{
Rectangle rectangle = new Rectangle(100, 100);
Polygon polygon = new Polygon(0, 0, 50, 50, 0, 50);
path = (Path) Shape.subtract(rectangle, polygon);
}
try {
String completePathObject = gson.toJson(path);
System.out.println(completePathObject);
} catch (IllegalArgumentException e) {
e.printStackTrace();
// java.lang.IllegalArgumentException: class com.sun.javafx.util.WeakReferenceQueue$ListEntry declares multiple JSON fields named next
}
try {
String pathObjectElements = gson.toJson(path.getElements());
System.out.println(pathObjectElements);
} catch (IllegalArgumentException e) {
e.printStackTrace();
// java.lang.IllegalArgumentException: class com.sun.javafx.util.WeakReferenceQueue$ListEntry declares multiple JSON fields named next
}
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("test.set"))) {
objectOutputStream.writeObject(path);
} catch (IOException e) {
e.printStackTrace();
// java.io.NotSerializableException: javafx.scene.shape.Path
}
try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("test.set"))) {
objectOutputStream.writeObject(path.getElements());
} catch (IOException e) {
e.printStackTrace();
// java.io.NotSerializableException: javafx.scene.shape.Path$2
}
}
}
Nodes contain a lot of properties you'd need to convert to a form that can be written to a file.
Since your last attempt indicates you'll be satisfied with writing the path elements to the file, you could convert the PathElements to parts of a SVG path and also implement logic for parsing the elements PathElements from a svg path string.
The following doesn't accept all possible SVG paths and may accept some invalid paths:
public class SVGConverter {
private enum PathElementType {
ARC('a', ArcTo.class, ArcTo::new,
ArcTo::radiusXProperty,
ArcTo::radiusYProperty,
ArcTo::XAxisRotationProperty,
ArcTo::largeArcFlagProperty,
ArcTo::sweepFlagProperty,
ArcTo::xProperty,
ArcTo::yProperty),
CLOSE_PATH('z', ClosePath.class, ClosePath::new),
CUBIC_CURVE('c', CubicCurveTo.class, CubicCurveTo::new,
CubicCurveTo::controlX1Property,
CubicCurveTo::controlY1Property,
CubicCurveTo::controlX2Property,
CubicCurveTo::controlY2Property,
CubicCurveTo::xProperty,
CubicCurveTo::yProperty),
H_LINE_TO('h', HLineTo.class, HLineTo::new,
HLineTo::xProperty),
LINE_TO('l', LineTo.class, LineTo::new,
LineTo::xProperty, LineTo::yProperty),
MOVE_TO('m', MoveTo.class, MoveTo::new,
MoveTo::xProperty, MoveTo::yProperty),
QUAD_CURVE_TO('q', QuadCurveTo.class, QuadCurveTo::new,
QuadCurveTo::controlXProperty, QuadCurveTo::controlYProperty,
QuadCurveTo::xProperty, QuadCurveTo::yProperty),
V_LINE_TO('v', VLineTo.class, VLineTo::new,
VLineTo::yProperty);
private final char letter;
private final String typeName;
private final Supplier<? extends PathElement> factory;
private final Function[] propertyGetters;
<T extends PathElement> PathElementType(char letter, Class<T> type, Supplier<T> factory, Function<T, ? extends Property<?>>... propertyGetters) {
this.letter = letter;
this.typeName = type.getName();
this.factory = factory;
this.propertyGetters = propertyGetters;
}
}
private final Map<String, PathElementType> ELEMENT_TYPES_BY_TYPE;
private final Map<Character, PathElementType> ELEMENT_TYPES_BY_LETTER;
public SVGConverter() {
ELEMENT_TYPES_BY_LETTER = new HashMap<>();
ELEMENT_TYPES_BY_TYPE = new HashMap<>();
for (PathElementType et : PathElementType.values()) {
ELEMENT_TYPES_BY_LETTER.put(et.letter, et);
ELEMENT_TYPES_BY_TYPE.put(et.typeName, et);
}
}
public String pathToSvg(Path path) {
StringBuilder sb = new StringBuilder();
for (PathElement element : path.getElements()) {
PathElementType elementType = ELEMENT_TYPES_BY_TYPE.get(element.getClass().getName());
if (elementType == null) {
throw new IllegalArgumentException("Unknown PathElement type: " + element.getClass().getName());
}
// specify path element type
char c = elementType.letter;
if (element.isAbsolute()) {
c = Character.toUpperCase(c);
}
sb.append(c);
// write property values
for (Function f : elementType.propertyGetters) {
Property property = (Property) f.apply(element);
sb.append((property instanceof BooleanProperty)
// special treatment for booleans to convert true/false to 1/0
? (((BooleanProperty) property).get() ? "1" : "0")
: property.getValue().toString()).append(' ');
}
}
// trim, if necessary
int lastIndex = sb.length() - 1;
if (lastIndex >= 0 && sb.charAt(lastIndex) == ' ') {
sb.deleteCharAt(lastIndex);
}
return sb.toString();
}
private static final String NUMBER_PATTERN_STRING = "[+-]?\\d*\\.\\d*(?:[eE][+-]?\\d+)?";
private static final Pattern NUMBER_PATTERN = Pattern.compile("(?<![\\d.+-])(" + NUMBER_PATTERN_STRING + ')');
private static final Pattern SVG_PATTERN = Pattern.compile("([aAcChHlLvmMqQVzZ])((?:\\s*" + NUMBER_PATTERN_STRING + "(?:[\\s,]+" + NUMBER_PATTERN_STRING + ")*)?)");
// parses doubles from number sequence
private static double[] getNumberMatches(Matcher m, int count) {
double[] result = new double[count];
for (int i = 0; i < count; i++) {
if (!m.find()) {
throw new IllegalArgumentException("missing numbers");
}
result[i] = Double.parseDouble(m.group(1));
}
if (m.find()) {
throw new IllegalArgumentException("too many numbers");
}
return result;
}
public Path svgToPath(String svg) {
Path path = new Path();
Matcher matcher = SVG_PATTERN.matcher(svg);
while (matcher.find()) {
// find out path element type
char c = matcher.group(1).charAt(0);
PathElementType elementType = ELEMENT_TYPES_BY_LETTER.get(Character.toLowerCase(c));
if (elementType == null) {
throw new IllegalArgumentException("Unknown path type " + c);
}
PathElement element = (PathElement) elementType.factory.get();
element.setAbsolute(Character.isUpperCase(c));
// retrieve parameters
if (elementType.propertyGetters.length > 0) {
Matcher numberMatcher = NUMBER_PATTERN.matcher(matcher.group(2));
double[] numbers = getNumberMatches(numberMatcher, elementType.propertyGetters.length);
for (int i = 0; i < elementType.propertyGetters.length; i++) {
Property property = (Property) elementType.propertyGetters[i].apply(element);
property.setValue((property instanceof BooleanProperty)
? (numbers[i] == 1) // convert to boolean (true iff 1.0)
: numbers[i]);
}
}
path.getElements().add(element);
}
return path;
}
}
Note: This does not restore any kind of bindings that may have existed before converting to string of course.

Drag and Drop between tables in horizontalLayout doesn't work

I've got 3 Tables in Vaadin:
My Problem now is that Drag & Drop doesn't work. My Code is the following one:
#Theme("valo")
#SpringView(name = TaskboardView.VIEW_NAME)
public class TaskboardView extends VerticalLayout implements View {
private enum TableType {
DONE, PROGRESS, OPEN;
}
private static final long serialVersionUID = 1L;
private final Logger logger = LoggerFactory.getLogger(TaskboardView.class);
public static final String VIEW_NAME = "taskboard";
// Components:
private SprintController sprintController = new SprintController();
private TaskController taskController = new TaskController();
private Sprint sprint;
private Set<Task> allTasks;
private List<Task> openTasks = new ArrayList<Task>();
private List<Task> inProgressTasks = new ArrayList<Task>();
private List<Task> doneTasks = new ArrayList<Task>();
// UI Components:
private Table openTable = new Table("Open Tasks:");
private int openTableId = 1;
private Table inProgressTable = new Table("Tasks in Progress");
private int inProgressTableId = 1;
private Table doneTable = new Table("Done Tasks");
private int doneTableId = 1;
private TextField sprintName = new TextField();
private OpenTableDropHandler openTableDropHandler = new OpenTableDropHandler();
private InProgressTableDropHandler inProgressTableDropHandler = new InProgressTableDropHandler();
DoneTableHandler doneTableHandler = new DoneTableHandler();
#PostConstruct
void init() {
logger.info("Initializing Taskboard View...");
try {
this.sprint = sprintController.getActiveSprint();
this.allTasks = sprintController.getTasksInSprint(this.sprint.getId().intValue());
sortSprintTasks(this.allTasks);
this.sprintName.setNullRepresentation("-- No active Sprint found --");
this.sprintName.setValue(this.sprint.getSprintName());
this.sprintName.setWidth("800px");
this.sprintName.setReadOnly(true);
this.sprintName.addStyleName("align-center"); // sets Allignment of
// the textfield!!!
} catch (NoActiveSprintReceivedException | NoSprintsExistException | IOException e) {
logger.error("Something went wrong initializing active Sprint. The taskboard can't be displayed.", e);
Notification.show("No Active Sprint found!", Notification.Type.ERROR_MESSAGE);
e.printStackTrace();
return;
} catch (TaskCanNotBeAllocatedException e) {
logger.error("Task of sprint couldn't be allocated to an status.", e);
Notification.show("Error! \n \n Task of sprint couldn't be allocated to an status.",
Notification.Type.ERROR_MESSAGE);
e.printStackTrace();
return;
}
// Layout for Sprint Name:
VerticalLayout headLayout = new VerticalLayout();
headLayout.setSpacing(true);
headLayout.setSizeFull();
;
headLayout.setMargin(true);
headLayout.addComponent(this.sprintName);
headLayout.setComponentAlignment(this.sprintName, Alignment.MIDDLE_CENTER);
setSizeFull();
setSpacing(true);
setMargin(true);
// Layout:
VerticalLayout verticalLayout = new VerticalLayout();
verticalLayout.setSpacing(true);
// Layout for Board:
HorizontalLayout taskBoardLayout = new HorizontalLayout();
taskBoardLayout.setSizeUndefined();
taskBoardLayout.setSpacing(true);
taskBoardLayout.setMargin(true);
// Adding to HorizontalLayout(TaskBoadLayout)
try {
initTable(this.openTable, TableType.OPEN);
initTable(this.inProgressTable, TableType.PROGRESS);
initTable(this.doneTable, TableType.DONE);
} catch (IOException e) {
logger.error("Something went wrong initizalizing Tables.");
Notification.show("Error! \n \n Couldn't initialize tables.", Notification.Type.ERROR_MESSAGE);
return;
}
taskBoardLayout.addComponent(openTable);
taskBoardLayout.addComponent(inProgressTable);
taskBoardLayout.addComponent(doneTable);
// Adding to VerticalLayout (MainLayout)
verticalLayout.addComponent(headLayout);
verticalLayout.addComponent(taskBoardLayout);
verticalLayout.setComponentAlignment(taskBoardLayout, Alignment.MIDDLE_CENTER);
addComponent(verticalLayout);
}
/**
* Sorts the tasks of the sprint to the required lists like open, in
* Progress, done.
*
* #param tasks
* #throws TaskCanNotBeAllocatedException
*/
private void sortSprintTasks(Set<Task> tasks) throws TaskCanNotBeAllocatedException {
logger.info("sortSprintTask(Set<Task>tasks): Sorting Tasks to the required lists...");
for (Task t : tasks) {
logger.info("Checking Sprint Status of Task >>>> " + t.getHeadLine() + " <<<<");
logger.info("Status: " + t.getStatus());
if (t.getStatus().equals(WorkflowStatusConfigurator.open)) {
this.openTasks.add(t);
} else if (t.getStatus().equals(WorkflowStatusConfigurator.inProgress)) {
this.inProgressTasks.add(t);
} else if (t.getStatus().equals(WorkflowStatusConfigurator.done)) {
this.doneTasks.add(t);
} else {
throw new TaskCanNotBeAllocatedException(
"Task can't be allocated to a sprint status: " + WorkflowStatusConfigurator.open + ", "
+ WorkflowStatusConfigurator.inProgress + ", " + WorkflowStatusConfigurator.done + ".");
}
}
}
#Override
public void enter(ViewChangeEvent event) {
// TODO Auto-generated method stub
}
/**
* Creates the tables depending on the type parameter
*
* #param table
* #param type
* #throws IOException
* #throws ClientProtocolException
*/
private void initTable(Table table, TableType type) throws ClientProtocolException, IOException {
table.setSelectable(true);
table.setImmediate(true);
table.setDragMode(TableDragMode.ROW);
table.addContainerProperty("ID", Long.class, null);
table.setColumnWidth("ID", 50);
table.addContainerProperty("Headline", String.class, null);
table.setColumnWidth("Headline", 300);
table.addContainerProperty("Task-Type", String.class, null);
table.setColumnWidth("Task-Type", 120);
table.addContainerProperty("Assignee", String.class, null);
table.setColumnWidth("Assignee", 100);
if (type.equals(TableType.OPEN) && this.openTasks.size() > 0) {
logger.info("Loading values of Open Tasks Table...");
table.setDropHandler(this.openTableDropHandler);
for (Task t : this.openTasks) {
String assignee = this.taskController.getAssigneeInTask(t.getId().intValue()).getUserName();
table.addItem(new Object[] { t.getId(), t.getHeadLine(), t.getTaskType(), assignee }, this.openTableId);
this.openTableId++;
}
return;
}
if (type.equals(TableType.PROGRESS) && this.inProgressTasks.size() > 0) {
logger.info("Loading values of Progress Tasks Table...");
table.setDropHandler(this.inProgressTableDropHandler);
for (Task t : this.inProgressTasks) {
String assignee = this.taskController.getAssigneeInTask(t.getId().intValue()).getUserName();
table.addItem(new Object[] { t.getId(), t.getHeadLine(), t.getTaskType(), assignee }, this.inProgressTableId);
this.inProgressTableId++;
}
return;
}
if (type.equals(TableType.DONE) && this.doneTasks.size() > 0) {
logger.info("Loading values of Done Tasks Table...");
table.setDropHandler(this.doneTableHandler);
for (Task t : this.doneTasks) {
String assignee = this.taskController.getAssigneeInTask(t.getId().intValue()).getUserName();
table.addItem(new Object[] { t.getId(), t.getHeadLine(), t.getTaskType(), assignee }, this.doneTableId);
this.doneTableId++;
}
return;
}
}
private int giveEncreasedAvailableTableId(TableType tableType) {
if(tableType.equals(TableType.OPEN)){
this.openTableId++;
return this.openTableId;
}else if(tableType.equals(TableType.PROGRESS)){
this.inProgressTableId++;
return this.inProgressTableId;
}else if(tableType.equals(TableType.DONE)){
this.doneTableId++;
return this.doneTableId;
}else{
return -1;
}
}
private class OpenTableDropHandler implements DropHandler{
private static final long serialVersionUID = 1L;
private final Logger logger = LoggerFactory.getLogger(OpenTableDropHandler.class);
#Override
public void drop(DragAndDropEvent event) {
// Wrapper for the object that is dragged
logger.info("Received Drag and Drop Event from OpenTable...");
DataBoundTransferable t = (DataBoundTransferable) event.getTransferable();
AbstractSelectTargetDetails dropData = ((AbstractSelectTargetDetails) event.getTargetDetails());
Object itemId = t.getItemId();
Long id = (Long) t.getSourceContainer().getItem(itemId).getItemProperty("ID").getValue();
try {
Task taskToAdd = taskController.getById(id.intValue());
String author = taskController.getAuthorInTask(taskToAdd.getId().intValue()).getUserName();
if ( t.getSourceComponent() != openTable && dropData.getTarget().equals(inProgressTable)) {
logger.info("Preparing Task Update to InProgress...");
openTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(),
taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.OPEN));
openTasks.add(taskToAdd);
inProgressTable.removeItem(itemId);
inProgressTasks.remove(taskToAdd);
}else if(t.getSourceComponent() != openTable && dropData.getTarget().equals(doneTable)){
logger.info("Preparing Task Update to Done...");
openTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(),
taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.OPEN));
openTasks.add(taskToAdd);
doneTable.removeItem(itemId);
doneTasks.remove(taskToAdd);
}else{
logger.info("Do nothing...");
return;
}
taskToAdd.setStatus(WorkflowStatusConfigurator.open);
logger.info("Sending updates of taskboard to webservice...");
HttpResponse response = taskController.put(taskToAdd, taskToAdd.getId().intValue());
MainView.navigator.navigateTo(TaskboardView.VIEW_NAME);
// HttpResponse authorResponse = taskController.setAuthorInTask(taskToAdd.getAuthor().getId().intValue(),
// taskToAdd.getId().intValue());
// HttpResponse assigneeResponse = taskController.setAssigneeInTask(taskToAdd.getAssignee().getId().intValue(),
// taskToAdd.getId().intValue());
} catch (ClientProtocolException e) {
logger.warn("Something went wrong during Drag and Drop Process", e.getCause());
} catch (IOException e) {
logger.warn("Something went wrong during Drag and Drop Process", e.getCause());
}
}
#Override
public AcceptCriterion getAcceptCriterion() {
return AcceptAll.get();
}
}
private class InProgressTableDropHandler implements DropHandler{
private static final long serialVersionUID = 1L;
private final Logger logger = LoggerFactory.getLogger(InProgressTableDropHandler.class);
#Override
public void drop(DragAndDropEvent event) {
// Wrapper for the object that is dragged
logger.info("Received Drag and Drop Event from In Progress Table.");
DataBoundTransferable t = (DataBoundTransferable) event.getTransferable();
AbstractSelectTargetDetails dropData = ((AbstractSelectTargetDetails) event.getTargetDetails());
Object itemId = t.getItemId();
Long id = (Long) t.getSourceContainer().getItem(itemId).getItemProperty("ID").getValue();
try {
Task taskToAdd = taskController.getById(id.intValue());
String author = taskController.getAuthorInTask(taskToAdd.getId().intValue()).getUserName();
if (t.getSourceComponent() != inProgressTable && dropData.getTarget().equals(doneTable) ){
inProgressTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(),
taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.PROGRESS));
doneTable.removeItem(itemId);
inProgressTasks.add(taskToAdd);
doneTasks.remove(taskToAdd);
}else if(t.getSourceComponent() != inProgressTable && dropData.getTarget().equals(openTable)){
inProgressTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(),
taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.PROGRESS));
openTable.removeItem(itemId);
inProgressTasks.add(taskToAdd);
openTasks.remove(taskToAdd);
}else{
return;
}
logger.info("Sending updates of taskboard to webservice...");
taskToAdd.setStatus(WorkflowStatusConfigurator.inProgress);
HttpResponse response = taskController.put(taskToAdd, taskToAdd.getId().intValue());
MainView.navigator.navigateTo(TaskboardView.VIEW_NAME);
}catch (ClientProtocolException e) {
logger.warn("Something went wrong during Drag and Drop Process", e.getCause());
} catch (IOException e) {
logger.warn("Something went wrong during Drag and Drop Process", e.getCause());
}
}
#Override
public AcceptCriterion getAcceptCriterion() {
return AcceptAll.get();
}
}
private class DoneTableHandler implements DropHandler{
private static final long serialVersionUID = 1L;
private final Logger logger = LoggerFactory.getLogger(DoneTableHandler.class);
#Override
public void drop(DragAndDropEvent event) {
logger.info("Received Drag and Drop Event from In Done Table.");
DataBoundTransferable t = (DataBoundTransferable) event.getTransferable();
AbstractSelectTargetDetails dropData = ((AbstractSelectTargetDetails) event.getTargetDetails());
Object itemId = t.getItemId();
Long id = (Long) t.getSourceContainer().getItem(itemId).getItemProperty("ID").getValue();
try {
Task taskToAdd = taskController.getById(id.intValue());
String author = taskController.getAuthorInTask(taskToAdd.getId().intValue()).getUserName();
if (t.getSourceComponent() != doneTable && dropData.getTarget().equals(inProgressTable) ){
doneTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(),
taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.DONE));
inProgressTable.removeItem(itemId);
doneTasks.add(taskToAdd);
inProgressTasks.remove(taskToAdd);
}else if(t.getSourceComponent() != doneTable && dropData.getTarget().equals(openTable)){
doneTable.addItem(new Object[] { taskToAdd.getId(), taskToAdd.getHeadLine(),
taskToAdd.getTaskType(), author, taskToAdd.getStatus() }, giveEncreasedAvailableTableId(TableType.DONE));
openTable.removeItem(itemId);
doneTasks.add(taskToAdd);
openTasks.remove(taskToAdd);
}else{
return;
}
logger.info("Sending updates of taskboard to webservice...");
taskToAdd.setStatus(WorkflowStatusConfigurator.done);
HttpResponse response = taskController.put(taskToAdd, taskToAdd.getId().intValue());
MainView.navigator.navigateTo(TaskboardView.VIEW_NAME);
}catch (ClientProtocolException e) {
logger.warn("Something went wrong during Drag and Drop Process", e.getCause());
} catch (IOException e) {
logger.warn("Something went wrong during Drag and Drop Process", e.getCause());
}
}
#Override
public AcceptCriterion getAcceptCriterion() {
return AcceptAll.get();
}
}
}
Has anyone any idea or at least a clue why this doesn't work? I wrote a code following the same pattern or way and it worked fine. The only difference is that there I don't use Horizontal Layout. And now the in Progress and Done Table don't react to draggin a row on them.
Off-topic: why do you have #Theme("valo") on your view? As far as I know that's used with the UI class...
On-topic:
As I was saying in my comment I don't think it's related to HorizontalLayout. Either you may have misunderstood the drag source and drop target concepts or it simply slipped in the code.
As it's also described in the docs the dragging starts from a source, and the event of dropping the data on the target is handled by a DropHandler.
If you take a look at your sources, DoneTableHandler for example, you can see
if (t.getSourceComponent() != doneTable && dropData.getTarget().equals(inProgressTable) ){
...
}else if(t.getSourceComponent() != doneTable && dropData.getTarget().equals(openTable)){
...
}else{
return;
}
Since you're listening for drops on your doneTable it will be the target and sources can only be the openTable or inProgressTable, not the other way around. I have a hunch that if you're going to add a log line in the else branch you'll see it on each drag & drop.
Below you can see a working sample in Vaadin 7.7.3 with a HorizontalLayout and 3 tables, similar to yours. It's quick and dirty so there's room for improvement (suggestions are welcome) but (eg: position of dropped items), it supports multirow drag and also the AcceptCriterion filters drops from the source table or any other component than the expected ones:
public class DragAndDropTables extends HorizontalLayout {
public DragAndDropTables() {
// leave some space between the tables
setSpacing(true);
// tables
Table toDoTable = createTable("To do");
Table inProgressTable = createTable("In progress");
Table doneTable = createTable("Done");
// drop handlers which allow only drops from expected sources
configureDragAndDrop(toDoTable, inProgressTable, doneTable);
configureDragAndDrop(inProgressTable, toDoTable, doneTable);
configureDragAndDrop(doneTable, toDoTable, inProgressTable);
// some table to make sure AcceptCriterion allows drops only from expected sources
Table tableNotAcceptableForDrops = createTable("Drops from here will not be accepted");
configureDragAndDrop(tableNotAcceptableForDrops);
tableNotAcceptableForDrops.addItem(new Task(100, "Not droppable task"));
// add some dummy data
for (int i = 0; i < 10; i++) {
toDoTable.addItem(new Task(i, "Task " + i));
}
// add the tables to the UI
addComponent(toDoTable);
addComponent(inProgressTable);
addComponent(doneTable);
addComponent(tableNotAcceptableForDrops);
}
private Table createTable(String caption) {
// basic table setup
Table table = new Table(caption);
BeanItemContainer<Task> itemContainer = new BeanItemContainer<>(Task.class);
table.setContainerDataSource(itemContainer);
table.setMultiSelect(true);
table.setSelectable(true);
table.setPageLength(10);
return table;
}
private void configureDragAndDrop(Table table, Table... acceptedSources) {
// drag & drop configuration
table.setDragMode(Table.TableDragMode.MULTIROW);
table.setDropHandler(new DropHandler() {
#Override
public void drop(DragAndDropEvent event) {
// where the items are dragged from
Table source = (Table) event.getTransferable().getSourceComponent();
// where the items are dragged to
Table target = (Table) event.getTargetDetails().getTarget();
// unique collection of dragged tasks
HashSet<Task> draggedTasks = new HashSet<>();
// https://vaadin.com/api/com/vaadin/ui/Table.TableDragMode.html
// even in MULTIROW drag mode, the event contains only the row on which the drag started
draggedTasks.add((Task) event.getTransferable().getData("itemId"));
// we'll get the rest, if any, from the source table selection value
draggedTasks.addAll((Collection<Task>) source.getValue());
// remove items from source table
draggedTasks.forEach(((Table) source)::removeItem);
// add items to destination table
target.addItems(draggedTasks);
}
#Override
public AcceptCriterion getAcceptCriterion() {
// accept drops only from specified tables, and prevent drops from the source table
return new SourceIs(acceptedSources);
}
});
}
// basic bean for easy binding
public static class Task {
private String name;
private int id;
public Task(int id, String name) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
}
Result:

Getting the output from a arraylist

Im fairly new to java and ive been doing som searching for an answer to my problem but i just cant seem to get the output from the arraylist.
I get a red mark under Ordtildikt String arrayoutput = kontrollObjekt.Ordtildikt;saying it cannot be resolved or is not a field. The program is supposed to get userinput and create an arraylist from the input
Interface class
import javax.swing.JOptionPane;
public class Grensesnitt {
public static void main(String[] args) {
Grensesnitt Grensesnitt = new Grensesnitt();
Grensesnitt.meny();
}
Kontroll kontrollObjekt = new Kontroll();
private final String[] ALTERNATIVER = {"Registrere ord","Skriv dikt","Avslutt"};
private final int REG = 0;
private final int SKRIV = 1;
public void meny() {
boolean fortsett = true;
while(fortsett) {
int valg = JOptionPane.showOptionDialog(
null,
"Gjør et valg:",
"Prosjektmeny",
JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE,
null,
ALTERNATIVER,
ALTERNATIVER[0]);
switch(valg) {
case REG: regNy();
break;
case SKRIV: regDikt();
break;
default: fortsett = false;
}
}
}
int i = 0;
public void regNy() {
while(i<=16)
{
String Ord = JOptionPane.showInputDialog("Skriv or til diktet: ");
kontrollObjekt.regNy(Ord);
//String Diktord = JOptionPane.showInputDialog("Skriv ord til diktet: ");
//kontrollObjekt.regNy(Diktord);
i = i + 1;
}
}
public void regDikt() {
String arrayoutput = kontrollObjekt.Ordtildikt;
JOptionPane.showMessageDialog(null, arrayoutput);
}
//JOptionPane.showMessageDialog(null, kontrollObjekt.Diktord);
}
Controll Class
import java.util.ArrayList;
public class Kontroll {
public ArrayList<String> Diktord = new ArrayList<String>();
public void regNy(String Ord) {
Diktord.add(Ord);
Diktord.add("\n");
}
public String Ordtildikt(String Ord) {
return Ord=Diktord.toString();
}
}
This is a method, not a variable.
kontrollObjekt.Ordtildikt;
You are trying to call this?
public String Ordtildikt(String Ord) {
return Ord=Diktord.toString();
}
1) Make it return Diktord.toString();
2) Get rid of String Ord unless you are going to use that parameter
3) Actually call the method, e.g. Put some parenthesis.
String arrayoutput = kontrollObjekt.Ordtildikt();
Also, I think this should be the correct regNy method unless you want to falsely report that the list is twice its size.
public void regNy(String Ord) {
Diktord.add(Ord + "\n");
}

getting a worklist and saving it to a file

I'm trying to retrieve the work list from the pacs server and saving it to a file "worklist.properties". I'm working on this code:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import org.dcm4che2.data.BasicDicomObject;
import org.dcm4che2.data.DicomElement;
import org.dcm4che2.data.DicomObject;
import org.dcm4che2.data.SpecificCharacterSet;
import org.dcm4che2.data.Tag;
import org.dcm4che2.data.UID;
import org.dcm4che2.net.Association;
import org.dcm4che2.net.CommandUtils;
import org.dcm4che2.net.Device;
import org.dcm4che2.net.DimseRSP;
import org.dcm4che2.net.NetworkApplicationEntity;
import org.dcm4che2.net.NetworkConnection;
import org.dcm4che2.net.NewThreadExecutor;
import org.dcm4che2.net.NoPresentationContextException;
import org.dcm4che2.net.TransferCapability;
public class TestGetMwl {
/**
* #param args
*/
public static void main(String[] args/*,String aet, String host, Integer port*/) {
new TestGetMwl(/*aet,host,port*/);
}
private static final int[] RETURN_KEYS = {
Tag.AccessionNumber,
Tag.ReferringPhysicianName,
Tag.PatientName,
Tag.PatientID,
Tag.PatientBirthDate,
Tag.PatientSex,
Tag.PatientWeight,
Tag.MedicalAlerts,
Tag.Allergies,
Tag.PregnancyStatus,
Tag.StudyInstanceUID,
Tag.RequestingPhysician,
Tag.RequestingService,
Tag.RequestedProcedureDescription,
Tag.AdmissionID,
Tag.SpecialNeeds,
Tag.CurrentPatientLocation,
Tag.PatientState,
Tag.RequestedProcedureID,
Tag.RequestedProcedurePriority,
Tag.PatientTransportArrangements,
Tag.PlacerOrderNumberImagingServiceRequest,
Tag.FillerOrderNumberImagingServiceRequest,
Tag.ConfidentialityConstraintOnPatientDataDescription,
};
private static final int[] SPS_RETURN_KEYS = {
Tag.Modality,
Tag.RequestedContrastAgent,
Tag.ScheduledStationAETitle,
Tag.ScheduledProcedureStepStartDate,
Tag.ScheduledProcedureStepStartTime,
Tag.ScheduledPerformingPhysicianName,
Tag.ScheduledProcedureStepDescription,
Tag.ScheduledProcedureStepID,
Tag.ScheduledStationName,
Tag.ScheduledProcedureStepLocation,
Tag.PreMedication,
Tag.ScheduledProcedureStepStatus
};
private static final String[] LE_TS = {
UID.ExplicitVRLittleEndian,
UID.ImplicitVRLittleEndian };
private static final byte[] EXT_NEG_INFO_FUZZY_MATCHING = { 1, 1, 1 };
private Device device;
private final NetworkApplicationEntity remoteAE = new NetworkApplicationEntity();
private final NetworkConnection remoteConn = new NetworkConnection();
private final NetworkApplicationEntity ae = new NetworkApplicationEntity();
private final NetworkConnection conn = new NetworkConnection();
private final DicomObject keys = new BasicDicomObject();
private final DicomObject spsKeys = new BasicDicomObject();
private Association assoc;
private int priority = 0;
private int cancelAfter = Integer.MAX_VALUE;//ÐœÐ°ÐºÑ ÐºÐ¾Ð»Ð¸Ñ‡ÐµÑтво Ñтрок
private boolean fuzzySemanticPersonNameMatching;
public TestGetMwl(/*String aet, String host, Integer port*/) {
String name = "DCMMWL";
device = new Device(name);
NewThreadExecutor executor = new NewThreadExecutor(name);
remoteAE.setInstalled(true);
remoteAE.setAssociationAcceptor(true);
remoteAE.setNetworkConnection(new NetworkConnection[] { remoteConn });
device.setNetworkApplicationEntity(ae);
device.setNetworkConnection(conn);
ae.setNetworkConnection(conn);
ae.setAssociationInitiator(true);
ae.setAETitle(name);
for (int i = 0; i < RETURN_KEYS.length; i++) {
keys.putNull(RETURN_KEYS[i], null);
}
keys.putNestedDicomObject(Tag.RequestedProcedureCodeSequence,
new BasicDicomObject());
keys.putNestedDicomObject(Tag.ScheduledProcedureStepSequence, spsKeys);
for (int i = 0; i < SPS_RETURN_KEYS.length; i++) {
spsKeys.putNull(SPS_RETURN_KEYS[i], null);
}
spsKeys.putNestedDicomObject(Tag.ScheduledProtocolCodeSequence,
new BasicDicomObject());
/////////
// remoteAE.setAETitle(aet);
// remoteConn.setHostname(host);
// remoteConn.setPort(port);
remoteAE.setAETitle("DCM4CHEE");
remoteConn.setHostname("localhost");
remoteConn.setPort(11112);
// addSpsMatchingKey(Tag.Modality, "CR");
//addSpsMatchingKey(Tag.Modality, "CR");
// addSpsMatchingKey(Tag.ScheduledProcedureStepStartDate,"20131030");
// addSpsMatchingKey(Tag.ScheduledProcedureStepStartTime,"11111");
setTransferSyntax(LE_TS);
long t1 = System.currentTimeMillis();
try {
assoc = ae.connect(remoteAE, executor);
} catch (Exception e) {
System.err.println("ERROR: Failed to establish association:");
e.printStackTrace(System.err);
System.exit(2);
}
long t2 = System.currentTimeMillis();
System.out.println("Connected to " + remoteAE + " in "
+ ((t2 - t1) / 1000F) + "s");
try {
List<DicomObject> result = query();
long t3 = System.currentTimeMillis();
System.out.println("Received " + result.size()
+ " matching entries in " + ((t3 - t2) / 1000F) + "s");
for(DicomObject dcm : result) {
// DicomElement pn = dcm.get(Tag.PatientName);
Properties worklist = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("C:\\properties\\worklist.properties");
// set the properties value
worklist.setProperty("1",dcm.getString(Tag.PatientName));
worklist.setProperty("2",dcm.getString(Tag.PatientName));
// save properties to project root folder
worklist.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("!!! PatientName="+dcm.getString(Tag.PatientName));
// }
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
assoc.release(true);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Released connection to " + remoteAE);
}
public void setTransferSyntax(String[] ts) {
TransferCapability tc = new TransferCapability(
UID.ModalityWorklistInformationModelFIND, ts,
TransferCapability.SCU);
if (fuzzySemanticPersonNameMatching)
tc.setExtInfo(EXT_NEG_INFO_FUZZY_MATCHING);
ae.setTransferCapability(new TransferCapability[]{tc});
}
public void addSpsMatchingKey(int tag, String value) {
spsKeys.putString(tag, null, value);
}
public List<DicomObject> query() throws IOException, InterruptedException {
TransferCapability tc = assoc.getTransferCapabilityAsSCU(
UID.ModalityWorklistInformationModelFIND);
if (tc == null) {
throw new NoPresentationContextException(
"Modality Worklist not supported by "
+ remoteAE.getAETitle());
}
//System.out.println("Send Query Request:");
//System.out.println(keys.toString());
DimseRSP rsp = assoc.cfind(UID.ModalityWorklistInformationModelFIND,
priority, keys, tc.getTransferSyntax()[0], cancelAfter);
List<DicomObject> result = new ArrayList<DicomObject>();
while (rsp.next()) {
DicomObject cmd = rsp.getCommand();
if (CommandUtils.isPending(cmd)) {
DicomObject data = rsp.getDataset();
result.add(data);
//System.out.println("\nReceived Query Response #"
// + result.size() + ":");
//System.out.println(data.toString());
}
}
return result;
}
}
when my worklist containes just one element it works perfectly. But, when the worklist containes more than one element, I get as a result just the last element saved in the worklist file.
please any idea how to fix that?
I thinks your code has got following problems:
Firstly,
output = new FileOutputStream("C:\\properties\\worklist.properties");
is inside for loop
for(DicomObject dcm : result) {
-> the worklist.properties file will be overwritten again and again.
The second,
worklist.setProperty("1",dcm.getString(Tag.PatientName));
worklist.setProperty("2",dcm.getString(Tag.PatientName));
got same property keys (1 and 2) so the value will be overwritten too.
EDIT:
Add sample code:
output = new FileOutputStream("C:\\properties\\worklist.properties");
// For example
int propid = 1;
for(DicomObject dcm : result) {
String key = "patientName" + new Integer(propid++).toString();
worklist.setProperty(key,dcm.getString(Tag.PatientName));
}
worklist.store(output, null);

Java Vector<E> getting blocked with no apparent reason

I'm probably doing something wrong, but this is what happens:
I register a listener, wait for it to be called and when it executes and calls "Vector.clear()" it locks. The problem happens in the "pipeMsgEvent" method, here it is the, not so friendly-looking, code (if you want, go directly to "this is important" lines):
public class JxtaCustomer implements PipeMsgListener {
public static final int ANSWER_OK = 0;
public static final int ANSWER_TIMEOUT =-1;
public static final int ANSWER_NOT_ASKED =-2;
public static final int ANSWER_WORKING =-3;
public static final int REQ_SENT = 0;
public static final int REQ_INV_PIPE_ID =-1;
public static final int REQ_INV_PIPE_IO =-2;
public static final int REQ_INV_GROUP_ID =-3;
protected int answer;
protected JxtaGenericAdvertisement serviceAdv = null;
protected JxtaNode ThePeer = null;
JxtaBiDiPipe myBiDiPipe = null;
protected Vector<Entry> output = null;
public JxtaCustomer(JxtaGenericAdvertisement adv, JxtaNode peer)
{
ThePeer = peer;
serviceAdv = new JxtaGenericAdvertisement((Element)adv.getDocument(new MimeMediaType("text/xml")));
answer = ANSWER_NOT_ASKED;
Vector<Entry> output = new Vector<Entry>();
}
public void pipeMsgEvent(PipeMsgEvent event)
{
System.out.println("It Works! Uhuuu");
// We received a message
Message message = event.getMessage();
System.out.println("Lets GO! Uhuuu");
Message.ElementIterator elIt = message.getMessageElementsOfNamespace( serviceAdv.getName() );
System.out.println("A little bit more");
answer = ANSWER_WORKING;
System.out.println("enter");
// This is important: Here I get stuck, "clear"
// never appears on the screen
output.clear();
System.out.println("clear");
while (elIt.hasNext()) {
MessageElement mElem = elIt.next();
System.out.println(mElem.getElementName() + " " + mElem.toString());
output.add( new Entry( mElem.getElementName(), mElem.toString() ) );
}
System.out.println("leave");
answer = ANSWER_OK;
}
public int sendRequest(Vector<Entry> params)
{
try {
// Creating Pipe Advertisement
String pipeAdvType = PipeAdvertisement.getAdvertisementType();
PipeAdvertisement pipeAd = (PipeAdvertisement)AdvertisementFactory.newAdvertisement(pipeAdvType);
URI pipeURI = new URI(serviceAdv.getPipeID());
pipeAd.setPipeID( IDFactory.fromURI(pipeURI) );
pipeAd.setType(PipeService.UnicastType);
pipeAd.setName(serviceAdv.getName() + " Service Pipe");
pipeAd.setDescription("Created by " + serviceAdv.getName());
// Creating Group
JxtaGroup jxgp = ThePeer.getGroupFromID( serviceAdv.getGroupID() );
if (null == jxgp)
return REQ_INV_GROUP_ID;
PeerGroup group = jxgp.getPeerGroup();
if (null == group)
return REQ_INV_GROUP_ID;
// This is important: In the JxtaBiDiPipe call I register
// the callback, while I have access to the code, I think
// the problem is in my code
myBiDiPipe = new JxtaBiDiPipe( group, pipeAd, 30000, this);
if (myBiDiPipe.isBound()) {
Thread.sleep(500);
Message myMessage = new Message();
if (0 == params.size())
params.add( new Entry("dummy", "null") );
for (int i=0; i<params.size(); i++) {
String Key = params.get(i).getKey();
String Value = params.get(i).getValue();
StringMessageElement strMsgElem = new StringMessageElement( Key, Value, null);
myMessage.addMessageElement( serviceAdv.getName(), strMsgElem);
}
myBiDiPipe.sendMessage(myMessage);
answer = ANSWER_TIMEOUT;
return REQ_SENT;
}
} catch (URISyntaxException e){
e.printStackTrace();
return REQ_INV_PIPE_ID;
} catch (IOException e) {
return REQ_INV_PIPE_IO;
} catch (Exception e) {
e.printStackTrace();
}
return REQ_INV_PIPE_IO;
}
public Vector<Entry> getResponse()
{
Vector<Entry> results = new Vector<Entry>();
if (ANSWER_OK != answer)
return results;
// This is important: I always call "getState()" and check its value
// before calling this method, so you can say it's guaranteed to be
// called after answer = ANSWER_OK, which never happens because of the
// lock
for (int i=0; i<output.size(); i++)
results.add( output.get(i) );
return results;
}
public int getState()
{
int count = 10;
return answer;
}
}
I always create JxtaCustomer like this:
JxtaCustomer customer = new JxtaCustomer(adv, ThePeer);
Vector<Entry> params = new Vector<Entry>();
params.add( new Entry("key1", "value1") );
params.add( new Entry("key2", "value2") );
customer.sendRequest(params);
while(JxtaCustomer.ANSWER_OK != customer.getState()) {
// I was actually using synchronized locks and timed waits
// but since I'm stuck there I'm using this nonsense instead
}
Vector<Entry> response = customer.getResponse();
Here is where in the code I call "sleep", "wait" or I create a "synchronized" (this last one is never)
$ grep synchronized $(find . -name "*.java")
$ grep sleep $(find . -name "*.java")
./Src/net/ubi/jxta/JxtaCustomer.java: Thread.sleep(500);
$ grep wait $(find . -name "*.java")
./App/ExampleServices/SimpleSigner.java: boolean waiting = false;
./App/ExampleServices/SimpleSigner.java: waiting = true;
./App/ExampleServices/SimpleSigner.java: return (waiting && JxtaCustomer.ANSWER_OK == customer.getState());
./App/ExampleServices/SimpleSigner.java: if (!waiting)
./App/ExampleServices/SimpleSigner.java: waiting = false;
./App/ExampleServices/SimpleSigner.java: return "Error: Response not ready, wait more time\n";
Your constructor sets a local variable called output,and not the member variable, you have
Vector<Entry> output = new Vector<Entry>();
when it should be
output = new Vector<Entry>();
So, later on when you call output.clear() you're getting an Null Pointer Exception thrown, which is why the following lines of code don't get executed.
compiler warnings like "unused local variables" can help spot these sorts of mistakes.

Categories