Search in sources :

Example 31 with RollingStock

use of jmri.jmrit.operations.rollingstock.RollingStock in project JMRI by JMRI.

the class Train method getTrainLength.

/**
     * Gets the train's length at the route location specified
     *
     * @param routeLocation The route location
     * @return The train length at the route location
     */
public int getTrainLength(RouteLocation routeLocation) {
    int length = 0;
    Route route = getRoute();
    if (route != null) {
        for (RouteLocation rl : route.getLocationsBySequenceList()) {
            for (RollingStock rs : EngineManager.instance().getList(this)) {
                if (rs.getRouteLocation() == rl) {
                    length += rs.getTotalLength();
                }
                if (rs.getRouteDestination() == rl) {
                    length += -rs.getTotalLength();
                }
            }
            for (RollingStock rs : CarManager.instance().getList(this)) {
                if (rs.getRouteLocation() == rl) {
                    length += rs.getTotalLength();
                }
                if (rs.getRouteDestination() == rl) {
                    length += -rs.getTotalLength();
                }
            }
            if (rl == routeLocation) {
                break;
            }
        }
    }
    return length;
}
Also used : RouteLocation(jmri.jmrit.operations.routes.RouteLocation) Route(jmri.jmrit.operations.routes.Route) RollingStock(jmri.jmrit.operations.rollingstock.RollingStock)

Example 32 with RollingStock

use of jmri.jmrit.operations.rollingstock.RollingStock in project JMRI by JMRI.

the class TrainBuilder method redirectCarsFromAlternateTrack.

/**
     * Checks to see if cars that are already in the train can be redirected
     * from the alternate track to the spur that really wants the car. Fixes the
     * issue of having cars placed at the alternate when the spur's cars get
     * pulled by this train, but cars were sent to the alternate because the
     * spur was full at the time it was tested.
     *
     * @return true if one or more cars were redirected
     */
private boolean redirectCarsFromAlternateTrack() {
    if (!Setup.isBuildAggressive()) {
        return false;
    }
    boolean redirected = false;
    List<RollingStock> cars = carManager.getByTrainList(_train);
    for (RollingStock rs : cars) {
        Car car = (Car) rs;
        // does the car have a final destination and the destination is this one?
        if (car.getFinalDestination() == null || car.getFinalDestinationTrack() == null || !car.getFinalDestinationName().equals(car.getDestinationName())) {
            continue;
        }
        log.debug("Car ({}) destination track ({}) has final destination track ({}) location ({})", car.toString(), car.getDestinationTrackName(), car.getFinalDestinationTrackName(), // NOI18N
        car.getDestinationName());
        // is the car in a kernel?
        if (car.getKernel() != null && !car.getKernel().isLead(car)) {
            continue;
        }
        if (car.testDestination(car.getFinalDestination(), car.getFinalDestinationTrack()).equals(Track.OKAY)) {
            Track alternate = car.getFinalDestinationTrack().getAlternateTrack();
            if (alternate != null && car.getDestinationTrack() == alternate && (alternate.getTrackType().equals(Track.YARD) || alternate.getTrackType().equals(Track.INTERCHANGE)) && checkDropTrainDirection(car, car.getRouteDestination(), car.getFinalDestinationTrack()) && checkTrainCanDrop(car, car.getFinalDestinationTrack())) {
                log.debug("Car ({}) alternate track ({}) can be redirected to final destination track ({})", car.toString(), car.getDestinationTrackName(), car.getFinalDestinationTrackName());
                if (car.getKernel() != null) {
                    for (Car k : car.getKernel().getCars()) {
                        addLine(_buildReport, FIVE, MessageFormat.format(Bundle.getMessage("buildRedirectFromAlternate"), new Object[] { car.getFinalDestinationName(), car.getFinalDestinationTrackName(), k.toString(), car.getDestinationTrackName() }));
                        k.setDestination(car.getFinalDestination(), car.getFinalDestinationTrack());
                    }
                } else {
                    addLine(_buildReport, FIVE, MessageFormat.format(Bundle.getMessage("buildRedirectFromAlternate"), new Object[] { car.getFinalDestinationName(), car.getFinalDestinationTrackName(), car.toString(), car.getDestinationTrackName() }));
                    car.setDestination(car.getFinalDestination(), car.getFinalDestinationTrack());
                }
                redirected = true;
            }
        }
    }
    return redirected;
}
Also used : Car(jmri.jmrit.operations.rollingstock.cars.Car) RollingStock(jmri.jmrit.operations.rollingstock.RollingStock) Track(jmri.jmrit.operations.locations.Track)

Example 33 with RollingStock

use of jmri.jmrit.operations.rollingstock.RollingStock in project JMRI by JMRI.

the class TrainSwitchLists method buildSwitchList.

/**
     * Builds a switch list for a location showing the work by train arrival
     * time. If not running in real time, new train work is appended to the end
     * of the file. User has the ability to modify the text of the messages
     * which can cause an IllegalArgumentException. Some messages have more
     * arguments than the default message allowing the user to customize the
     * message to their liking.
     * 
     * There also an option to list all of the car work by track name. This option
     * is only available in real time and is shown after the switch list by
     * train.
     *
     * @param location The Location needing a switch list
     */
@SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST_OF_RETURN_VALUE", // NOI18N
justification = "CarManager only provides Car Objects")
public void buildSwitchList(Location location) {
    // Append switch list data if not operating in real time
    boolean newTrainsOnly = !Setup.isSwitchListRealTime();
    // add text to end of file when true
    boolean append = false;
    // used to determine if FF needed between trains
    boolean checkFormFeed = true;
    if (newTrainsOnly) {
        if (!location.getStatus().equals(Location.MODIFIED) && !Setup.isSwitchListAllTrainsEnabled()) {
            // nothing to add
            return;
        }
        append = location.getSwitchListState() == Location.SW_APPEND;
        if (location.getSwitchListState() != Location.SW_APPEND) {
            location.setSwitchListState(Location.SW_APPEND);
        }
        location.setStatus(Location.UPDATED);
    }
    log.debug("Append: {} for location ({})", append, location.getName());
    // create switch list file
    File file = TrainManagerXml.instance().createSwitchListFile(location.getName());
    PrintWriter fileOut = null;
    try {
        fileOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, append), "UTF-8")), // NOI18N
        true);
    } catch (IOException e) {
        log.error("Can not open switchlist file: {}", file.getName());
        return;
    }
    try {
        // build header
        if (!append) {
            newLine(fileOut, Setup.getRailroadName());
            newLine(fileOut);
            newLine(fileOut, MessageFormat.format(messageFormatText = TrainSwitchListText.getStringSwitchListFor(), new Object[] { splitString(location.getName()) }));
            if (!location.getSwitchListComment().equals(Location.NONE)) {
                newLine(fileOut, location.getSwitchListComment());
            }
        }
        String valid = MessageFormat.format(messageFormatText = TrainManifestText.getStringValid(), new Object[] { getDate(true) });
        if (Setup.isPrintTimetableNameEnabled()) {
            TrainSchedule sch = TrainScheduleManager.instance().getScheduleById(trainManager.getTrainScheduleActiveId());
            if (sch != null) {
                valid = valid + " (" + sch.getName() + ")";
            }
        }
        // get a list of trains sorted by arrival time
        List<Train> trains = trainManager.getTrainsArrivingThisLocationList(location);
        for (Train train : trains) {
            if (!train.isBuilt()) {
                // train wasn't built so skip
                continue;
            }
            if (newTrainsOnly && train.getSwitchListStatus().equals(Train.PRINTED)) {
                // already printed this train
                continue;
            }
            Route route = train.getRoute();
            if (route == null) {
                // no route for this train
                continue;
            }
            // determine if train works this location
            boolean works = isThereWorkAtLocation(train, location);
            if (!works && !Setup.isSwitchListAllTrainsEnabled()) {
                log.debug("No work for train ({}) at location ({})", train.getName(), location.getName());
                continue;
            }
            // we're now going to add to the switch list
            if (checkFormFeed) {
                if (append && !Setup.getSwitchListPageFormat().equals(Setup.PAGE_NORMAL)) {
                    fileOut.write(FORM_FEED);
                }
                if (Setup.isPrintValidEnabled()) {
                    newLine(fileOut, valid);
                }
            } else if (!Setup.getSwitchListPageFormat().equals(Setup.PAGE_NORMAL)) {
                fileOut.write(FORM_FEED);
            }
            // done with FF for this train
            checkFormFeed = false;
            // some cars booleans and the number of times this location get's serviced
            // when true there was a car pick up
            pickupCars = false;
            // when true there was a car set out
            dropCars = false;
            int stops = 1;
            boolean trainDone = false;
            // get engine and car lists
            List<Engine> engineList = engineManager.getByTrainBlockingList(train);
            List<Car> carList = carManager.getByTrainDestinationList(train);
            List<RouteLocation> routeList = route.getLocationsBySequenceList();
            RouteLocation rlPrevious = null;
            // does the train stop once or more at this location?
            for (RouteLocation rl : routeList) {
                if (!splitString(rl.getName()).equals(splitString(location.getName()))) {
                    rlPrevious = rl;
                    continue;
                }
                String expectedArrivalTime = train.getExpectedArrivalTime(rl);
                if (expectedArrivalTime.equals(Train.ALREADY_SERVICED)) {
                    trainDone = true;
                }
                // first time at this location?
                if (stops == 1) {
                    newLine(fileOut);
                    newLine(fileOut, MessageFormat.format(messageFormatText = TrainSwitchListText.getStringScheduledWork(), new Object[] { train.getName(), train.getDescription() }));
                    if (train.isTrainEnRoute()) {
                        if (!trainDone) {
                            newLine(fileOut, MessageFormat.format(messageFormatText = TrainSwitchListText.getStringDepartedExpected(), new Object[] { splitString(train.getTrainDepartsName()), expectedArrivalTime, rl.getTrainDirectionString() }));
                        }
                    } else if (!train.isLocalSwitcher()) {
                        if (rl == train.getRoute().getDepartsRouteLocation()) {
                            newLine(fileOut, MessageFormat.format(messageFormatText = TrainSwitchListText.getStringDepartsAt(), new Object[] { splitString(train.getTrainDepartsName()), rl.getTrainDirectionString(), train.getFormatedDepartureTime() }));
                        } else {
                            newLine(fileOut, MessageFormat.format(messageFormatText = TrainSwitchListText.getStringDepartsAtExpectedArrival(), new Object[] { splitString(train.getTrainDepartsName()), train.getFormatedDepartureTime(), expectedArrivalTime, rl.getTrainDirectionString() }));
                        }
                    }
                } else {
                    // Print visit number only if previous location wasn't the same
                    if (rlPrevious == null || !splitString(rl.getName()).equals(splitString(rlPrevious.getName()))) {
                        if (Setup.getSwitchListPageFormat().equals(Setup.PAGE_PER_VISIT)) {
                            fileOut.write(FORM_FEED);
                        }
                        newLine(fileOut);
                        if (train.isTrainEnRoute()) {
                            if (expectedArrivalTime.equals(Train.ALREADY_SERVICED)) {
                                newLine(fileOut, MessageFormat.format(messageFormatText = TrainSwitchListText.getStringVisitNumberDone(), new Object[] { stops, train.getName(), train.getDescription() }));
                            } else if (rl != train.getRoute().getTerminatesRouteLocation()) {
                                newLine(fileOut, MessageFormat.format(messageFormatText = TrainSwitchListText.getStringVisitNumberDeparted(), new Object[] { stops, train.getName(), expectedArrivalTime, rl.getTrainDirectionString(), train.getDescription() }));
                            } else {
                                // message: Visit number {0} for train ({1}) expect to arrive in {2}, terminates {3}
                                newLine(fileOut, MessageFormat.format(messageFormatText = TrainSwitchListText.getStringVisitNumberTerminatesDeparted(), new Object[] { stops, train.getName(), expectedArrivalTime, splitString(rl.getName()), train.getDescription() }));
                            }
                        } else {
                            // train hasn't departed
                            if (rl != train.getRoute().getTerminatesRouteLocation()) {
                                newLine(fileOut, MessageFormat.format(messageFormatText = TrainSwitchListText.getStringVisitNumber(), new Object[] { stops, train.getName(), expectedArrivalTime, rl.getTrainDirectionString(), train.getDescription() }));
                            } else {
                                newLine(fileOut, MessageFormat.format(messageFormatText = TrainSwitchListText.getStringVisitNumberTerminates(), new Object[] { stops, train.getName(), expectedArrivalTime, splitString(rl.getName()), train.getDescription() }));
                            }
                        }
                    } else {
                        // don't bump stop count, same location
                        stops--;
                        // Does the train reverse direction?
                        if (rl.getTrainDirection() != rlPrevious.getTrainDirection() && !TrainSwitchListText.getStringTrainDirectionChange().equals("")) {
                            newLine(fileOut, MessageFormat.format(messageFormatText = TrainSwitchListText.getStringTrainDirectionChange(), new Object[] { train.getName(), rl.getTrainDirectionString(), train.getDescription(), train.getTrainTerminatesName() }));
                        }
                    }
                }
                // save current location in case there's back to back location with the same name
                rlPrevious = rl;
                // add route comment
                if (Setup.isSwitchListRouteLocationCommentEnabled() && !rl.getComment().trim().equals("")) {
                    newLine(fileOut, rl.getComment());
                }
                // now print out the work for this location
                if (Setup.getManifestFormat().equals(Setup.STANDARD_FORMAT)) {
                    pickupEngines(fileOut, engineList, rl, !IS_MANIFEST);
                    // if switcher show loco drop at end of list
                    if (train.isLocalSwitcher()) {
                        blockCarsByTrack(fileOut, train, carList, routeList, rl, IS_PRINT_HEADER, !IS_MANIFEST);
                        dropEngines(fileOut, engineList, rl, !IS_MANIFEST);
                    } else {
                        dropEngines(fileOut, engineList, rl, !IS_MANIFEST);
                        blockCarsByTrack(fileOut, train, carList, routeList, rl, IS_PRINT_HEADER, !IS_MANIFEST);
                    }
                } else if (Setup.getManifestFormat().equals(Setup.TWO_COLUMN_FORMAT)) {
                    blockLocosTwoColumn(fileOut, engineList, rl, !IS_MANIFEST);
                    blockCarsByTrackTwoColumn(fileOut, train, carList, routeList, rl, IS_PRINT_HEADER, !IS_MANIFEST);
                } else {
                    blockLocosTwoColumn(fileOut, engineList, rl, !IS_MANIFEST);
                    blockCarsByTrackNameTwoColumn(fileOut, train, carList, routeList, rl, IS_PRINT_HEADER, !IS_MANIFEST);
                }
                if (Setup.isPrintHeadersEnabled() || !Setup.getManifestFormat().equals(Setup.STANDARD_FORMAT)) {
                    printHorizontalLine(fileOut, !IS_MANIFEST);
                }
                stops++;
                // done with work, now print summary for this location if we're done
                if (rl != train.getRoute().getTerminatesRouteLocation()) {
                    RouteLocation nextRl = train.getRoute().getNextRouteLocation(rl);
                    if (splitString(rl.getName()).equals(splitString(nextRl.getName()))) {
                        // the current location name is the "same" as the next
                        continue;
                    }
                    // print departure text if not a switcher
                    if (!train.isLocalSwitcher()) {
                        String trainDeparts = "";
                        if (Setup.isPrintLoadsAndEmptiesEnabled()) {
                            int emptyCars = train.getNumberEmptyCarsInTrain(rl);
                            // Message format: Train departs Boston Westbound with 4 loads, 8 empties, 450 feet,
                            // 3000 tons
                            trainDeparts = MessageFormat.format(TrainSwitchListText.getStringTrainDepartsLoads(), new Object[] { TrainCommon.splitString(rl.getName()), rl.getTrainDirectionString(), train.getNumberCarsInTrain(rl) - emptyCars, emptyCars, train.getTrainLength(rl), Setup.getLengthUnit().toLowerCase(), train.getTrainWeight(rl), train.getTrainTerminatesName(), train.getName() });
                        } else {
                            // Message format: Train departs Boston Westbound with 12 cars, 450 feet, 3000 tons
                            trainDeparts = MessageFormat.format(TrainSwitchListText.getStringTrainDepartsCars(), new Object[] { TrainCommon.splitString(rl.getName()), rl.getTrainDirectionString(), train.getNumberCarsInTrain(rl), train.getTrainLength(rl), Setup.getLengthUnit().toLowerCase(), train.getTrainWeight(rl), train.getTrainTerminatesName(), train.getName() });
                        }
                        newLine(fileOut, trainDeparts);
                    }
                }
            }
            if (trainDone && !pickupCars && !dropCars) {
                // Default message: Train ({0}) has serviced this location
                newLine(fileOut, MessageFormat.format(messageFormatText = TrainSwitchListText.getStringTrainDone(), new Object[] { train.getName(), train.getDescription(), splitString(location.getName()) }));
            } else {
                if (stops > 1 && !pickupCars) {
                    // Default message: No car pick ups for train ({0}) at this location
                    newLine(fileOut, MessageFormat.format(messageFormatText = TrainSwitchListText.getStringNoCarPickUps(), new Object[] { train.getName(), train.getDescription(), splitString(location.getName()) }));
                }
                if (stops > 1 && !dropCars) {
                    // Default message: No car set outs for train ({0}) at this location
                    newLine(fileOut, MessageFormat.format(messageFormatText = TrainSwitchListText.getStringNoCarDrops(), new Object[] { train.getName(), train.getDescription(), splitString(location.getName()) }));
                }
            }
        }
        // now report car movement by tracks at location
        if (Setup.isTrackSummaryEnabled() && Setup.isSwitchListRealTime()) {
            // list utility cars by quantity
            clearUtilityCarTypes();
            if (Setup.getSwitchListPageFormat().equals(Setup.PAGE_NORMAL)) {
                newLine(fileOut);
                newLine(fileOut);
            } else {
                fileOut.write(FORM_FEED);
            }
            newLine(fileOut, MessageFormat.format(messageFormatText = TrainSwitchListText.getStringSwitchListByTrack(), new Object[] { splitString(location.getName()) }));
            // we only need the cars delivered to or at this location
            List<RollingStock> rsList = carManager.getByTrainList();
            List<Car> carList = new ArrayList<Car>();
            for (RollingStock rs : rsList) {
                if ((rs.getLocation() != null && splitString(rs.getLocation().getName()).equals(splitString(location.getName()))) || (rs.getDestination() != null && splitString(rs.getDestination().getName()).equals(splitString(location.getName()))))
                    carList.add((Car) rs);
            }
            // locations and tracks can have "similar" names, only list track names once
            List<String> trackNames = new ArrayList<String>();
            for (Location loc : locationManager.getLocationsByNameList()) {
                if (!splitString(loc.getName()).equals(splitString(location.getName())))
                    continue;
                for (Track track : loc.getTrackByNameList(null)) {
                    String trackName = splitString(track.getName());
                    if (trackNames.contains(trackName))
                        continue;
                    trackNames.add(trackName);
                    // for printing train message once                     
                    String trainName = "";
                    newLine(fileOut);
                    // print out just the track name
                    newLine(fileOut, trackName);
                    // now show the cars pickup and holds for this track
                    for (Car car : carList) {
                        if (!splitString(car.getTrackName()).equals(trackName)) {
                            continue;
                        }
                        // is the car scheduled for pickup?
                        if (car.getRouteLocation() != null) {
                            if (splitString(car.getRouteLocation().getLocation().getName()).equals(splitString(location.getName()))) {
                                // cars are sorted by train name, print train message once
                                if (!trainName.equals(car.getTrainName())) {
                                    trainName = car.getTrainName();
                                    newLine(fileOut, MessageFormat.format(messageFormatText = TrainSwitchListText.getStringScheduledWork(), new Object[] { car.getTrainName(), car.getTrain().getDescription() }));
                                    printPickupCarHeader(fileOut, !IS_MANIFEST, !IS_TWO_COLUMN_TRACK);
                                }
                                if (car.isUtility()) {
                                    pickupUtilityCars(fileOut, carList, car, !IS_MANIFEST);
                                } else {
                                    pickUpCar(fileOut, car, !IS_MANIFEST);
                                }
                            }
                        // car holds
                        } else if (car.isUtility()) {
                            String s = pickupUtilityCars(carList, car, !IS_MANIFEST, !IS_TWO_COLUMN_TRACK);
                            if (s != null) {
                                newLine(fileOut, // NOI18N
                                TrainSwitchListText.getStringHoldCar().split("\\{")[0] + s.trim());
                            }
                        } else {
                            newLine(fileOut, MessageFormat.format(messageFormatText = TrainSwitchListText.getStringHoldCar(), new Object[] { padAndTruncateString(car.getRoadName(), CarRoads.instance().getMaxNameLength()), padAndTruncateString(TrainCommon.splitString(car.getNumber()), Control.max_len_string_print_road_number), padAndTruncateString(car.getTypeName().split("-")[0], CarTypes.instance().getMaxNameLength()), padAndTruncateString(car.getLength() + LENGTHABV, Control.max_len_string_length_name), padAndTruncateString(car.getLoadName(), CarLoads.instance().getMaxNameLength()), padAndTruncateString(trackName, locationManager.getMaxTrackNameLength()), padAndTruncateString(car.getColor(), CarColors.instance().getMaxNameLength()) }));
                        }
                    }
                    // now do set outs at this location
                    for (Car car : carList) {
                        if (!splitString(car.getDestinationTrackName()).equals(trackName)) {
                            continue;
                        }
                        if (car.getRouteDestination() != null && splitString(car.getRouteDestination().getLocation().getName()).equals(splitString(location.getName()))) {
                            // cars are sorted by train name, print train message once
                            if (!trainName.equals(car.getTrainName())) {
                                trainName = car.getTrainName();
                                newLine(fileOut, MessageFormat.format(messageFormatText = TrainSwitchListText.getStringScheduledWork(), new Object[] { car.getTrainName(), car.getTrain().getDescription() }));
                                printDropCarHeader(fileOut, !IS_MANIFEST, !IS_TWO_COLUMN_TRACK);
                            }
                            if (car.isUtility()) {
                                setoutUtilityCars(fileOut, carList, car, !IS_MANIFEST);
                            } else {
                                dropCar(fileOut, car, !IS_MANIFEST);
                            }
                        }
                    }
                }
            }
        }
    } catch (IllegalArgumentException e) {
        newLine(fileOut, MessageFormat.format(Bundle.getMessage("ErrorIllegalArgument"), new Object[] { Bundle.getMessage("TitleSwitchListText"), e.getLocalizedMessage() }));
        newLine(fileOut, messageFormatText);
        e.printStackTrace();
    }
    // Are there any cars that need to be found?
    addCarsLocationUnknown(fileOut, !IS_MANIFEST);
    fileOut.flush();
    fileOut.close();
}
Also used : ArrayList(java.util.ArrayList) RouteLocation(jmri.jmrit.operations.routes.RouteLocation) RollingStock(jmri.jmrit.operations.rollingstock.RollingStock) BufferedWriter(java.io.BufferedWriter) TrainSchedule(jmri.jmrit.operations.trains.timetable.TrainSchedule) Route(jmri.jmrit.operations.routes.Route) Engine(jmri.jmrit.operations.rollingstock.engines.Engine) PrintWriter(java.io.PrintWriter) IOException(java.io.IOException) Car(jmri.jmrit.operations.rollingstock.cars.Car) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File) Track(jmri.jmrit.operations.locations.Track) RouteLocation(jmri.jmrit.operations.routes.RouteLocation) Location(jmri.jmrit.operations.locations.Location) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Example 34 with RollingStock

