Example usage for org.apache.commons.configuration HierarchicalConfiguration containsKey

List of usage examples for org.apache.commons.configuration HierarchicalConfiguration containsKey

Introduction

In this page you can find the example usage for org.apache.commons.configuration HierarchicalConfiguration containsKey.

Prototype

public boolean containsKey(String key) 

Source Link

Document

Checks if the specified key is contained in this configuration.

Usage

From source file:com.graphhopper.jsprit.core.problem.io.VrpXMLReader.java

private void readShipments(XMLConfiguration config) {
    List<HierarchicalConfiguration> shipmentConfigs = config.configurationsAt("shipments.shipment");
    for (HierarchicalConfiguration shipmentConfig : shipmentConfigs) {
        String id = shipmentConfig.getString("[@id]");
        if (id == null)
            throw new IllegalStateException("shipment[@id] is missing.");

        String capacityString = shipmentConfig.getString("capacity-demand");
        boolean capacityDimensionsExist = shipmentConfig.containsKey("capacity-dimensions.dimension(0)");
        if (capacityString == null && !capacityDimensionsExist) {
            throw new IllegalStateException("capacity of shipment is not set. use 'capacity-dimensions'");
        }/*from ww w  .j  a v  a2 s  . c om*/
        if (capacityString != null && capacityDimensionsExist) {
            throw new IllegalStateException(
                    "either use capacity or capacity-dimension, not both. prefer the use of 'capacity-dimensions' over 'capacity'.");
        }

        Shipment.Builder builder;
        if (capacityString != null) {
            builder = Shipment.Builder.newInstance(id).addSizeDimension(0, Integer.parseInt(capacityString));
        } else {
            builder = Shipment.Builder.newInstance(id);
            List<HierarchicalConfiguration> dimensionConfigs = shipmentConfig
                    .configurationsAt("capacity-dimensions.dimension");
            for (HierarchicalConfiguration dimension : dimensionConfigs) {
                Integer index = dimension.getInt("[@index]");
                Integer value = dimension.getInt("");
                builder.addSizeDimension(index, value);
            }
        }

        //name
        String name = shipmentConfig.getString("name");
        if (name != null)
            builder.setName(name);

        //pickup location
        //pickup-locationId
        Location.Builder pickupLocationBuilder = Location.Builder.newInstance();
        String pickupLocationId = shipmentConfig.getString("pickup.locationId");
        if (pickupLocationId == null)
            pickupLocationId = shipmentConfig.getString("pickup.location.id");
        if (pickupLocationId != null) {
            pickupLocationBuilder.setId(pickupLocationId);
        }

        //pickup-coord
        Coordinate pickupCoord = getCoord(shipmentConfig, "pickup.");
        if (pickupCoord == null)
            pickupCoord = getCoord(shipmentConfig, "pickup.location.");
        if (pickupCoord != null) {
            pickupLocationBuilder.setCoordinate(pickupCoord);
        }

        //pickup.location.index
        String pickupLocationIndex = shipmentConfig.getString("pickup.location.index");
        if (pickupLocationIndex != null)
            pickupLocationBuilder.setIndex(Integer.parseInt(pickupLocationIndex));
        builder.setPickupLocation(pickupLocationBuilder.build());

        //pickup-serviceTime
        String pickupServiceTime = shipmentConfig.getString("pickup.duration");
        if (pickupServiceTime != null)
            builder.setPickupServiceTime(Double.parseDouble(pickupServiceTime));

        //pickup-tw
        List<HierarchicalConfiguration> pickupTWConfigs = shipmentConfig
                .configurationsAt("pickup.timeWindows.timeWindow");
        if (!pickupTWConfigs.isEmpty()) {
            for (HierarchicalConfiguration pu_twConfig : pickupTWConfigs) {
                builder.addPickupTimeWindow(
                        TimeWindow.newInstance(pu_twConfig.getDouble("start"), pu_twConfig.getDouble("end")));
            }
        }

        //delivery location
        //delivery-locationId
        Location.Builder deliveryLocationBuilder = Location.Builder.newInstance();
        String deliveryLocationId = shipmentConfig.getString("delivery.locationId");
        if (deliveryLocationId == null)
            deliveryLocationId = shipmentConfig.getString("delivery.location.id");
        if (deliveryLocationId != null) {
            deliveryLocationBuilder.setId(deliveryLocationId);
            //            builder.setDeliveryLocationId(deliveryLocationId);
        }

        //delivery-coord
        Coordinate deliveryCoord = getCoord(shipmentConfig, "delivery.");
        if (deliveryCoord == null)
            deliveryCoord = getCoord(shipmentConfig, "delivery.location.");
        if (deliveryCoord != null) {
            deliveryLocationBuilder.setCoordinate(deliveryCoord);
        }

        String deliveryLocationIndex = shipmentConfig.getString("delivery.location.index");
        if (deliveryLocationIndex != null)
            deliveryLocationBuilder.setIndex(Integer.parseInt(deliveryLocationIndex));
        builder.setDeliveryLocation(deliveryLocationBuilder.build());

        //delivery-serviceTime
        String deliveryServiceTime = shipmentConfig.getString("delivery.duration");
        if (deliveryServiceTime != null)
            builder.setDeliveryServiceTime(Double.parseDouble(deliveryServiceTime));

        //delivery-tw
        List<HierarchicalConfiguration> deliveryTWConfigs = shipmentConfig
                .configurationsAt("delivery.timeWindows.timeWindow");
        if (!deliveryTWConfigs.isEmpty()) {
            for (HierarchicalConfiguration dl_twConfig : deliveryTWConfigs) {
                builder.addDeliveryTimeWindow(
                        TimeWindow.newInstance(dl_twConfig.getDouble("start"), dl_twConfig.getDouble("end")));
            }
        }

        //read skills
        String skillString = shipmentConfig.getString("requiredSkills");
        if (skillString != null) {
            String cleaned = skillString.replaceAll("\\s", "");
            String[] skillTokens = cleaned.split("[,;]");
            for (String skill : skillTokens)
                builder.addRequiredSkill(skill.toLowerCase());
        }

        //build shipment
        Shipment shipment = builder.build();
        //         vrpBuilder.addJob(shipment);
        shipmentMap.put(shipment.getId(), shipment);
    }
}

From source file:jsprit.core.problem.io.VrpXMLReader.java