use of jmri.jmrit.operations.rollingstock.RollingStock in project JMRI by JMRI.

the class TrackDestinationEditFrame method checkLocationsLoop.

private boolean checkLocationsLoop() {
    boolean noIssues = true;
    for (Location destination : locationManager.getLocationsByNameList()) {
        if (_track.acceptsDestination(destination)) {
            log.debug("Track ({}) accepts destination ({})", _track.getName(), destination.getName());
            //                statusFrame.repaint();
            if (_track.getLocation() == destination) {
                continue;
            }
            // now check to see if the track's rolling stock is accepted by the destination
            checkTypes: for (String type : CarTypes.instance().getNames()) {
                if (!_track.acceptsTypeName(type)) {
                    continue;
                }
                if (!destination.acceptsTypeName(type)) {
                    noIssues = false;
                    int response = JOptionPane.showConfirmDialog(this, MessageFormat.format(Bundle.getMessage("WarningDestinationCarType"), new Object[] { destination.getName(), type }), Bundle.getMessage("WarningCarMayNotMove"), JOptionPane.OK_CANCEL_OPTION);
                    if (response == JOptionPane.OK_OPTION)
                        continue;
                    // done
                    return false;
                }
                // now determine if there's a track willing to service car type
                for (Track track : destination.getTrackList()) {
                    if (track.acceptsTypeName(type)) {
                        // yes there's a track
                        continue checkTypes;
                    }
                }
                noIssues = false;
                int response = JOptionPane.showConfirmDialog(this, MessageFormat.format(Bundle.getMessage("WarningDestinationTrackCarType"), new Object[] { destination.getName(), type }), Bundle.getMessage("WarningCarMayNotMove"), JOptionPane.OK_CANCEL_OPTION);
                if (response == JOptionPane.OK_OPTION)
                    continue;
                // done
                return false;
            }
            // now check road names
            checkRoads: for (String road : CarRoads.instance().getNames()) {
                if (!_track.acceptsRoadName(road)) {
                    continue;
                }
                // now determine if there's a track willing to service this road
                for (Track track : destination.getTrackList()) {
                    if (track.acceptsRoadName(road)) {
                        // yes there's a track
                        continue checkRoads;
                    }
                }
                noIssues = false;
                int response = JOptionPane.showConfirmDialog(this, MessageFormat.format(Bundle.getMessage("WarningDestinationTrackCarRoad"), new Object[] { destination.getName(), road }), Bundle.getMessage("WarningCarMayNotMove"), JOptionPane.OK_CANCEL_OPTION);
                if (response == JOptionPane.OK_OPTION)
                    continue;
                // done
                return false;
            }
            // now check load names
            for (String type : CarTypes.instance().getNames()) {
                if (!_track.acceptsTypeName(type)) {
                    continue;
                }
                List<String> loads = CarLoads.instance().getNames(type);
                checkLoads: for (String load : loads) {
                    if (!_track.acceptsLoadName(load)) {
                        continue;
                    }
                    // now determine if there's a track willing to service this load
                    for (Track track : destination.getTrackList()) {
                        if (track.acceptsLoadName(load)) {
                            continue checkLoads;
                        }
                    }
                    noIssues = false;
                    int response = JOptionPane.showConfirmDialog(this, MessageFormat.format(Bundle.getMessage("WarningDestinationTrackCarLoad"), new Object[] { destination.getName(), type, load }), Bundle.getMessage("WarningCarMayNotMove"), JOptionPane.OK_CANCEL_OPTION);
                    if (response == JOptionPane.OK_OPTION)
                        continue;
                    // done
                    return false;
                }
                // now check car type and load combinations
                checkLoads: for (String load : loads) {
                    if (!_track.acceptsLoad(load, type)) {
                        continue;
                    }
                    // now determine if there's a track willing to service this load
                    for (Track track : destination.getTrackList()) {
                        if (track.acceptsLoad(load, type)) {
                            continue checkLoads;
                        }
                    }
                    noIssues = false;
                    int response = JOptionPane.showConfirmDialog(this, MessageFormat.format(Bundle.getMessage("WarningDestinationTrackCarLoad"), new Object[] { destination.getName(), type, load }), Bundle.getMessage("WarningCarMayNotMove"), JOptionPane.OK_CANCEL_OPTION);
                    if (response == JOptionPane.OK_OPTION)
                        continue;
                    // done
                    return false;
                }
            }
            // now determine if there's a train or trains that can move a car from this track to the destinations
            // need to check all car types, loads, and roads that this track services
            Car car = new Car();
            // set car length to net out to zero
            car.setLength(Integer.toString(-RollingStock.COUPLER));
            for (String type : CarTypes.instance().getNames()) {
                if (!_track.acceptsTypeName(type)) {
                    continue;
                }
                List<String> loads = CarLoads.instance().getNames(type);
                for (String load : loads) {
                    if (!_track.acceptsLoad(load, type)) {
                        continue;
                    }
                    for (String road : CarRoads.instance().getNames()) {
                        if (!_track.acceptsRoadName(road)) {
                            continue;
                        }
                        // is there a car with this road?
                        boolean foundCar = false;
                        for (RollingStock rs : CarManager.instance().getList()) {
                            if (rs.getTypeName().equals(type) && rs.getRoadName().equals(road)) {
                                foundCar = true;
                                break;
                            }
                        }
                        if (!foundCar) {
                            // no car with this road name
                            continue;
                        }
                        car.setTypeName(type);
                        car.setRoadName(road);
                        car.setLoadName(load);
                        car.setTrack(_track);
                        car.setFinalDestination(destination);
                        // does the destination accept this car?
                        // this checks tracks that have schedules
                        String testDest = "";
                        for (Track track : destination.getTrackList()) {
                            if (track.getScheduleMode() == Track.SEQUENTIAL) {
                                // must test in match mode
                                track.setScheduleMode(Track.MATCH);
                                String itemId = track.getScheduleItemId();
                                testDest = car.testDestination(destination, track);
                                track.setScheduleMode(Track.SEQUENTIAL);
                                track.setScheduleItemId(itemId);
                            } else {
                                testDest = car.testDestination(destination, track);
                            }
                            if (testDest.equals(Track.OKAY)) {
                                // done
                                break;
                            }
                        }
                        if (!testDest.equals(Track.OKAY)) {
                            noIssues = false;
                            int response = JOptionPane.showConfirmDialog(this, MessageFormat.format(Bundle.getMessage("WarningNoTrack"), new Object[] { destination.getName(), type, road, load, destination.getName() }), Bundle.getMessage("WarningCarMayNotMove"), JOptionPane.OK_CANCEL_OPTION);
                            if (response == JOptionPane.OK_OPTION)
                                continue;
                            // done
                            return false;
                        }
                        log.debug("Find train for car type ({}), road ({}), load ({})", type, road, load);
                        boolean results = Router.instance().setDestination(car, null, null);
                        // clear destination if set by router
                        car.setDestination(null, null);
                        if (!results) {
                            noIssues = false;
                            int response = JOptionPane.showConfirmDialog(this, MessageFormat.format(Bundle.getMessage("WarningNoTrain"), new Object[] { type, road, load, destination.getName() }), Bundle.getMessage("WarningCarMayNotMove"), JOptionPane.OK_CANCEL_OPTION);
                            if (response == JOptionPane.OK_OPTION)
                                continue;
                            // done
                            return false;
                        }
                    // TODO need to check owners and car built dates
                    }
                }
            }
        }
    }
    return noIssues;
}
Also used : Car(jmri.jmrit.operations.rollingstock.cars.Car) Track(jmri.jmrit.operations.locations.Track) RollingStock(jmri.jmrit.operations.rollingstock.RollingStock) Location(jmri.jmrit.operations.locations.Location)