private void readShipments(XMLConfiguration config) {
    List<HierarchicalConfiguration> shipmentConfigs = config.configurationsAt("shipments.shipment");
    for (HierarchicalConfiguration shipmentConfig : shipmentConfigs) {
        String id = shipmentConfig.getString("[@id]");
        if (id == null)
            throw new IllegalStateException("shipment[@id] is missing.");

        String capacityString = shipmentConfig.getString("capacity-demand");
        boolean capacityDimensionsExist = shipmentConfig.containsKey("capacity-dimensions.dimension(0)");
        if (capacityString == null && !capacityDimensionsExist) {
            throw new IllegalStateException("capacity of shipment is not set. use 'capacity-dimensions'");
        }/*from w  w  w. j a va 2s.  co  m*/
        if (capacityString != null && capacityDimensionsExist) {
            throw new IllegalStateException(
                    "either use capacity or capacity-dimension, not both. prefer the use of 'capacity-dimensions' over 'capacity'.");
        }

        Shipment.Builder builder;
        if (capacityString != null) {
            builder = Shipment.Builder.newInstance(id).addSizeDimension(0, Integer.parseInt(capacityString));
        } else {
            builder = Shipment.Builder.newInstance(id);
            List<HierarchicalConfiguration> dimensionConfigs = shipmentConfig
                    .configurationsAt("capacity-dimensions.dimension");
            for (HierarchicalConfiguration dimension : dimensionConfigs) {
                Integer index = dimension.getInt("[@index]");
                Integer value = dimension.getInt("");
                builder.addSizeDimension(index, value);
            }
        }

        //name
        String name = shipmentConfig.getString("name");
        if (name != null)
            builder.setName(name);

        //pickup location
        //pickup-locationId
        Location.Builder pickupLocationBuilder = Location.Builder.newInstance();
        String pickupLocationId = shipmentConfig.getString("pickup.locationId");
        if (pickupLocationId == null)
            pickupLocationId = shipmentConfig.getString("pickup.location.id");
        if (pickupLocationId != null) {
            pickupLocationBuilder.setId(pickupLocationId);
        }

        //pickup-coord
        Coordinate pickupCoord = getCoord(shipmentConfig, "pickup.");
        if (pickupCoord == null)
            pickupCoord = getCoord(shipmentConfig, "pickup.location.");
        if (pickupCoord != null) {
            pickupLocationBuilder.setCoordinate(pickupCoord);
        }

        //pickup.location.index
        String pickupLocationIndex = shipmentConfig.getString("pickup.location.index");
        if (pickupLocationIndex != null)
            pickupLocationBuilder.setIndex(Integer.parseInt(pickupLocationIndex));
        builder.setPickupLocation(pickupLocationBuilder.build());

        //pickup-serviceTime
        String pickupServiceTime = shipmentConfig.getString("pickup.duration");
        if (pickupServiceTime != null)
            builder.setPickupServiceTime(Double.parseDouble(pickupServiceTime));

        //pickup-tw
        String pickupTWStart = shipmentConfig.getString("pickup.timeWindows.timeWindow(0).start");
        String pickupTWEnd = shipmentConfig.getString("pickup.timeWindows.timeWindow(0).end");
        if (pickupTWStart != null && pickupTWEnd != null) {
            TimeWindow pickupTW = TimeWindow.newInstance(Double.parseDouble(pickupTWStart),
                    Double.parseDouble(pickupTWEnd));
            builder.setPickupTimeWindow(pickupTW);
        }

        //delivery location
        //delivery-locationId
        Location.Builder deliveryLocationBuilder = Location.Builder.newInstance();
        String deliveryLocationId = shipmentConfig.getString("delivery.locationId");
        if (deliveryLocationId == null)
            deliveryLocationId = shipmentConfig.getString("delivery.location.id");
        if (deliveryLocationId != null) {
            deliveryLocationBuilder.setId(deliveryLocationId);
            //            builder.setDeliveryLocationId(deliveryLocationId);
        }

        //delivery-coord
        Coordinate deliveryCoord = getCoord(shipmentConfig, "delivery.");
        if (deliveryCoord == null)
            deliveryCoord = getCoord(shipmentConfig, "delivery.location.");
        if (deliveryCoord != null) {
            deliveryLocationBuilder.setCoordinate(deliveryCoord);
        }

        String deliveryLocationIndex = shipmentConfig.getString("delivery.location.index");
        if (deliveryLocationIndex != null)
            deliveryLocationBuilder.setIndex(Integer.parseInt(deliveryLocationIndex));
        builder.setDeliveryLocation(deliveryLocationBuilder.build());

        //delivery-serviceTime
        String deliveryServiceTime = shipmentConfig.getString("delivery.duration");
        if (deliveryServiceTime != null)
            builder.setDeliveryServiceTime(Double.parseDouble(deliveryServiceTime));

        //delivery-tw
        String delTWStart = shipmentConfig.getString("delivery.timeWindows.timeWindow(0).start");
        String delTWEnd = shipmentConfig.getString("delivery.timeWindows.timeWindow(0).end");
        if (delTWStart != null && delTWEnd != null) {
            TimeWindow delTW = TimeWindow.newInstance(Double.parseDouble(delTWStart),
                    Double.parseDouble(delTWEnd));
            builder.setDeliveryTimeWindow(delTW);
        }

        //read skills
        String skillString = shipmentConfig.getString("requiredSkills");
        if (skillString != null) {
            String cleaned = skillString.replaceAll("\\s", "");
            String[] skillTokens = cleaned.split("[,;]");
            for (String skill : skillTokens)
                builder.addRequiredSkill(skill.toLowerCase());
        }

        //build shipment
        Shipment shipment = builder.build();
        //         vrpBuilder.addJob(shipment);
        shipmentMap.put(shipment.getId(), shipment);
    }
}

From source file:jsprit.core.problem.io.VrpXMLReader.java

private void readVehiclesAndTheirTypes(XMLConfiguration vrpProblem) {

    //read vehicle-types
    Map<String, VehicleType> types = new HashMap<String, VehicleType>();
    List<HierarchicalConfiguration> typeConfigs = vrpProblem.configurationsAt("vehicleTypes.type");
    for (HierarchicalConfiguration typeConfig : typeConfigs) {
        String typeId = typeConfig.getString("id");
        if (typeId == null)
            throw new IllegalStateException("typeId is missing.");

        String capacityString = typeConfig.getString("capacity");
        boolean capacityDimensionsExist = typeConfig.containsKey("capacity-dimensions.dimension(0)");
        if (capacityString == null && !capacityDimensionsExist) {
            throw new IllegalStateException("capacity of type is not set. use 'capacity-dimensions'");
        }/* ww  w  .j  av  a2  s.c  o  m*/
        if (capacityString != null && capacityDimensionsExist) {
            throw new IllegalStateException(
                    "either use capacity or capacity-dimension, not both. prefer the use of 'capacity-dimensions' over 'capacity'.");
        }

        VehicleTypeImpl.Builder typeBuilder;
        if (capacityString != null) {
            typeBuilder = VehicleTypeImpl.Builder.newInstance(typeId).addCapacityDimension(0,
                    Integer.parseInt(capacityString));
        } else {
            typeBuilder = VehicleTypeImpl.Builder.newInstance(typeId);
            List<HierarchicalConfiguration> dimensionConfigs = typeConfig
                    .configurationsAt("capacity-dimensions.dimension");
            for (HierarchicalConfiguration dimension : dimensionConfigs) {
                Integer index = dimension.getInt("[@index]");
                Integer value = dimension.getInt("");
                typeBuilder.addCapacityDimension(index, value);
            }
        }
        Double fix = typeConfig.getDouble("costs.fixed");
        Double timeC = typeConfig.getDouble("costs.time");
        Double distC = typeConfig.getDouble("costs.distance");

        if (fix != null)
            typeBuilder.setFixedCost(fix);
        if (timeC != null)
            typeBuilder.setCostPerTime(timeC);
        if (distC != null)
            typeBuilder.setCostPerDistance(distC);
        VehicleType type = typeBuilder.build();
        String id = type.getTypeId();
        types.put(id, type);
    }

    //read vehicles
    List<HierarchicalConfiguration> vehicleConfigs = vrpProblem.configurationsAt("vehicles.vehicle");
    boolean doNotWarnAgain = false;
    for (HierarchicalConfiguration vehicleConfig : vehicleConfigs) {
        String vehicleId = vehicleConfig.getString("id");
        if (vehicleId == null)
            throw new IllegalStateException("vehicleId is missing.");
        Builder builder = VehicleImpl.Builder.newInstance(vehicleId);
        String typeId = vehicleConfig.getString("typeId");
        if (typeId == null)
            throw new IllegalStateException("typeId is missing.");
        String vType = vehicleConfig.getString("[@type]");
        if (vType != null) {
            if (vType.equals("penalty")) {
                typeId += "_penalty";
            }
        }
        VehicleType type = types.get(typeId);
        if (type == null)
            throw new IllegalStateException("vehicleType with typeId " + typeId + " is missing.");
        builder.setType(type);

        //read startlocation
        Location.Builder startLocationBuilder = Location.Builder.newInstance();
        String locationId = vehicleConfig.getString("location.id");
        if (locationId == null) {
            locationId = vehicleConfig.getString("startLocation.id");
        }
        startLocationBuilder.setId(locationId);
        String coordX = vehicleConfig.getString("location.coord[@x]");
        String coordY = vehicleConfig.getString("location.coord[@y]");
        if (coordX == null || coordY == null) {
            coordX = vehicleConfig.getString("startLocation.coord[@x]");
            coordY = vehicleConfig.getString("startLocation.coord[@y]");
        }
        if (coordX == null || coordY == null) {
            if (!doNotWarnAgain) {
                logger.debug("location.coord is missing. will not warn you again.");
                doNotWarnAgain = true;
            }
        } else {
            Coordinate coordinate = Coordinate.newInstance(Double.parseDouble(coordX),
                    Double.parseDouble(coordY));
            startLocationBuilder.setCoordinate(coordinate);
        }
        String index = vehicleConfig.getString("startLocation.index");
        if (index == null)
            index = vehicleConfig.getString("location.index");
        if (index != null) {
            startLocationBuilder.setIndex(Integer.parseInt(index));
        }
        builder.setStartLocation(startLocationBuilder.build());

        //read endlocation
        Location.Builder endLocationBuilder = Location.Builder.newInstance();
        boolean hasEndLocation = false;
        String endLocationId = vehicleConfig.getString("endLocation.id");
        if (endLocationId != null) {
            hasEndLocation = true;
            endLocationBuilder.setId(endLocationId);
        }
        String endCoordX = vehicleConfig.getString("endLocation.coord[@x]");
        String endCoordY = vehicleConfig.getString("endLocation.coord[@y]");
        if (endCoordX == null || endCoordY == null) {
            if (!doNotWarnAgain) {
                logger.debug("endLocation.coord is missing. will not warn you again.");
                doNotWarnAgain = true;
            }
        } else {
            Coordinate coordinate = Coordinate.newInstance(Double.parseDouble(endCoordX),
                    Double.parseDouble(endCoordY));
            hasEndLocation = true;
            endLocationBuilder.setCoordinate(coordinate);
        }
        String endLocationIndex = vehicleConfig.getString("endLocation.index");
        if (endLocationIndex != null) {
            hasEndLocation = true;
            endLocationBuilder.setIndex(Integer.parseInt(endLocationIndex));
        }
        if (hasEndLocation)
            builder.setEndLocation(endLocationBuilder.build());

        //read timeSchedule
        String start = vehicleConfig.getString("timeSchedule.start");
        String end = vehicleConfig.getString("timeSchedule.end");
        if (start != null)
            builder.setEarliestStart(Double.parseDouble(start));
        if (end != null)
            builder.setLatestArrival(Double.parseDouble(end));

        //read return2depot
        String returnToDepot = vehicleConfig.getString("returnToDepot");
        if (returnToDepot != null) {
            builder.setReturnToDepot(vehicleConfig.getBoolean("returnToDepot"));
        }

        //read skills
        String skillString = vehicleConfig.getString("skills");
        if (skillString != null) {
            String cleaned = skillString.replaceAll("\\s", "");
            String[] skillTokens = cleaned.split("[,;]");
            for (String skill : skillTokens)
                builder.addSkill(skill.toLowerCase());
        }

        //build vehicle
        VehicleImpl vehicle = builder.build();
        vrpBuilder.addVehicle(vehicle);
        vehicleMap.put(vehicleId, vehicle);
    }

}

From source file:com.graphhopper.jsprit.core.problem.io.VrpXMLReader.java

private void readVehiclesAndTheirTypes(XMLConfiguration vrpProblem) {

    //read vehicle-types
    Map<String, VehicleType> types = new HashMap<String, VehicleType>();
    List<HierarchicalConfiguration> typeConfigs = vrpProblem.configurationsAt("vehicleTypes.type");
    for (HierarchicalConfiguration typeConfig : typeConfigs) {
        String typeId = typeConfig.getString("id");
        if (typeId == null)
            throw new IllegalStateException("typeId is missing.");

        String capacityString = typeConfig.getString("capacity");
        boolean capacityDimensionsExist = typeConfig.containsKey("capacity-dimensions.dimension(0)");
        if (capacityString == null && !capacityDimensionsExist) {
            throw new IllegalStateException("capacity of type is not set. use 'capacity-dimensions'");
        }//  w ww.  j  a va  2 s. co  m
        if (capacityString != null && capacityDimensionsExist) {
            throw new IllegalStateException(
                    "either use capacity or capacity-dimension, not both. prefer the use of 'capacity-dimensions' over 'capacity'.");
        }

        VehicleTypeImpl.Builder typeBuilder;
        if (capacityString != null) {
            typeBuilder = VehicleTypeImpl.Builder.newInstance(typeId).addCapacityDimension(0,
                    Integer.parseInt(capacityString));
        } else {
            typeBuilder = VehicleTypeImpl.Builder.newInstance(typeId);
            List<HierarchicalConfiguration> dimensionConfigs = typeConfig
                    .configurationsAt("capacity-dimensions.dimension");
            for (HierarchicalConfiguration dimension : dimensionConfigs) {
                Integer index = dimension.getInt("[@index]");
                Integer value = dimension.getInt("");
                typeBuilder.addCapacityDimension(index, value);
            }
        }

        Double fix = typeConfig.getDouble("costs.fixed");
        Double timeC = typeConfig.getDouble("costs.time");
        Double distC = typeConfig.getDouble("costs.distance");

        if (fix != null)
            typeBuilder.setFixedCost(fix);
        if (timeC != null)
            typeBuilder.setCostPerTime(timeC);
        if (distC != null)
            typeBuilder.setCostPerDistance(distC);
        VehicleType type = typeBuilder.build();
        String id = type.getTypeId();
        types.put(id, type);
    }

    //read vehicles
    List<HierarchicalConfiguration> vehicleConfigs = vrpProblem.configurationsAt("vehicles.vehicle");
    boolean doNotWarnAgain = false;
    for (HierarchicalConfiguration vehicleConfig : vehicleConfigs) {
        String vehicleId = vehicleConfig.getString("id");
        if (vehicleId == null)
            throw new IllegalStateException("vehicleId is missing.");
        Builder builder = VehicleImpl.Builder.newInstance(vehicleId);
        String typeId = vehicleConfig.getString("typeId");
        if (typeId == null)
            throw new IllegalStateException("typeId is missing.");
        String vType = vehicleConfig.getString("[@type]");
        if (vType != null) {
            if (vType.equals("penalty")) {
                typeId += "_penalty";
            }
        }
        VehicleType type = types.get(typeId);
        if (type == null)
            throw new IllegalStateException("vehicleType with typeId " + typeId + " is missing.");
        builder.setType(type);

        //read startlocation
        Location.Builder startLocationBuilder = Location.Builder.newInstance();
        String locationId = vehicleConfig.getString("location.id");
        if (locationId == null) {
            locationId = vehicleConfig.getString("startLocation.id");
        }
        startLocationBuilder.setId(locationId);
        String coordX = vehicleConfig.getString("location.coord[@x]");
        String coordY = vehicleConfig.getString("location.coord[@y]");
        if (coordX == null || coordY == null) {
            coordX = vehicleConfig.getString("startLocation.coord[@x]");
            coordY = vehicleConfig.getString("startLocation.coord[@y]");
        }
        if (coordX == null || coordY == null) {
            if (!doNotWarnAgain) {
                logger.debug("location.coord is missing. will not warn you again.");
                doNotWarnAgain = true;
            }
        } else {
            Coordinate coordinate = Coordinate.newInstance(Double.parseDouble(coordX),
                    Double.parseDouble(coordY));
            startLocationBuilder.setCoordinate(coordinate);
        }
        String index = vehicleConfig.getString("startLocation.index");
        if (index == null)
            index = vehicleConfig.getString("location.index");
        if (index != null) {
            startLocationBuilder.setIndex(Integer.parseInt(index));
        }
        builder.setStartLocation(startLocationBuilder.build());

        //read endlocation
        Location.Builder endLocationBuilder = Location.Builder.newInstance();
        boolean hasEndLocation = false;
        String endLocationId = vehicleConfig.getString("endLocation.id");
        if (endLocationId != null) {
            hasEndLocation = true;
            endLocationBuilder.setId(endLocationId);
        }
        String endCoordX = vehicleConfig.getString("endLocation.coord[@x]");
        String endCoordY = vehicleConfig.getString("endLocation.coord[@y]");
        if (endCoordX == null || endCoordY == null) {
            if (!doNotWarnAgain) {
                logger.debug("endLocation.coord is missing. will not warn you again.");
                doNotWarnAgain = true;
            }
        } else {
            Coordinate coordinate = Coordinate.newInstance(Double.parseDouble(endCoordX),
                    Double.parseDouble(endCoordY));
            hasEndLocation = true;
            endLocationBuilder.setCoordinate(coordinate);
        }
        String endLocationIndex = vehicleConfig.getString("endLocation.index");
        if (endLocationIndex != null) {
            hasEndLocation = true;
            endLocationBuilder.setIndex(Integer.parseInt(endLocationIndex));
        }
        if (hasEndLocation)
            builder.setEndLocation(endLocationBuilder.build());

        //read timeSchedule
        String start = vehicleConfig.getString("timeSchedule.start");
        String end = vehicleConfig.getString("timeSchedule.end");
        if (start != null)
            builder.setEarliestStart(Double.parseDouble(start));
        if (end != null)
            builder.setLatestArrival(Double.parseDouble(end));

        //read return2depot
        String returnToDepot = vehicleConfig.getString("returnToDepot");
        if (returnToDepot != null) {
            builder.setReturnToDepot(vehicleConfig.getBoolean("returnToDepot"));
        }

        //read skills
        String skillString = vehicleConfig.getString("skills");
        if (skillString != null) {
            String cleaned = skillString.replaceAll("\\s", "");
            String[] skillTokens = cleaned.split("[,;]");
            for (String skill : skillTokens)
                builder.addSkill(skill.toLowerCase());
        }

        // read break
        List<HierarchicalConfiguration> breakTWConfigs = vehicleConfig
                .configurationsAt("break.timeWindows.timeWindow");
        if (!breakTWConfigs.isEmpty()) {
            String breakDurationString = vehicleConfig.getString("breaks.duration");
            Break.Builder current_break = Break.Builder.newInstance(vehicleId);
            current_break.setServiceTime(Double.parseDouble(breakDurationString));
            for (HierarchicalConfiguration twConfig : breakTWConfigs) {
                current_break.addTimeWindow(
                        TimeWindow.newInstance(twConfig.getDouble("start"), twConfig.getDouble("end")));
            }
            builder.setBreak(current_break.build());
        }

        //build vehicle
        VehicleImpl vehicle = builder.build();
        vrpBuilder.addVehicle(vehicle);
        vehicleMap.put(vehicleId, vehicle);
    }

}