Example 35 with RollingStock

use of jmri.jmrit.operations.rollingstock.RollingStock in project JMRI by JMRI.

the class PrintCarRosterAction method printCars.

@SuppressFBWarnings(value = "BC_UNCONFIRMED_CAST_OF_RETURN_VALUE", justification = "CarManager only provides Car Objects")
private void printCars() {
    boolean landscape = false;
    if (manifestOrientationComboBox.getSelectedItem() != null && manifestOrientationComboBox.getSelectedItem() == Setup.LANDSCAPE) {
        landscape = true;
    }
    int fontSize = (int) fontSizeComboBox.getSelectedItem();
    // obtain a HardcopyWriter to do this
    HardcopyWriter writer = null;
    try {
        writer = new HardcopyWriter(mFrame, Bundle.getMessage("TitleCarRoster"), fontSize, .5, .5, .5, .5, isPreview, "", landscape, true, null);
    } catch (HardcopyWriter.PrintCanceledException ex) {
        log.debug("Print cancelled");
        return;
    }
    numberCharPerLine = writer.getCharactersPerLine();
    // Loop through the Roster, printing as needed
    String location = "";
    String number;
    String road;
    String type;
    String length = "";
    String weight = "";
    String color = "";
    String owner = "";
    String built = "";
    String load = "";
    String kernel = "";
    String train = "";
    String destination = "";
    String finalDestination = "";
    String returnWhenEmpty = "";
    String value = "";
    String rfid = "";
    String last = "";
    String wait = "";
    String schedule = "";
    String comment = "";
    try {
        printTitleLine(writer);
        String previousLocation = null;
        List<RollingStock> cars = panel.carsTableModel.getCarList(sortByComboBox.getSelectedIndex());
        for (RollingStock rs : cars) {
            Car car = (Car) rs;
            if (printCarsWithLocation.isSelected() && car.getLocation() == null) {
                // car doesn't have a location skip
                continue;
            }
            location = "";
            destination = "";
            finalDestination = "";
            returnWhenEmpty = "";
            if (printCarLocation.isSelected()) {
                if (car.getLocation() != null) {
                    location = car.getLocationName().trim() + " - " + car.getTrackName().trim();
                }
                location = padAttribute(location, LocationManager.instance().getMaxLocationAndTrackNameLength() + 3);
            }
            // Page break between locations?
            if (previousLocation != null && !car.getLocationName().trim().equals(previousLocation) && printPage.isSelected()) {
                writer.pageBreak();
                printTitleLine(writer);
            } else // Add a line between locations?
            if (previousLocation != null && !car.getLocationName().trim().equals(previousLocation) && printSpace.isSelected()) {
                writer.write(NEW_LINE);
            }
            previousLocation = car.getLocationName().trim();
            // car number
            number = padAttribute(car.getNumber().trim(), Control.max_len_string_print_road_number);
            // car road
            road = padAttribute(car.getRoadName().trim(), CarRoads.instance().getMaxNameLength());
            // car type
            type = padAttribute(car.getTypeName().trim(), CarTypes.instance().getMaxFullNameLength());
            if (printCarLength.isSelected()) {
                length = padAttribute(car.getLength().trim(), Control.max_len_string_length_name);
            }
            if (printCarWeight.isSelected()) {
                weight = padAttribute(car.getWeight().trim(), Control.max_len_string_weight_name);
            }
            if (printCarColor.isSelected()) {
                color = padAttribute(car.getColor().trim(), CarColors.instance().getMaxNameLength());
            }
            if (printCarLoad.isSelected()) {
                load = padAttribute(car.getLoadName().trim(), CarLoads.instance().getMaxNameLength());
            }
            if (printCarKernel.isSelected()) {
                kernel = padAttribute(car.getKernelName().trim(), Control.max_len_string_attibute);
            }
            if (printCarOwner.isSelected()) {
                owner = padAttribute(car.getOwner().trim(), CarOwners.instance().getMaxNameLength());
            }
            if (printCarBuilt.isSelected()) {
                built = padAttribute(car.getBuilt().trim(), Control.max_len_string_built_name);
            }
            if (printCarLast.isSelected()) {
                last = padAttribute(car.getLastDate().split(" ")[0], 10);
            }
            if (printCarWait.isSelected()) {
                wait = padAttribute(Integer.toString(car.getWait()), 4);
            }
            if (printCarPickup.isSelected()) {
                schedule = padAttribute(car.getPickupScheduleName(), 10);
            }
            if (printCarValue.isSelected()) {
                value = padAttribute(car.getValue().trim(), Control.max_len_string_attibute);
            }
            if (printCarRfid.isSelected()) {
                rfid = padAttribute(car.getRfid().trim(), Control.max_len_string_attibute);
            }
            if (// pad out train to half of its maximum
            printCarTrain.isSelected()) {
                train = padAttribute(car.getTrainName().trim(), Control.max_len_string_train_name / 2);
            }
            if (printCarDestination.isSelected()) {
                if (car.getDestination() != null) {
                    destination = car.getDestinationName().trim() + " - " + car.getDestinationTrackName();
                }
                destination = padAttribute(destination, LocationManager.instance().getMaxLocationAndTrackNameLength() + 3);
            }
            if (printCarFinalDestination.isSelected()) {
                if (car.getFinalDestination() != null) {
                    finalDestination = car.getFinalDestinationName().trim() + " - " + car.getFinalDestinationTrackName().trim();
                }
                finalDestination = padAttribute(finalDestination, LocationManager.instance().getMaxLocationAndTrackNameLength() + 3);
            }
            if (printCarRWE.isSelected()) {
                if (car.getReturnWhenEmptyDestination() != null) {
                    returnWhenEmpty = car.getReturnWhenEmptyDestinationName().trim() + " - " + car.getReturnWhenEmptyDestTrackName().trim();
                }
                returnWhenEmpty = padAttribute(returnWhenEmpty, LocationManager.instance().getMaxLocationAndTrackNameLength() + 3);
            }
            if (printCarComment.isSelected()) {
                comment = car.getComment().trim();
            }
            String s = number + road + type + length + weight + color + load + kernel + owner + built + last + wait + schedule + value + rfid + location + train + destination + finalDestination + returnWhenEmpty + comment;
            if (s.length() > numberCharPerLine) {
                s = s.substring(0, numberCharPerLine);
            }
            writer.write(s + NEW_LINE);
        }
        // and force completion of the printing
        writer.close();
    } catch (IOException we) {
        log.error("Error printing car roster");
    }
}
Also used : IOException(java.io.IOException) HardcopyWriter(jmri.util.davidflanagan.HardcopyWriter) RollingStock(jmri.jmrit.operations.rollingstock.RollingStock) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings)

Aggregations

RollingStock (jmri.jmrit.operations.rollingstock.RollingStock)43 SuppressFBWarnings (edu.umd.cs.findbugs.annotations.SuppressFBWarnings)13 Car (jmri.jmrit.operations.rollingstock.cars.Car)13 Route (jmri.jmrit.operations.routes.Route)11 RouteLocation (jmri.jmrit.operations.routes.RouteLocation)11 Track (jmri.jmrit.operations.locations.Track)7 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)5 Location (jmri.jmrit.operations.locations.Location)5 Engine (jmri.jmrit.operations.rollingstock.engines.Engine)5 Train (jmri.jmrit.operations.trains.Train)5 BufferedWriter (java.io.BufferedWriter)4 File (java.io.File)4 FileOutputStream (java.io.FileOutputStream)4 OutputStreamWriter (java.io.OutputStreamWriter)4 PrintWriter (java.io.PrintWriter)4 Dimension (java.awt.Dimension)2 JPanel (javax.swing.JPanel)2 XmlFile (jmri.jmrit.XmlFile)2 HardcopyWriter (jmri.util.davidflanagan.HardcopyWriter)2