From source file:com.graphhopper.jsprit.io.problem.VrpXMLReader.java

private void readShipments(XMLConfiguration config) {
    List<HierarchicalConfiguration> shipmentConfigs = config.configurationsAt("shipments.shipment");
    for (HierarchicalConfiguration shipmentConfig : shipmentConfigs) {
        String id = shipmentConfig.getString("[@id]");
        if (id == null)
            throw new IllegalArgumentException("shipment[@id] is missing.");

        String capacityString = shipmentConfig.getString("capacity-demand");
        boolean capacityDimensionsExist = shipmentConfig.containsKey("capacity-dimensions.dimension(0)");
        if (capacityString == null && !capacityDimensionsExist) {
            throw new IllegalArgumentException("capacity of shipment is not set. use 'capacity-dimensions'");
        }/*from ww  w . j  av  a  2  s.  c om*/
        if (capacityString != null && capacityDimensionsExist) {
            throw new IllegalArgumentException(
                    "either use capacity or capacity-dimension, not both. prefer the use of 'capacity-dimensions' over 'capacity'.");
        }

        Shipment.Builder builder;
        if (capacityString != null) {
            builder = Shipment.Builder.newInstance(id).addSizeDimension(0, Integer.parseInt(capacityString));
        } else {
            builder = Shipment.Builder.newInstance(id);
            List<HierarchicalConfiguration> dimensionConfigs = shipmentConfig
                    .configurationsAt("capacity-dimensions.dimension");
            for (HierarchicalConfiguration dimension : dimensionConfigs) {
                Integer index = dimension.getInt("[@index]");
                Integer value = dimension.getInt("");
                builder.addSizeDimension(index, value);
            }
        }

        //name
        String name = shipmentConfig.getString("name");
        if (name != null)
            builder.setName(name);

        //pickup location
        //pickup-locationId
        Location.Builder pickupLocationBuilder = Location.Builder.newInstance();
        String pickupLocationId = shipmentConfig.getString("pickup.locationId");
        if (pickupLocationId == null)
            pickupLocationId = shipmentConfig.getString("pickup.location.id");
        if (pickupLocationId != null) {
            pickupLocationBuilder.setId(pickupLocationId);
        }

        //pickup-coord
        Coordinate pickupCoord = getCoord(shipmentConfig, "pickup.");
        if (pickupCoord == null)
            pickupCoord = getCoord(shipmentConfig, "pickup.location.");
        if (pickupCoord != null) {
            pickupLocationBuilder.setCoordinate(pickupCoord);
        }

        //pickup.location.index
        String pickupLocationIndex = shipmentConfig.getString("pickup.location.index");
        if (pickupLocationIndex != null)
            pickupLocationBuilder.setIndex(Integer.parseInt(pickupLocationIndex));
        builder.setPickupLocation(pickupLocationBuilder.build());

        //pickup-serviceTime
        String pickupServiceTime = shipmentConfig.getString("pickup.duration");
        if (pickupServiceTime != null)
            builder.setPickupServiceTime(Double.parseDouble(pickupServiceTime));

        //pickup-tw
        List<HierarchicalConfiguration> pickupTWConfigs = shipmentConfig
                .configurationsAt("pickup.timeWindows.timeWindow");
        if (!pickupTWConfigs.isEmpty()) {
            for (HierarchicalConfiguration pu_twConfig : pickupTWConfigs) {
                builder.addPickupTimeWindow(
                        TimeWindow.newInstance(pu_twConfig.getDouble("start"), pu_twConfig.getDouble("end")));
            }
        }

        //delivery location
        //delivery-locationId
        Location.Builder deliveryLocationBuilder = Location.Builder.newInstance();
        String deliveryLocationId = shipmentConfig.getString("delivery.locationId");
        if (deliveryLocationId == null)
            deliveryLocationId = shipmentConfig.getString("delivery.location.id");
        if (deliveryLocationId != null) {
            deliveryLocationBuilder.setId(deliveryLocationId);
            //            builder.setDeliveryLocationId(deliveryLocationId);
        }

        //delivery-coord
        Coordinate deliveryCoord = getCoord(shipmentConfig, "delivery.");
        if (deliveryCoord == null)
            deliveryCoord = getCoord(shipmentConfig, "delivery.location.");
        if (deliveryCoord != null) {
            deliveryLocationBuilder.setCoordinate(deliveryCoord);
        }

        String deliveryLocationIndex = shipmentConfig.getString("delivery.location.index");
        if (deliveryLocationIndex != null)
            deliveryLocationBuilder.setIndex(Integer.parseInt(deliveryLocationIndex));
        builder.setDeliveryLocation(deliveryLocationBuilder.build());

        //delivery-serviceTime
        String deliveryServiceTime = shipmentConfig.getString("delivery.duration");
        if (deliveryServiceTime != null)
            builder.setDeliveryServiceTime(Double.parseDouble(deliveryServiceTime));

        //delivery-tw
        List<HierarchicalConfiguration> deliveryTWConfigs = shipmentConfig
                .configurationsAt("delivery.timeWindows.timeWindow");
        if (!deliveryTWConfigs.isEmpty()) {
            for (HierarchicalConfiguration dl_twConfig : deliveryTWConfigs) {
                builder.addDeliveryTimeWindow(
                        TimeWindow.newInstance(dl_twConfig.getDouble("start"), dl_twConfig.getDouble("end")));
            }
        }

        //read skills
        String skillString = shipmentConfig.getString("requiredSkills");
        if (skillString != null) {
            String cleaned = skillString.replaceAll("\\s", "");
            String[] skillTokens = cleaned.split("[,;]");
            for (String skill : skillTokens)
                builder.addRequiredSkill(skill.toLowerCase());
        }

        //build shipment
        Shipment shipment = builder.build();
        //         vrpBuilder.addJob(shipment);
        shipmentMap.put(shipment.getId(), shipment);
    }
}

From source file:com.graphhopper.jsprit.io.problem.VrpXMLReader.java

private void readVehiclesAndTheirTypes(XMLConfiguration vrpProblem) {

    //read vehicle-types
    Map<String, VehicleType> types = new HashMap<String, VehicleType>();
    List<HierarchicalConfiguration> typeConfigs = vrpProblem.configurationsAt("vehicleTypes.type");
    for (HierarchicalConfiguration typeConfig : typeConfigs) {
        String typeId = typeConfig.getString("id");
        if (typeId == null)
            throw new IllegalArgumentException("typeId is missing.");

        String capacityString = typeConfig.getString("capacity");
        boolean capacityDimensionsExist = typeConfig.containsKey("capacity-dimensions.dimension(0)");
        if (capacityString == null && !capacityDimensionsExist) {
            throw new IllegalArgumentException("capacity of type is not set. use 'capacity-dimensions'");
        }//  w  ww .j av a2  s. c om
        if (capacityString != null && capacityDimensionsExist) {
            throw new IllegalArgumentException(
                    "either use capacity or capacity-dimension, not both. prefer the use of 'capacity-dimensions' over 'capacity'.");
        }

        VehicleTypeImpl.Builder typeBuilder;
        if (capacityString != null) {
            typeBuilder = VehicleTypeImpl.Builder.newInstance(typeId).addCapacityDimension(0,
                    Integer.parseInt(capacityString));
        } else {
            typeBuilder = VehicleTypeImpl.Builder.newInstance(typeId);
            List<HierarchicalConfiguration> dimensionConfigs = typeConfig
                    .configurationsAt("capacity-dimensions.dimension");
            for (HierarchicalConfiguration dimension : dimensionConfigs) {
                Integer index = dimension.getInt("[@index]");
                Integer value = dimension.getInt("");
                typeBuilder.addCapacityDimension(index, value);
            }
        }

        Double fix = typeConfig.getDouble("costs.fixed");
        Double timeC = typeConfig.getDouble("costs.time");
        Double distC = typeConfig.getDouble("costs.distance");
        if (typeConfig.containsKey("costs.service")) {
            Double serviceC = typeConfig.getDouble("costs.service");
            if (serviceC != null)
                typeBuilder.setCostPerServiceTime(serviceC);
        }

        if (typeConfig.containsKey("costs.wait")) {
            Double waitC = typeConfig.getDouble("costs.wait");
            if (waitC != null)
                typeBuilder.setCostPerWaitingTime(waitC);
        }

        if (fix != null)
            typeBuilder.setFixedCost(fix);
        if (timeC != null)
            typeBuilder.setCostPerTransportTime(timeC);
        if (distC != null)
            typeBuilder.setCostPerDistance(distC);
        VehicleType type = typeBuilder.build();
        String id = type.getTypeId();
        types.put(id, type);
    }

    //read vehicles
    List<HierarchicalConfiguration> vehicleConfigs = vrpProblem.configurationsAt("vehicles.vehicle");
    boolean doNotWarnAgain = false;
    for (HierarchicalConfiguration vehicleConfig : vehicleConfigs) {
        String vehicleId = vehicleConfig.getString("id");
        if (vehicleId == null)
            throw new IllegalArgumentException("vehicleId is missing.");
        Builder builder = VehicleImpl.Builder.newInstance(vehicleId);
        String typeId = vehicleConfig.getString("typeId");
        if (typeId == null)
            throw new IllegalArgumentException("typeId is missing.");
        String vType = vehicleConfig.getString("[@type]");
        if (vType != null) {
            if (vType.equals("penalty")) {
                typeId += "_penalty";
            }
        }
        VehicleType type = types.get(typeId);
        if (type == null)
            throw new IllegalArgumentException("vehicleType with typeId " + typeId + " is missing.");
        builder.setType(type);

        //read startlocation
        Location.Builder startLocationBuilder = Location.Builder.newInstance();
        String locationId = vehicleConfig.getString("location.id");
        if (locationId == null) {
            locationId = vehicleConfig.getString("startLocation.id");
        }
        startLocationBuilder.setId(locationId);
        String coordX = vehicleConfig.getString("location.coord[@x]");
        String coordY = vehicleConfig.getString("location.coord[@y]");
        if (coordX == null || coordY == null) {
            coordX = vehicleConfig.getString("startLocation.coord[@x]");
            coordY = vehicleConfig.getString("startLocation.coord[@y]");
        }
        if (coordX == null || coordY == null) {
            if (!doNotWarnAgain) {
                logger.debug("location.coord is missing. will not warn you again.");
                doNotWarnAgain = true;
            }
        } else {
            Coordinate coordinate = Coordinate.newInstance(Double.parseDouble(coordX),
                    Double.parseDouble(coordY));
            startLocationBuilder.setCoordinate(coordinate);
        }
        String index = vehicleConfig.getString("startLocation.index");
        if (index == null)
            index = vehicleConfig.getString("location.index");
        if (index != null) {
            startLocationBuilder.setIndex(Integer.parseInt(index));
        }
        builder.setStartLocation(startLocationBuilder.build());

        //read endlocation
        Location.Builder endLocationBuilder = Location.Builder.newInstance();
        boolean hasEndLocation = false;
        String endLocationId = vehicleConfig.getString("endLocation.id");
        if (endLocationId != null) {
            hasEndLocation = true;
            endLocationBuilder.setId(endLocationId);
        }
        String endCoordX = vehicleConfig.getString("endLocation.coord[@x]");
        String endCoordY = vehicleConfig.getString("endLocation.coord[@y]");
        if (endCoordX == null || endCoordY == null) {
            if (!doNotWarnAgain) {
                logger.debug("endLocation.coord is missing. will not warn you again.");
                doNotWarnAgain = true;
            }
        } else {
            Coordinate coordinate = Coordinate.newInstance(Double.parseDouble(endCoordX),
                    Double.parseDouble(endCoordY));
            hasEndLocation = true;
            endLocationBuilder.setCoordinate(coordinate);
        }
        String endLocationIndex = vehicleConfig.getString("endLocation.index");
        if (endLocationIndex != null) {
            hasEndLocation = true;
            endLocationBuilder.setIndex(Integer.parseInt(endLocationIndex));
        }
        if (hasEndLocation)
            builder.setEndLocation(endLocationBuilder.build());

        //read timeSchedule
        String start = vehicleConfig.getString("timeSchedule.start");
        String end = vehicleConfig.getString("timeSchedule.end");
        if (start != null)
            builder.setEarliestStart(Double.parseDouble(start));
        if (end != null)
            builder.setLatestArrival(Double.parseDouble(end));

        //read return2depot
        String returnToDepot = vehicleConfig.getString("returnToDepot");
        if (returnToDepot != null) {
            builder.setReturnToDepot(vehicleConfig.getBoolean("returnToDepot"));
        }

        //read skills
        String skillString = vehicleConfig.getString("skills");
        if (skillString != null) {
            String cleaned = skillString.replaceAll("\\s", "");
            String[] skillTokens = cleaned.split("[,;]");
            for (String skill : skillTokens)
                builder.addSkill(skill.toLowerCase());
        }

        // read break
        List<HierarchicalConfiguration> breakTWConfigs = vehicleConfig
                .configurationsAt("breaks.timeWindows.timeWindow");
        if (!breakTWConfigs.isEmpty()) {
            String breakDurationString = vehicleConfig.getString("breaks.duration");
            Break.Builder current_break = Break.Builder.newInstance(vehicleId);
            current_break.setServiceTime(Double.parseDouble(breakDurationString));
            for (HierarchicalConfiguration twConfig : breakTWConfigs) {
                current_break.addTimeWindow(
                        TimeWindow.newInstance(twConfig.getDouble("start"), twConfig.getDouble("end")));
            }
            builder.setBreak(current_break.build());
        }

        //build vehicle
        VehicleImpl vehicle = builder.build();
        vrpBuilder.addVehicle(vehicle);
        vehicleMap.put(vehicleId, vehicle);
    }

}

From source file:com.graphhopper.jsprit.core.problem.io.VrpXMLReader.java

private void readServices(XMLConfiguration vrpProblem) {
    List<HierarchicalConfiguration> serviceConfigs = vrpProblem.configurationsAt("services.service");
    for (HierarchicalConfiguration serviceConfig : serviceConfigs) {
        String id = serviceConfig.getString("[@id]");
        if (id == null)
            throw new IllegalStateException("service[@id] is missing.");
        String type = serviceConfig.getString("[@type]");
        if (type == null)
            type = "service";

        String capacityString = serviceConfig.getString("capacity-demand");
        boolean capacityDimensionsExist = serviceConfig.containsKey("capacity-dimensions.dimension(0)");
        if (capacityString == null && !capacityDimensionsExist) {
            throw new IllegalStateException("capacity of service is not set. use 'capacity-dimensions'");
        }//from   w w w .  j a  va 2s . c  o  m
        if (capacityString != null && capacityDimensionsExist) {
            throw new IllegalStateException(
                    "either use capacity or capacity-dimension, not both. prefer the use of 'capacity-dimensions' over 'capacity'.");
        }

        Service.Builder builder;
        if (capacityString != null) {
            builder = serviceBuilderFactory.createBuilder(type, id, Integer.parseInt(capacityString));
        } else {
            builder = serviceBuilderFactory.createBuilder(type, id, null);
            List<HierarchicalConfiguration> dimensionConfigs = serviceConfig
                    .configurationsAt("capacity-dimensions.dimension");
            for (HierarchicalConfiguration dimension : dimensionConfigs) {
                Integer index = dimension.getInt("[@index]");
                Integer value = dimension.getInt("");
                builder.addSizeDimension(index, value);
            }
        }

        //name
        String name = serviceConfig.getString("name");
        if (name != null)
            builder.setName(name);

        //location
        Location.Builder locationBuilder = Location.Builder.newInstance();
        String serviceLocationId = serviceConfig.getString("locationId");
        if (serviceLocationId == null) {
            serviceLocationId = serviceConfig.getString("location.id");
        }
        if (serviceLocationId != null)
            locationBuilder.setId(serviceLocationId);

        Coordinate serviceCoord = getCoord(serviceConfig, "");
        if (serviceCoord == null)
            serviceCoord = getCoord(serviceConfig, "location.");
        if (serviceCoord != null) {
            locationBuilder.setCoordinate(serviceCoord);
        }

        String locationIndex = serviceConfig.getString("location.index");
        if (locationIndex != null)
            locationBuilder.setIndex(Integer.parseInt(locationIndex));
        builder.setLocation(locationBuilder.build());

        if (serviceConfig.containsKey("duration")) {
            builder.setServiceTime(serviceConfig.getDouble("duration"));
        }
        List<HierarchicalConfiguration> deliveryTWConfigs = serviceConfig
                .configurationsAt("timeWindows.timeWindow");
        if (!deliveryTWConfigs.isEmpty()) {
            for (HierarchicalConfiguration twConfig : deliveryTWConfigs) {
                builder.addTimeWindow(
                        TimeWindow.newInstance(twConfig.getDouble("start"), twConfig.getDouble("end")));
            }
        }

        //read skills
        String skillString = serviceConfig.getString("requiredSkills");
        if (skillString != null) {
            String cleaned = skillString.replaceAll("\\s", "");
            String[] skillTokens = cleaned.split("[,;]");
            for (String skill : skillTokens)
                builder.addRequiredSkill(skill.toLowerCase());
        }

        //build service
        Service service = builder.build();
        serviceMap.put(service.getId(), service);
        //         vrpBuilder.addJob(service);

    }
}

From source file:jsprit.core.problem.io.VrpXMLReader.java

private void readServices(XMLConfiguration vrpProblem) {
    List<HierarchicalConfiguration> serviceConfigs = vrpProblem.configurationsAt("services.service");
    for (HierarchicalConfiguration serviceConfig : serviceConfigs) {
        String id = serviceConfig.getString("[@id]");
        if (id == null)
            throw new IllegalStateException("service[@id] is missing.");
        String type = serviceConfig.getString("[@type]");
        if (type == null)
            type = "service";

        String capacityString = serviceConfig.getString("capacity-demand");
        boolean capacityDimensionsExist = serviceConfig.containsKey("capacity-dimensions.dimension(0)");
        if (capacityString == null && !capacityDimensionsExist) {
            throw new IllegalStateException("capacity of service is not set. use 'capacity-dimensions'");
        }/*from w  w w  .  ja  v  a  2  s. c o m*/
        if (capacityString != null && capacityDimensionsExist) {
            throw new IllegalStateException(
                    "either use capacity or capacity-dimension, not both. prefer the use of 'capacity-dimensions' over 'capacity'.");
        }

        Service.Builder builder;
        if (capacityString != null) {
            builder = serviceBuilderFactory.createBuilder(type, id, Integer.parseInt(capacityString));
        } else {
            builder = serviceBuilderFactory.createBuilder(type, id, null);
            List<HierarchicalConfiguration> dimensionConfigs = serviceConfig
                    .configurationsAt("capacity-dimensions.dimension");
            for (HierarchicalConfiguration dimension : dimensionConfigs) {
                Integer index = dimension.getInt("[@index]");
                Integer value = dimension.getInt("");
                builder.addSizeDimension(index, value);
            }
        }

        //name
        String name = serviceConfig.getString("name");
        if (name != null)
            builder.setName(name);

        //location
        Location.Builder locationBuilder = Location.Builder.newInstance();
        String serviceLocationId = serviceConfig.getString("locationId");
        if (serviceLocationId == null) {
            serviceLocationId = serviceConfig.getString("location.id");
        }
        if (serviceLocationId != null)
            locationBuilder.setId(serviceLocationId);

        Coordinate serviceCoord = getCoord(serviceConfig, "");
        if (serviceCoord == null)
            serviceCoord = getCoord(serviceConfig, "location.");
        if (serviceCoord != null) {
            locationBuilder.setCoordinate(serviceCoord);
        }

        String locationIndex = serviceConfig.getString("location.index");
        if (locationIndex != null)
            locationBuilder.setIndex(Integer.parseInt(locationIndex));
        builder.setLocation(locationBuilder.build());

        if (serviceConfig.containsKey("duration")) {
            builder.setServiceTime(serviceConfig.getDouble("duration"));
        }
        List<HierarchicalConfiguration> deliveryTWConfigs = serviceConfig
                .configurationsAt("timeWindows.timeWindow");
        if (!deliveryTWConfigs.isEmpty()) {
            for (HierarchicalConfiguration twConfig : deliveryTWConfigs) {
                builder.setTimeWindow(
                        TimeWindow.newInstance(twConfig.getDouble("start"), twConfig.getDouble("end")));
            }
        }

        //read skills
        String skillString = serviceConfig.getString("requiredSkills");
        if (skillString != null) {
            String cleaned = skillString.replaceAll("\\s", "");
            String[] skillTokens = cleaned.split("[,;]");
            for (String skill : skillTokens)
                builder.addRequiredSkill(skill.toLowerCase());
        }

        //build service
        Service service = builder.build();
        serviceMap.put(service.getId(), service);
        //         vrpBuilder.addJob(service);

    }
}

From source file:com.graphhopper.jsprit.io.problem.VrpXMLReader.java

private void readServices(XMLConfiguration vrpProblem) {
    List<HierarchicalConfiguration> serviceConfigs = vrpProblem.configurationsAt("services.service");
    for (HierarchicalConfiguration serviceConfig : serviceConfigs) {
        String id = serviceConfig.getString("[@id]");
        if (id == null)
            throw new IllegalArgumentException("service[@id] is missing.");
        String type = serviceConfig.getString("[@type]");
        if (type == null)
            type = "service";

        String capacityString = serviceConfig.getString("capacity-demand");
        boolean capacityDimensionsExist = serviceConfig.containsKey("capacity-dimensions.dimension(0)");
        if (capacityString == null && !capacityDimensionsExist) {
            throw new IllegalArgumentException("capacity of service is not set. use 'capacity-dimensions'");
        }//from w w  w . ja v  a 2 s  .com
        if (capacityString != null && capacityDimensionsExist) {
            throw new IllegalArgumentException(
                    "either use capacity or capacity-dimension, not both. prefer the use of 'capacity-dimensions' over 'capacity'.");
        }

        Service.Builder builder;
        if (capacityString != null) {
            builder = serviceBuilderFactory.createBuilder(type, id, Integer.parseInt(capacityString));
        } else {
            builder = serviceBuilderFactory.createBuilder(type, id, null);
            List<HierarchicalConfiguration> dimensionConfigs = serviceConfig
                    .configurationsAt("capacity-dimensions.dimension");
            for (HierarchicalConfiguration dimension : dimensionConfigs) {
                Integer index = dimension.getInt("[@index]");
                Integer value = dimension.getInt("");
                builder.addSizeDimension(index, value);
            }
        }

        //name
        String name = serviceConfig.getString("name");
        if (name != null)
            builder.setName(name);

        //location
        Location.Builder locationBuilder = Location.Builder.newInstance();
        String serviceLocationId = serviceConfig.getString("locationId");
        if (serviceLocationId == null) {
            serviceLocationId = serviceConfig.getString("location.id");
        }
        if (serviceLocationId != null)
            locationBuilder.setId(serviceLocationId);

        Coordinate serviceCoord = getCoord(serviceConfig, "");
        if (serviceCoord == null)
            serviceCoord = getCoord(serviceConfig, "location.");
        if (serviceCoord != null) {
            locationBuilder.setCoordinate(serviceCoord);
        }

        String locationIndex = serviceConfig.getString("location.index");
        if (locationIndex != null)
            locationBuilder.setIndex(Integer.parseInt(locationIndex));
        builder.setLocation(locationBuilder.build());

        if (serviceConfig.containsKey("duration")) {
            builder.setServiceTime(serviceConfig.getDouble("duration"));
        }
        List<HierarchicalConfiguration> deliveryTWConfigs = serviceConfig
                .configurationsAt("timeWindows.timeWindow");
        if (!deliveryTWConfigs.isEmpty()) {
            for (HierarchicalConfiguration twConfig : deliveryTWConfigs) {
                builder.addTimeWindow(
                        TimeWindow.newInstance(twConfig.getDouble("start"), twConfig.getDouble("end")));
            }
        }

        //read skills
        String skillString = serviceConfig.getString("requiredSkills");
        if (skillString != null) {
            String cleaned = skillString.replaceAll("\\s", "");
            String[] skillTokens = cleaned.split("[,;]");
            for (String skill : skillTokens)
                builder.addRequiredSkill(skill.toLowerCase());
        }

        //build service
        Service service = builder.build();
        serviceMap.put(service.getId(), service);
        //         vrpBuilder.addJob(service);

    }
}

From source file:com.bytelightning.opensource.pokerface.PokerFace.java

/**
 * Configures all the needed components, but does not actually start the server.
 * @param config   Contains all information needed to fully wire up the http, https, and httpclient components of this reverse proxy.
 * @throws Exception   Yeah, a lot can go wrong here, but at least it will be caught immediately :-)
 *//*from w  w w.  j  a va 2 s .co m*/
public void config(HierarchicalConfiguration config) throws Exception {
    List<HierarchicalConfiguration> lconf;
    HttpAsyncRequester executor = null;
    BasicNIOConnPool connPool = null;
    ObjectPool<ByteBuffer> byteBufferPool = null;
    LinkedHashMap<String, TargetDescriptor> mappings = null;
    ConcurrentMap<String, HttpHost> hosts = null;

    handlerRegistry = new UriHttpAsyncRequestHandlerMapper();

    // Initialize the keystore (if one was specified)
    KeyStore keystore = null;
    char[] keypass = null;
    String keystoreUri = config.getString("keystore");
    if ((keystoreUri != null) && (keystoreUri.trim().length() > 0)) {
        Path keystorePath = Utils.MakePath(keystoreUri);
        if (!Files.exists(keystorePath))
            throw new ConfigurationException("Keystore does not exist.");
        if (Files.isDirectory(keystorePath))
            throw new ConfigurationException("Keystore is not a file");
        String storepass = config.getString("storepass");
        if ((storepass != null) && "null".equals(storepass))
            storepass = null;
        keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (InputStream keyStoreStream = Files.newInputStream(keystorePath)) {
            keystore.load(keyStoreStream, storepass == null ? null : storepass.trim().toCharArray());
        } catch (IOException ex) {
            Logger.error("Unable to load https server keystore from " + keystoreUri);
            return;
        }
        keypass = config.getString("keypass").trim().toCharArray();
    }

    // Wire up the listening reactor
    lconf = config.configurationsAt("server");
    if ((lconf == null) || (lconf.size() != 1))
        throw new ConfigurationException("One (and only one) server configuration element is allowed.");
    else {
        Builder builder = IOReactorConfig.custom();
        builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("server[@cpu]", 0.667)));
        builder.setSoTimeout(config.getInt("server[@soTimeout]", 0));
        builder.setSoLinger(config.getInt("server[@soLinger]", -1));
        builder.setSoReuseAddress(true);
        builder.setTcpNoDelay(false);
        builder.setSelectInterval(100);

        IOReactorConfig rconfig = builder.build();
        Logger.info("Configuring server with options: " + rconfig.toString());
        listeningReactor = new DefaultListeningIOReactor(rconfig);

        lconf = config.configurationsAt("server.listen");
        InetSocketAddress addr;
        boolean hasNonWildcardSecure = false;
        LinkedHashMap<SocketAddress, SSLContext> addrSSLContext = new LinkedHashMap<SocketAddress, SSLContext>();
        if ((lconf == null) || (lconf.size() == 0)) {
            addr = new InetSocketAddress("127.0.0.1", 8080);
            ListenerEndpoint ep = listeningReactor.listen(addr);
            Logger.warn("Configured " + ep.getAddress());
        } else {
            TrustManager[] trustManagers = null;
            KeyManagerFactory kmf = null;
            // Create all the specified listeners.
            for (HierarchicalConfiguration hc : lconf) {
                String addrStr = hc.getString("[@address]");
                if ((addrStr == null) || (addrStr.length() == 0))
                    addrStr = "0.0.0.0";
                String alias = hc.getString("[@alias]");
                int port = hc.getInt("[@port]", alias != null ? 443 : 80);
                addr = new InetSocketAddress(addrStr, port);
                ListenerEndpoint ep = listeningReactor.listen(addr);
                String protocol = hc.containsKey("[@protocol]") ? hc.getString("[@protocol]") : null;
                Boolean secure = hc.containsKey("[@secure]") ? hc.getBoolean("[@secure]") : null;
                if ((alias != null) && (secure == null))
                    secure = true;
                if ((protocol != null) && (secure == null))
                    secure = true;
                if ((secure != null) && secure) {
                    if (protocol == null)
                        protocol = "TLS";
                    if (keystore == null)
                        throw new ConfigurationException(
                                "An https listening socket was requested, but no keystore was specified.");
                    if (kmf == null) {
                        kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
                        kmf.init(keystore, keypass);
                    }
                    // Are we going to trust all clients or just specific ones?
                    if (hc.getBoolean("[@trustAny]", true))
                        trustManagers = new TrustManager[] { new X509TrustAllManager() };
                    else {
                        TrustManagerFactory instance = TrustManagerFactory
                                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
                        instance.init(keystore);
                        trustManagers = instance.getTrustManagers();
                    }
                    KeyManager[] keyManagers = kmf.getKeyManagers();
                    if (alias != null)
                        for (int i = 0; i < keyManagers.length; i++) {
                            if (keyManagers[i] instanceof X509ExtendedKeyManager)
                                keyManagers[i] = new PokerFaceKeyManager(alias,
                                        (X509ExtendedKeyManager) keyManagers[i]);
                        }
                    SSLContext sslCtx = SSLContext.getInstance(protocol);
                    sslCtx.init(keyManagers, trustManagers, new SecureRandom());
                    if (addr.getAddress().isAnyLocalAddress()) {
                        // This little optimization helps us respond faster for every connection as we don't have to extrapolate a local connection address to wild card.
                        for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                                .hasMoreElements();) {
                            NetworkInterface intf = en.nextElement();
                            for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                                    .hasMoreElements();) {
                                addr = new InetSocketAddress(enumIpAddr.nextElement(), port);
                                addrSSLContext.put(addr, sslCtx);
                            }
                        }
                    } else {
                        addrSSLContext.put(addr, sslCtx);
                        hasNonWildcardSecure = true;
                    }
                }
                Logger.warn("Configured " + (alias == null ? "" : (protocol + " on")) + ep.getAddress());
            }
        }
        // We will need an HTTP protocol processor for the incoming connections
        String serverAgent = config.getString("server.serverAgent", "PokerFace/" + Utils.Version);
        HttpProcessor inhttpproc = new ImmutableHttpProcessor(
                new HttpResponseInterceptor[] { new ResponseDateInterceptor(), new ResponseServer(serverAgent),
                        new ResponseContent(), new ResponseConnControl() });
        HttpAsyncService serviceHandler = new HttpAsyncService(inhttpproc, new DefaultConnectionReuseStrategy(),
                null, handlerRegistry, null) {
            public void exception(final NHttpServerConnection conn, final Exception cause) {
                Logger.warn(cause.getMessage());
                super.exception(conn, cause);
            }
        };
        if (addrSSLContext.size() > 0) {
            final SSLContext defaultCtx = addrSSLContext.values().iterator().next();
            final Map<SocketAddress, SSLContext> sslMap;
            if ((!hasNonWildcardSecure) || (addrSSLContext.size() == 1))
                sslMap = null;
            else
                sslMap = addrSSLContext;
            listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler,
                    new SSLNHttpServerConnectionFactory(defaultCtx, null, ConnectionConfig.DEFAULT) {
                        protected SSLIOSession createSSLIOSession(IOSession iosession, SSLContext sslcontext,
                                SSLSetupHandler sslHandler) {
                            SSLIOSession retVal;
                            SSLContext sktCtx = sslcontext;
                            if (sslMap != null) {
                                SocketAddress la = iosession.getLocalAddress();
                                if (la != null) {
                                    sktCtx = sslMap.get(la);
                                    if (sktCtx == null)
                                        sktCtx = sslcontext;
                                }
                                retVal = new SSLIOSession(iosession, SSLMode.SERVER, sktCtx, sslHandler);
                            } else
                                retVal = super.createSSLIOSession(iosession, sktCtx, sslHandler);
                            if (sktCtx != null)
                                retVal.setAttribute("com.bytelightning.opensource.pokerface.secure", true);
                            return retVal;
                        }
                    });
        } else
            listeningDispatcher = new DefaultHttpServerIODispatch(serviceHandler, ConnectionConfig.DEFAULT);
    }

    // Configure the httpclient reactor that will be used to do reverse proxing to the specified targets.
    lconf = config.configurationsAt("targets");
    if ((lconf != null) && (lconf.size() > 0)) {
        HierarchicalConfiguration conf = lconf.get(0);
        Builder builder = IOReactorConfig.custom();
        builder.setIoThreadCount(ComputeReactorProcessors(config.getDouble("targets[@cpu]", 0.667)));
        builder.setSoTimeout(conf.getInt("targets[@soTimeout]", 0));
        builder.setSoLinger(config.getInt("targets[@soLinger]", -1));
        builder.setConnectTimeout(conf.getInt("targets[@connectTimeout]", 0));
        builder.setSoReuseAddress(true);
        builder.setTcpNoDelay(false);
        connectingReactor = new DefaultConnectingIOReactor(builder.build());

        final int bufferSize = conf.getInt("targets[@bufferSize]", 1024) * 1024;
        byteBufferPool = new SoftReferenceObjectPool<ByteBuffer>(new BasePooledObjectFactory<ByteBuffer>() {
            @Override
            public ByteBuffer create() throws Exception {
                return ByteBuffer.allocateDirect(bufferSize);
            }

            @Override
            public PooledObject<ByteBuffer> wrap(ByteBuffer buffer) {
                return new DefaultPooledObject<ByteBuffer>(buffer);
            }
        });

        KeyManager[] keyManagers = null;
        TrustManager[] trustManagers = null;

        if (keystore != null) {
            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(keystore, keypass);
            keyManagers = kmf.getKeyManagers();
        }
        // Will the httpclient's trust any remote target, or only specific ones.
        if (conf.getBoolean("targets[@trustAny]", false))
            trustManagers = new TrustManager[] { new X509TrustAllManager() };
        else if (keystore != null) {
            TrustManagerFactory instance = TrustManagerFactory
                    .getInstance(TrustManagerFactory.getDefaultAlgorithm());
            instance.init(keystore);
            trustManagers = instance.getTrustManagers();
        }
        SSLContext clientSSLContext = SSLContext.getInstance(conf.getString("targets[@protocol]", "TLS"));
        clientSSLContext.init(keyManagers, trustManagers, new SecureRandom());

        // Setup an SSL capable connection pool for the httpclients.
        connPool = new BasicNIOConnPool(connectingReactor,
                new BasicNIOConnFactory(clientSSLContext, null, ConnectionConfig.DEFAULT),
                conf.getInt("targets[@connectTimeout]", 0));
        connPool.setMaxTotal(conf.getInt("targets[@connMaxTotal]", 1023));
        connPool.setDefaultMaxPerRoute(conf.getInt("targets[@connMaxPerRoute]", 1023));

        // Set up HTTP protocol processor for outgoing connections
        String userAgent = conf.getString("targets.userAgent", "PokerFace/" + Utils.Version);
        HttpProcessor outhttpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                new RequestContent(), new RequestTargetHost(), new RequestConnControl(),
                new RequestUserAgent(userAgent), new RequestExpectContinue(true) });
        executor = new HttpAsyncRequester(outhttpproc, new DefaultConnectionReuseStrategy());

        // Now set up all the configured targets.
        mappings = new LinkedHashMap<String, TargetDescriptor>();
        hosts = new ConcurrentHashMap<String, HttpHost>();
        String[] scheme = { null };
        String[] host = { null };
        int[] port = { 0 };
        String[] path = { null };
        int[] stripPrefixCount = { 0 };
        for (HierarchicalConfiguration targetConfig : conf.configurationsAt("target")) {
            String match = targetConfig.getString("[@pattern]");
            if ((match == null) || (match.trim().length() < 1)) {
                Logger.error("Unable to configure target;  Invalid url match pattern");
                continue;
            }
            String key = RequestForTargetConsumer.UriToTargetKey(targetConfig.getString("[@url]"), scheme, host,
                    port, path, stripPrefixCount);
            if (key == null) {
                Logger.error("Unable to configure target");
                continue;
            }
            HttpHost targetHost = hosts.get(key);
            if (targetHost == null) {
                targetHost = new HttpHost(host[0], port[0], scheme[0]);
                hosts.put(key, targetHost);
            }
            TargetDescriptor desc = new TargetDescriptor(targetHost, path[0], stripPrefixCount[0]);
            mappings.put(match, desc);
        }
        connectionDispatcher = new DefaultHttpClientIODispatch(new HttpAsyncRequestExecutor(),
                ConnectionConfig.DEFAULT);
    }
    // Allocate the script map which will be populated by it's own executor thread.
    if (config.containsKey("scripts.rootDirectory")) {
        Path tmp = Utils.MakePath(config.getProperty("scripts.rootDirectory"));
        if (!Files.exists(tmp))
            throw new FileNotFoundException("Scripts directory does not exist.");
        if (!Files.isDirectory(tmp))
            throw new FileNotFoundException("'scripts' path is not a directory.");
        scripts = new ConcurrentSkipListMap<String, ScriptObjectMirror>();
        boolean watch = config.getBoolean("scripts.dynamicWatch", false);
        List<Path> jsLibs;
        Object prop = config.getProperty("scripts.library");
        if (prop != null) {
            jsLibs = new ArrayList<Path>();
            if (prop instanceof Collection<?>) {
                @SuppressWarnings("unchecked")
                Collection<Object> oprop = (Collection<Object>) prop;
                for (Object obj : oprop)
                    jsLibs.add(Utils.MakePath(obj));
            } else {
                jsLibs.add(Utils.MakePath(prop));
            }
        } else
            jsLibs = null;

        lconf = config.configurationsAt("scripts.scriptConfig");
        if (lconf != null) {
            if (lconf.size() > 1)
                throw new ConfigurationException("Only one scriptConfig element is allowed.");
            if (lconf.size() == 0)
                lconf = null;
        }

        HierarchicalConfiguration scriptConfig;
        if (lconf == null)
            scriptConfig = new HierarchicalConfiguration();
        else
            scriptConfig = lconf.get(0);
        scriptConfig.setProperty("pokerface.scripts.rootDirectory", tmp.toString());

        configureScripts(jsLibs, scriptConfig, tmp, watch);
        if (watch)
            ScriptDirectoryWatcher = new DirectoryWatchService();
    }

    // Configure the static file directory (if any)
    Path staticFilesPath = null;
    if (config.containsKey("files.rootDirectory")) {
        Path tmp = Utils.MakePath(config.getProperty("files.rootDirectory"));
        if (!Files.exists(tmp))
            throw new FileNotFoundException("Files directory does not exist.");
        if (!Files.isDirectory(tmp))
            throw new FileNotFoundException("'files' path is not a directory.");
        staticFilesPath = tmp;
        List<HierarchicalConfiguration> mimeEntries = config.configurationsAt("files.mime-entry");
        if (mimeEntries != null) {
            for (HierarchicalConfiguration entry : mimeEntries) {
                entry.setDelimiterParsingDisabled(true);
                String type = entry.getString("[@type]", "").trim();
                if (type.length() == 0)
                    throw new ConfigurationException("Invalid mime type entry");
                String extensions = entry.getString("[@extensions]", "").trim();
                if (extensions.length() == 0)
                    throw new ConfigurationException("Invalid mime extensions for: " + type);
                ScriptHelperImpl.AddMimeEntry(type, extensions);
            }
        }
    }

    handlerRegistry.register("/*",
            new RequestHandler(executor, connPool, byteBufferPool, staticFilesPath, mappings,
                    scripts != null ? Collections.unmodifiableNavigableMap(scripts) : null,
                    config.getBoolean("scripts.allowScriptsToSpecifyDynamicHosts", false) ? hosts : null));
}