/**
  * filters test based on given filterKey/filterValue. If the any of the filter key/value pairs
  * found from data object, then returns true.
  *
  * @param data test data
  * @return true if test is selected after applying filter, false otherwise
  */
 private boolean checkAgainstFilterProperties(
     HierarchicalConfiguration data, HierarchicalConfiguration context) {
   boolean included = true;
   String filterKeys[] = null;
   String filterValues[] = null;
   if (context.containsKey(ARG_FILTER_KEY)
       && !context.getString(ARG_FILTER_KEY).trim().equals("")) {
     filterKeys = context.getStringArray(ARG_FILTER_KEY);
     filterValues = context.getStringArray(ARG_FILTER_VALUE);
   } else if (DDConfig.getSingleton().getData().containsKey(ARG_FILTER_KEY)
       && !DDConfig.getSingleton().getData().getString(ARG_FILTER_KEY).trim().equals("")) {
     filterKeys = DDConfig.getSingleton().getData().getStringArray(ARG_FILTER_KEY);
     filterValues = DDConfig.getSingleton().getData().getStringArray(ARG_FILTER_VALUE);
   }
   if (filterKeys != null && filterValues != null) {
     included = false;
     for (int index = 0; index < filterKeys.length; index++) {
       String filterKey = filterKeys[index];
       String filterValue = null;
       if (index >= filterValues.length) {
         filterValue = "";
       } else {
         filterValue = filterValues[index];
       }
       if (data.containsKey(filterKey) && data.getString(filterKey, "").equals(filterValue)) {
         included = true;
         break;
       }
     }
   }
   return included;
 }
Exemple #2
0
  public void load(HierarchicalConfiguration config) throws IOException {
    HierarchicalConfiguration localConfig = config.configurationAt(this.getClass().getName());
    String dictionaryFilename = "/dict/single.txt";
    if (dictionaryFilename == null)
      throw new IllegalArgumentException("Must specify dictionary filename");
    String dictionaryTypeName = localConfig.getString("dictionaryType");
    if (dictionaryTypeName == null)
      throw new IllegalArgumentException("Must specify dictionary type");
    String delimiter = localConfig.getString("delimiter");
    int column = localConfig.getInt("column", -1);
    if (delimiter != null && column == -1)
      throw new IllegalArgumentException("Must specify column if delimiter specified");
    EntityType dictionaryType = EntityType.getType(dictionaryTypeName);

    // Load data
    java.util.Scanner s =
        new java.util.Scanner(getClass().getResourceAsStream(dictionaryFilename))
            .useDelimiter("\\A");

    while (s.hasNext()) {
      String line = s.nextLine();
      line = line.trim();
      if (line.length() > 0) {
        if (delimiter == null) {
          add(line, dictionaryType);
        } else {
          // TODO Performance - don't use split
          String[] split = line.split(delimiter);
          add(split[column], dictionaryType);
        }
      }
    }
    s.close();
  }
Exemple #3
0
  @Override
  protected void parse() {
    defaultScript = getConfig().getString(PARAM_DEFAULT_SCRIPT, "");
    defaultDir = getConfig().getString(PARAM_DEFAULT_DIR, "");

    try {
      List<HierarchicalConfiguration> fields =
          ((HierarchicalConfiguration) getConfig()).configurationsAt(ALL_SCRIPTS_KEY);
      this.scripts = new HashSet<>(fields.size());
      List<String> tempListNames = new ArrayList<>(fields.size());
      for (HierarchicalConfiguration sub : fields) {
        String name = sub.getString(SCRIPT_NAME_KEY, "");
        try {
          if (!"".equals(name) && !tempListNames.contains(name)) {
            tempListNames.add(name);

            File file = new File(sub.getString(SCRIPT_FILE_KEY));
            if (!file.exists()) {
              logger.error("Script '" + file.getAbsolutePath() + "' does not exist");
              continue;
            }

            ScriptWrapper script =
                new ScriptWrapper(
                    sub.getString(SCRIPT_NAME_KEY),
                    sub.getString(SCRIPT_DESC_KEY),
                    sub.getString(SCRIPT_ENGINE_KEY),
                    sub.getString(SCRIPT_TYPE_KEY),
                    sub.getBoolean(SCRIPT_ENABLED_KEY),
                    file);

            script.setLoadOnStart(true); // Because it was saved ;)

            scripts.add(script);
          }
        } catch (Exception e) {
          logger.error("Error while loading the script: " + name, e);
        }
      }
    } catch (Exception e) {
      logger.error("Error while loading the scripts: " + e.getMessage(), e);
    }

    try {
      this.scriptDirs = new ArrayList<File>();
      for (Object dirName : getConfig().getList(SCRIPT_DIRS)) {
        File f = new File((String) dirName);
        if (!f.exists() || !f.isDirectory()) {
          logger.error("Not a valid script directory: " + dirName);
        } else {
          scriptDirs.add(f);
        }
      }

    } catch (Exception e) {
      logger.error("Error while loading the script dirs: " + e.getMessage(), e);
    }
    confirmRemoveDir = getConfig().getBoolean(SCRIPT_CONFIRM_REMOVE_DIR, true);
  }
 protected void loadStringTransformerFromXML(XMLConfiguration xml) throws IOException {
   setCaseSensitive(xml.getBoolean("[@caseSensitive]", false));
   setInclusive(xml.getBoolean("[@inclusive]", false));
   List<HierarchicalConfiguration> nodes = xml.configurationsAt("stripBetween");
   for (HierarchicalConfiguration node : nodes) {
     addStripEndpoints(node.getString("start", null), node.getString("end", null));
   }
 }
Exemple #5
0
 private static Coordinate getCoord(HierarchicalConfiguration serviceConfig, String prefix) {
   Coordinate pickupCoord = null;
   if (serviceConfig.getString(prefix + "coord[@x]") != null
       && serviceConfig.getString(prefix + "coord[@y]") != null) {
     double x = Double.parseDouble(serviceConfig.getString(prefix + "coord[@x]"));
     double y = Double.parseDouble(serviceConfig.getString(prefix + "coord[@y]"));
     pickupCoord = Coordinate.newInstance(x, y);
   }
   return pickupCoord;
 }
  /**
   * @see org.apache.james.mailrepository.lib.AbstractMailRepository
   *     #doConfigure(org.apache.commons.configuration.HierarchicalConfiguration)
   */
  @Override
  public void doConfigure(HierarchicalConfiguration config) throws ConfigurationException {
    this.workspace = config.getString("workspace", null);
    String username = config.getString("username", null);
    String password = config.getString("password", null);

    if (username != null && password != null) {
      this.creds = new SimpleCredentials(username, password.toCharArray());
    }
  }
Exemple #7
0
 public static boolean loadConfig(String configFilePath) {
   String tmp = System.getProperty("os.name").toLowerCase();
   if (tmp.startsWith("windows")) {
     g.os = g.OS_WINDOWS;
   } else if (tmp.startsWith("linux")) {
     g.os = g.OS_LINUX;
   } else {
     g.os = g.OS_OTHER;
   }
   tmp = System.getProperty("sun.arch.data.model");
   if (tmp.equals("64")) {
     g.arch = g.ARCH_64;
   } else {
     g.arch = g.ARCH_32;
   }
   try {
     if (configFilePath == null) {
       config = new XMLConfiguration(configPath + "config.xml");
     } else {
       config = new XMLConfiguration(configFilePath);
     }
     dbConfig = config.getString("db", "").toLowerCase();
     siteUrl = config.getString("serverInfo.siteUrl");
     siteName = config.getString("serverInfo.siteName");
     uploadTemp = rootPath + config.getString("serverInfo.uploadTemp");
     uploadSizeMax = config.getLong("serverInfo.uploadSizeMax", 0);
     sessionExpiredTime = config.getInt("serverInfo.sessionExpiredTime", 0);
     sessionIdName = config.getString("serverInfo.sessionIdName", "ycsid");
     String _s = g.getConfig().getString("startup");
     if ("".equals(_s)) {
       startup = null;
     } else {
       _s = _s.replaceAll("\\s", "");
       startup = _s.split(";");
     }
     _s = null;
     // 加载全局参数
     List<HierarchicalConfiguration> fields = config.configurationsAt("globalVars.var");
     if (fields != null && fields.size() > 0) {
       vars = new String[fields.size()][2];
       HierarchicalConfiguration sub;
       for (int i = 0; i < fields.size(); i++) {
         sub = fields.get(i);
         vars[i][0] = sub.getString("[@name]");
         vars[i][1] = sub.getString("[@value]");
       }
       sub = null;
     }
     return true;
   } catch (ConfigurationException e) {
     return false;
   }
 }
  @Override
  @SuppressWarnings("unchecked")
  public List<UserAlert> getAvailableAlerts() {
    List<UserAlert> alerts = new ArrayList<UserAlert>();

    final SortedMap<Integer, Pair> categoryNames = new ConcurrentSkipListMap<Integer, Pair>();

    HierarchicalConfiguration hc = (HierarchicalConfiguration) configuration;
    List<HierarchicalConfiguration> categories = hc.configurationsAt(ALERTS_CATEGORIES_CATEGORY);

    for (HierarchicalConfiguration c : categories) {
      String key = c.getString("[@key]");
      int order = c.getInt("[@displayOrder]", categoryNames.size());
      String value = c.getString("");

      categoryNames.put(order, new Pair<String, String>(key, value));
    }

    final String[] weeklyCategories = hc.getStringArray(ALERTS_WEEKLY);
    final String[] monthlyCategories = hc.getStringArray(ALERTS_MONTHLY);
    final String[] subjectFilters = hc.getStringArray(SUBJECT_FILTER);

    final Set<Map.Entry<Integer, Pair>> categoryNamesSet = categoryNames.entrySet();

    for (final Map.Entry<Integer, Pair> category : categoryNamesSet) {
      final String key = (String) category.getValue().getFirst();
      boolean weeklyCategoryKey = false;
      boolean monthlyCategoryKey = false;
      boolean subjectFilter = false;

      if (ArrayUtils.contains(weeklyCategories, key)) {
        weeklyCategoryKey = true;
      }
      if (ArrayUtils.contains(monthlyCategories, key)) {
        monthlyCategoryKey = true;
      }
      if (ArrayUtils.contains(subjectFilters, key)) {
        subjectFilter = true;
      }

      alerts.add(
          new UserAlert(
              (String) category.getValue().getFirst(),
              (String) category.getValue().getSecond(),
              weeklyCategoryKey,
              monthlyCategoryKey,
              subjectFilter));
    }
    return alerts;
  }
Exemple #9
0
  public String getTheme() {
    if (theme == null) {
      this.theme = configuration.getString("appearances.ui-theme.default", "redmond").trim();
    }

    return theme;
  }
Exemple #10
0
  public String getResourcePrefix() {
    if (resourcePrefix == null) {
      this.resourcePrefix = StringUtils.trimToEmpty(configuration.getString("web.resource-prefix"));
    }

    return resourcePrefix;
  }
Exemple #11
0
  public String getLocaleAttributeName() {
    if (localeAttributeName == null) {
      this.localeAttributeName = configuration.getString("web.locale-attribute", "locale").trim();
    }

    return localeAttributeName;
  }
 /**
  * Get's data from XML file in classpath in specified format.<br>
  * First search the
  *
  * @param className ClassName
  * @param context The context.
  */
 public HierarchicalConfiguration getData(
     final String className, HierarchicalConfiguration context) {
   HierarchicalConfiguration dataForTestCase = null;
   try {
     Class<?> clazz = Class.forName(className);
     String dataFilePath = null;
     URL dataFileURL = null;
     boolean packageFile = false;
     Map<String, HierarchicalConfiguration> dataMap = null;
     String dataFileName = context.getString("supplier.dataFile", null);
     log.debug("Checking the data file in argument...");
     if (dataFileName == null || dataFileName.equals("")) {
       log.debug("Data file not given in argument..Using DataFileFinder..");
       dataFilePath = DDUtils.findDataFile(className, ".xml", context);
     } else {
       log.debug("Got data file in argument");
       dataFilePath = dataFileName;
     }
     log.debug("Data file path: " + dataFilePath);
     if (dataFilePath == null) {
       return null; // No data found, hence it's a normal test case.
     }
     dataFileURL = clazz.getResource(dataFilePath);
     if (packageFile) {
       // The data file is from package file name so check the cache.
       log.debug("Cache: " + cache.size());
       synchronized (XMLDataSupplier.class) {
         if (loadedFiles.contains(dataFilePath)) { // get it from cache.
           log.info("File was loaded before !!!");
           dataForTestCase = cache.get(clazz.getName());
         } else { // not in cache, so load and put it to cache.
           log.info("File was not loaded before, loading now...");
           if (dataFileURL != null) {
             cache.putAll(XMLDataParser.load(dataFileURL, clazz));
           } else {
             cache.putAll(XMLDataParser.load(dataFilePath, clazz));
           }
           dataForTestCase = cache.get(clazz.getName());
           loadedFiles.add(dataFilePath);
         }
       }
       if ((dataForTestCase == null) || dataForTestCase.isEmpty()) {
         log.info("Data for '{}' is not available!", className);
         return null;
       }
     } else { // data file not from package file so go ahead and load.
       log.debug("Loading the xml file...");
       if (dataFileURL != null) {
         dataMap = XMLDataParser.load(dataFileURL, clazz);
       } else {
         dataMap = XMLDataParser.load(dataFilePath, clazz);
       }
       dataForTestCase = dataMap.get(clazz.getName());
     }
   } catch (Exception ex) {
     throw new DDException("Error in loading the data file", ex);
   }
   return dataForTestCase;
 }
Exemple #13
0
  public String getEditorTheme() {
    if (editorTheme == null) {
      this.editorTheme =
          StringUtils.trimToNull(configuration.getString("appearances.editor-theme"));
    }

    return editorTheme;
  }
Exemple #14
0
  @PostConstruct
  public void init() {
    String genreFileName = PropertyTools.getProperty("yamj3.genre.fileName");
    if (StringUtils.isBlank(genreFileName)) {
      LOG.trace("No valid genre file name configured");
      return;
    }
    if (!StringUtils.endsWithIgnoreCase(genreFileName, "xml")) {
      LOG.warn("Invalid genre file name specified: {}", genreFileName);
      return;
    }

    File xmlFile;
    if (StringUtils.isBlank(FilenameUtils.getPrefix(genreFileName))) {
      // relative path given
      String path = System.getProperty("yamj3.home");
      if (StringUtils.isEmpty(path)) {
        path = ".";
      }
      xmlFile = new File(FilenameUtils.concat(path, genreFileName));
    } else {
      // absolute path given
      xmlFile = new File(genreFileName);
    }

    if (!xmlFile.exists() || !xmlFile.isFile()) {
      LOG.warn("Genres file does not exist: {}", xmlFile.getPath());
      return;
    }
    if (!xmlFile.canRead()) {
      LOG.warn("Genres file not readble: {}", xmlFile.getPath());
      return;
    }

    LOG.debug("Initialize genres from file: {}", xmlFile.getPath());

    try {
      XMLConfiguration c = new XMLConfiguration(xmlFile);

      List<HierarchicalConfiguration> genres = c.configurationsAt("genre");
      for (HierarchicalConfiguration genre : genres) {
        String masterGenre = genre.getString("[@name]");
        List<Object> subGenres = genre.getList("subgenre");
        for (Object subGenre : subGenres) {
          LOG.debug("New genre added to map: {} -> {}", subGenre, masterGenre);
          GENRES_MAP.put(((String) subGenre).toLowerCase(), masterGenre);
        }
      }

      try {
        this.commonStorageService.updateGenresXml(GENRES_MAP);
      } catch (Exception ex) {
        LOG.warn("Failed update genres xml in database", ex);
      }
    } catch (Exception ex) {
      LOG.error("Failed parsing genre input file: " + xmlFile.getPath(), ex);
    }
  }
  private Graph getGraphFromConfiguration(final HierarchicalConfiguration graphConfiguration)
      throws GraphConfigurationException {
    String graphConfigurationType = graphConfiguration.getString(Tokens.REXSTER_GRAPH_TYPE);
    final boolean isReadOnly = graphConfiguration.getBoolean(Tokens.REXSTER_GRAPH_READ_ONLY, false);

    if (graphConfigurationType.equals("neo4jgraph")) {
      graphConfigurationType = Neo4jGraphConfiguration.class.getName();
    } else if (graphConfigurationType.equals("orientgraph")) {
      graphConfigurationType = OrientGraphConfiguration.class.getName();
    } else if (graphConfigurationType.equals("tinkergraph")) {
      graphConfigurationType = TinkerGraphGraphConfiguration.class.getName();
    } else if (graphConfigurationType.equals("rexstergraph")) {
      graphConfigurationType = RexsterGraphGraphConfiguration.class.getName();
    } else if (graphConfigurationType.equals("memorystoresailgraph")) {
      graphConfigurationType = MemoryStoreSailGraphConfiguration.class.getName();
    } else if (graphConfigurationType.equals("nativestoresailgraph")) {
      graphConfigurationType = NativeStoreSailGraphConfiguration.class.getName();
    } else if (graphConfigurationType.equals("sparqlrepositorysailgraph")) {
      graphConfigurationType = SparqlRepositorySailGraphConfiguration.class.getName();
    } else if (graphConfigurationType.equals("dexgraph")) {
      graphConfigurationType = DexGraphConfiguration.class.getName();
    }

    final Graph graph;
    try {
      final Class clazz =
          Class.forName(
              graphConfigurationType, true, Thread.currentThread().getContextClassLoader());
      final GraphConfiguration graphConfigInstance = (GraphConfiguration) clazz.newInstance();
      Graph readWriteGraph = graphConfigInstance.configureGraphInstance(graphConfiguration);

      if (isReadOnly) {
        // the graph is configured to be readonly so wrap it up
        if (readWriteGraph instanceof IndexableGraph) {
          graph = new ReadOnlyIndexableGraph((IndexableGraph) readWriteGraph);
        } else {
          graph = new ReadOnlyGraph(readWriteGraph);
        }
      } else {
        graph = readWriteGraph;
      }

    } catch (NoClassDefFoundError err) {
      throw new GraphConfigurationException(
          String.format(
              "GraphConfiguration [%s] could not instantiate a class [%s].  Ensure that it is in Rexster's path.",
              graphConfigurationType, err.getMessage()));
    } catch (Exception ex) {
      throw new GraphConfigurationException(
          String.format(
              "GraphConfiguration could not be found or otherwise instantiated: [%s]. Ensure that it is in Rexster's path.",
              graphConfigurationType),
          ex);
    }

    return graph;
  }
 @Override
 protected String getTargetUrl() {
   HierarchicalConfiguration config = ConfigUtils.getCurrentConfig();
   if (config != null) {
     return config.getString(LOGIN_FAILURE_URL_KEY, targetUrl);
   } else {
     return targetUrl;
   }
 }
Exemple #17
0
  public static Hashtable getMap(String config) throws FitsConfigurationException {
    Hashtable mappings = new Hashtable();
    XMLConfiguration conf = null;
    try {
      conf = new XMLConfiguration(config);
    } catch (ConfigurationException e) {
      throw new FitsConfigurationException("Error reading " + config + "fits.xml", e);
    }

    List fields = conf.configurationsAt("map");
    for (Iterator it = fields.iterator(); it.hasNext(); ) {
      HierarchicalConfiguration sub = (HierarchicalConfiguration) it.next();
      // sub contains now all data about a single field
      String format = sub.getString("[@format]");
      String transform = sub.getString("[@transform]");
      mappings.put(format, transform);
    }
    return mappings;
  }
Exemple #18
0
  public String getViewParameterName() {
    if (viewParameterName == null) {
      this.viewParameterName = configuration.getString("web.view-parameter", "viewId").trim();

      if (viewParameterName == null) {
        this.viewParameterName = "viewId";
      }
    }

    return viewParameterName;
  }
  public static DefaultEngineConfig create() {
    DefaultEngineConfig conf = new DefaultEngineConfig();
    String path = Utils.getConfigDir() + Constants.HDATA_XML;

    try {
      XMLConfiguration config = new XMLConfiguration(path);
      config.setValidating(true);

      List<HierarchicalConfiguration> properties = config.configurationsAt(".property");
      for (HierarchicalConfiguration hc : properties) {
        String name = hc.getString("name");
        String value = hc.getString("value");
        conf.setProperty(name, value);
      }
    } catch (ConfigurationException e) {
      Throwables.propagate(e);
    }

    return conf;
  }
 @Override
 public void loadFromXML(Reader in) throws IOException {
   try {
     XMLConfiguration xml = ConfigurationUtil.newXMLConfiguration(in);
     defaultDelay = xml.getLong("[@default]", defaultDelay);
     ignoreRobotsCrawlDelay = xml.getBoolean("[@ignoreRobotsCrawlDelay]", ignoreRobotsCrawlDelay);
     scope = xml.getString("[@scope]", SCOPE_CRAWLER);
     List<HierarchicalConfiguration> nodes = xml.configurationsAt("schedule");
     for (HierarchicalConfiguration node : nodes) {
       schedules.add(
           new DelaySchedule(
               node.getString("[@dayOfWeek]", null),
               node.getString("[@dayOfMonth]", null),
               node.getString("[@time]", null),
               node.getLong("", DEFAULT_DELAY)));
     }
   } catch (ConfigurationException e) {
     throw new IOException("Cannot load XML.", e);
   }
 }
Exemple #21
0
  /** @return the availableThemes */
  public SortedMap<String, String> getAvailableThemes() {
    synchronized (this) {
      if (availableThemes == null) {
        this.availableThemes = new TreeMap<String, String>();

        List<HierarchicalConfiguration> configurations =
            configuration.configurationsAt("appearances.ui-theme.available-themes.theme");
        for (HierarchicalConfiguration config : configurations) {
          String name = config.getString("[@name]");
          availableThemes.put(StringUtils.capitalize(name), name);
        }
      }
    }

    return availableThemes;
  }
  public ConfigKey generateByPropertiesKey(String key) {
    SubnodeConfiguration configurationAt = null;
    try {
      if (Character.isLetter(key.charAt(0))) {
        configurationAt = keysConfig.configurationAt(key);
      }
    } catch (IllegalArgumentException e) {
      // Can't find a key. maybe its an alternate key.
    }
    if (configurationAt == null || configurationAt.isEmpty()) {
      key = alternateKeysMap.get(key);
      configurationAt = keysConfig.configurationAt(key);
    }

    String type = configurationAt.getString("type");
    if (StringUtils.isBlank(type)) {
      type = "String";
    }
    String[] validValues = configurationAt.getStringArray("validValues");

    // Description containing the list delimiter *will* be broken into an array, so rejoin it using
    // that delimiter.
    // We pad the separator because the strings in the array are trimmed automatically.
    String description =
        StringUtils.join(
            configurationAt.getStringArray("description"),
            configurationAt.getListDelimiter() + " ");
    String alternateKey = keysConfig.getString("/" + key + "/" + "alternateKey");

    // If the isReloadable attribute isn't specified - assume it is false
    boolean reloadable = configurationAt.getBoolean("isReloadable", false);
    ConfigKey configKey =
        new ConfigKey(
            type,
            description,
            alternateKey,
            key,
            "",
            validValues,
            "",
            getHelperByType(type),
            reloadable,
            isDeprecated(key));
    configKey.setParser(parser);
    return configKey;
  }
Exemple #23
0
  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'");
      }
      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);
        }
      }
      String serviceLocationId = serviceConfig.getString("locationId");
      if (serviceLocationId != null) builder.setLocationId(serviceLocationId);
      Coordinate serviceCoord = getCoord(serviceConfig, "");
      if (serviceCoord != null) {
        builder.setCoord(serviceCoord);
        if (serviceLocationId != null) {
          //					vrpBuilder.addLocation(serviceLocationId,serviceCoord);
        } else {
          //					vrpBuilder.addLocation(serviceCoord.toString(),serviceCoord);
          builder.setLocationId(serviceCoord.toString());
        }
      }
      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")));
        }
      }
      Service service = builder.build();
      serviceMap.put(service.getId(), service);
      //			vrpBuilder.addJob(service);

    }
  }
Exemple #24
0
  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'");
      }
      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();
      String penalty = typeConfig.getString("[@type]");
      if (penalty != null) {
        if (penalty.equals("penalty")) {
          String penaltyFactor = typeConfig.getString("[@penaltyFactor]");
          if (penaltyFactor != null) {
            type = new PenaltyVehicleType(type, Double.parseDouble(penaltyFactor));
          } else type = new PenaltyVehicleType(type);
          id = id + "_penalty";
        }
      }

      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);
      String locationId = vehicleConfig.getString("location.id");
      if (locationId == null) {
        locationId = vehicleConfig.getString("startLocation.id");
      }
      if (locationId == null) throw new IllegalStateException("location.id is missing.");
      builder.setStartLocationId(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.warn("location.coord is missing. will not warn you again.");
          doNotWarnAgain = true;
        }
      } else {
        Coordinate coordinate =
            Coordinate.newInstance(Double.parseDouble(coordX), Double.parseDouble(coordY));
        builder.setStartLocationCoordinate(coordinate);
      }

      String endLocationId = vehicleConfig.getString("endLocation.id");
      if (endLocationId != null) builder.setEndLocationId(endLocationId);
      String endCoordX = vehicleConfig.getString("endLocation.coord[@x]");
      String endCoordY = vehicleConfig.getString("endLocation.coord[@y]");
      if (endCoordX == null || endCoordY == null) {
        if (!doNotWarnAgain) {
          logger.warn("endLocation.coord is missing. will not warn you again.");
          doNotWarnAgain = true;
        }
      } else {
        Coordinate coordinate =
            Coordinate.newInstance(Double.parseDouble(endCoordX), Double.parseDouble(endCoordY));
        builder.setEndLocationCoordinate(coordinate);
      }

      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));
      String returnToDepot = vehicleConfig.getString("returnToDepot");
      if (returnToDepot != null) {
        builder.setReturnToDepot(vehicleConfig.getBoolean("returnToDepot"));
      }
      VehicleImpl vehicle = builder.build();
      vrpBuilder.addVehicle(vehicle);
      vehicleMap.put(vehicleId, vehicle);
    }
  }
  @SuppressWarnings("deprecation")
  public static InsertionStrategy createInsertion(
      VehicleRoutingProblem vrp,
      HierarchicalConfiguration config,
      VehicleFleetManager vehicleFleetManager,
      StateManager stateManager,
      List<PrioritizedVRAListener> algorithmListeners,
      ExecutorService executorService,
      int nuOfThreads,
      ConstraintManager constraintManager,
      boolean addDefaultCostCalculators) {

    if (config.containsKey("[@name]")) {
      String insertionName = config.getString("[@name]");
      if (!insertionName.equals("bestInsertion")
          && !insertionName.equals("regretInsertion")
          && !insertionName.equals("fixedBestInsertion")
          && !insertionName.equals("firstFixedBestInsertion")
          && !insertionName.equals("fixedRegretInsertion")) {
        throw new IllegalStateException(
            insertionName
                + " is not supported. use either \"bestInsertion\" or \"regretInsertion\"");
      }

      InsertionBuilder iBuilder =
          new InsertionBuilder(vrp, vehicleFleetManager, stateManager, constraintManager);

      if (executorService != null) {
        iBuilder.setConcurrentMode(executorService, nuOfThreads);
      }

      if (config.containsKey("level")) {
        String level = config.getString("level");
        if (level.equals("local")) {
          iBuilder.setLocalLevel(addDefaultCostCalculators);
        } else if (level.equals("route")) {
          int forwardLooking = 0;
          int memory = 1;
          String forward = config.getString("level[@forwardLooking]");
          String mem = config.getString("level[@memory]");
          if (forward != null) forwardLooking = Integer.parseInt(forward);
          else
            log.warn(
                "parameter route[@forwardLooking] is missing. by default it is 0 which equals to local level");
          if (mem != null) memory = Integer.parseInt(mem);
          else log.warn("parameter route[@memory] is missing. by default it is 1");
          iBuilder.setRouteLevel(forwardLooking, memory, addDefaultCostCalculators);
        } else
          throw new IllegalStateException(
              "level " + level + " is not known. currently it only knows \"local\" or \"route\"");
      } else iBuilder.setLocalLevel(addDefaultCostCalculators);

      if (config.containsKey("considerFixedCosts") || config.containsKey("considerFixedCost")) {
        if (addDefaultCostCalculators) {
          String val = config.getString("considerFixedCosts");
          if (val == null) val = config.getString("considerFixedCost");
          if (val.equals("true")) {
            double fixedCostWeight = 0.5;
            String weight = config.getString("considerFixedCosts[@weight]");
            if (weight == null) weight = config.getString("considerFixedCost[@weight]");
            if (weight != null) fixedCostWeight = Double.parseDouble(weight);
            else
              throw new IllegalStateException(
                  "fixedCostsParameter 'weight' must be set, e.g. <considerFixedCosts weight=1.0>true</considerFixedCosts>.\n"
                      + "this has to be changed in algorithm-config-xml-file.");
            iBuilder.considerFixedCosts(fixedCostWeight);
          } else if (val.equals("false")) {

          } else
            throw new IllegalStateException(
                "considerFixedCosts must either be true or false, i.e. <considerFixedCosts weight=1.0>true</considerFixedCosts> or \n<considerFixedCosts weight=1.0>false</considerFixedCosts>. "
                    + "if latter, you can also omit the tag. this has to be changed in algorithm-config-xml-file");
        }
      }
      String timeSliceString = config.getString("experimental[@timeSlice]");
      String neighbors = config.getString("experimental[@neighboringSlices]");
      if (timeSliceString != null && neighbors != null) {
        iBuilder.experimentalTimeScheduler(
            Double.parseDouble(timeSliceString), Integer.parseInt(neighbors));
      }
      String allowVehicleSwitch = config.getString("allowVehicleSwitch");
      if (allowVehicleSwitch != null) {
        iBuilder.setAllowVehicleSwitch(Boolean.parseBoolean(allowVehicleSwitch));
      }

      if (insertionName.equals("regretInsertion")) {
        iBuilder.setInsertionStrategy(InsertionBuilder.Strategy.REGRET);
      } else if (insertionName.equals("fixedBestInsertion")) {
        iBuilder.setInsertionStrategy(InsertionBuilder.Strategy.FIXEDBEST);
      } else if (insertionName.equals("firstFixedBestInsertion")) {
        iBuilder.setInsertionStrategy(InsertionBuilder.Strategy.FIRSTFIXEDBEST);
      } else if (insertionName.equals("fixedRegretInsertion")) {
        iBuilder.setInsertionStrategy(InsertionBuilder.Strategy.FIXEDREGRET);
      }
      return iBuilder.build();
    } else
      throw new IllegalStateException("cannot create insertionStrategy, since it has no name.");
  }
Exemple #26
0
  @Override
  protected void parse() {
    removeOldOptions();

    try {
      this.threadPerHost = getConfig().getInt(THREAD_PER_HOST, 1);
    } catch (Exception e) {
    }

    try {
      this.hostPerScan = getConfig().getInt(HOST_PER_SCAN, 2);
    } catch (Exception e) {
    }

    try {
      this.delayInMs = getConfig().getInt(DELAY_IN_MS, 0);
    } catch (Exception e) {
    }

    try {
      this.maxResultsToList = getConfig().getInt(MAX_RESULTS_LIST, 1000);
    } catch (Exception e) {
    }

    try {
      this.maxScansInUI = getConfig().getInt(MAX_SCANS_IN_UI, 5);
    } catch (Exception e) {
    }

    try {
      this.injectPluginIdInHeader = getConfig().getBoolean(INJECT_PLUGIN_ID_IN_HEADER, false);
    } catch (Exception e) {
    }

    try {
      this.handleAntiCSRFTokens = getConfig().getBoolean(HANDLE_ANTI_CSRF_TOKENS, false);
    } catch (Exception e) {
    }

    try {
      this.promptInAttackMode = getConfig().getBoolean(PROMPT_IN_ATTACK_MODE, true);
    } catch (Exception e) {
    }

    try {
      this.rescanInAttackMode = getConfig().getBoolean(RESCAN_IN_ATTACK_MODE, true);
    } catch (Exception e) {
    }

    try {
      this.promptToClearFinishedScans = getConfig().getBoolean(PROMPT_TO_CLEAR_FINISHED, true);
    } catch (Exception e) {
    }

    try {
      this.showAdvancedDialog = getConfig().getBoolean(SHOW_ADV_DIALOG, false);
    } catch (Exception e) {
    }

    try {
      this.defaultPolicy = getConfig().getString(DEFAULT_POLICY, null);
    } catch (Exception e) {
    }

    try {
      this.attackPolicy = getConfig().getString(ATTACK_POLICY, null);
    } catch (Exception e) {
    }

    try {
      this.targetParamsInjectable =
          getConfig().getInt(TARGET_INJECTABLE, TARGET_INJECTABLE_DEFAULT);
    } catch (Exception e) {
    }

    try {
      this.targetParamsEnabledRPC =
          getConfig().getInt(TARGET_ENABLED_RPC, TARGET_ENABLED_RPC_DEFAULT);
    } catch (Exception e) {
    }

    try {
      this.allowAttackOnStart = getConfig().getBoolean(ALLOW_ATTACK_ON_START, false);
    } catch (Exception e) {
    }

    // Parse the parameters that need to be excluded
    // ------------------------------------------------
    try {
      List<HierarchicalConfiguration> fields =
          ((HierarchicalConfiguration) getConfig()).configurationsAt(EXCLUDED_PARAMS_KEY);

      this.excludedParams.clear();
      this.excludedParamsMap.clear();
      List<String> tempParamNames = new ArrayList<>(fields.size());

      for (HierarchicalConfiguration sub : fields) {
        String name = sub.getString(EXCLUDED_PARAM_NAME, "");
        if (!name.isEmpty() && !tempParamNames.contains(name)) {
          tempParamNames.add(name);

          addScannerParamFilter(
              name,
              sub.getInt(EXCLUDED_PARAM_TYPE, NameValuePair.TYPE_UNDEFINED),
              sub.getString(EXCLUDED_PARAM_URL));
        }
      }

    } catch (ConversionException e) {
      logger.error("Error while loading the exluded parameter list: " + e.getMessage(), e);
    }

    // If the list is null probably we've to use defaults!!!
    if (this.excludedParams.isEmpty()) {
      // OK let's set the Default parameter exclusion list
      // Evaluate the possibility to load it from an external file...
      addScannerParamFilter("(?i)ASP.NET_SessionId", NameValuePair.TYPE_UNDEFINED, "*");
      addScannerParamFilter("(?i)ASPSESSIONID.*", NameValuePair.TYPE_UNDEFINED, "*");
      addScannerParamFilter("(?i)PHPSESSID", NameValuePair.TYPE_UNDEFINED, "*");
      addScannerParamFilter("(?i)SITESERVER", NameValuePair.TYPE_UNDEFINED, "*");
      addScannerParamFilter("(?i)sessid", NameValuePair.TYPE_UNDEFINED, "*");
      addScannerParamFilter("__VIEWSTATE", NameValuePair.TYPE_POST_DATA, "*");
      addScannerParamFilter("__EVENTVALIDATION", NameValuePair.TYPE_POST_DATA, "*");
      addScannerParamFilter("__EVENTTARGET", NameValuePair.TYPE_POST_DATA, "*");
      addScannerParamFilter("__EVENTARGUMENT", NameValuePair.TYPE_POST_DATA, "*");
      addScannerParamFilter("(?i)jsessionid", NameValuePair.TYPE_UNDEFINED, "*");
      addScannerParamFilter("cfid", NameValuePair.TYPE_COOKIE, "*");
      addScannerParamFilter("cftoken", NameValuePair.TYPE_COOKIE, "*");
    }
  }
  public void processQueries(String instanceName, String xmlFile) {

    XMLConfiguration config = null;
    /** clear'em out */
    if (collectionQueries.get(instanceName) != null) {
      collectionQueries.get(instanceName).clear();
    }
    if (relationshipQueries.get(instanceName) != null) {
      relationshipQueries.get(instanceName).clear();
    }

    if (jdbcDriver != null) {
      jdbcDriver = null;
    }

    if (validationQuery != null) {
      validationQuery = null;
    }

    if (url != null) {
      url = null;
    }

    try {
      /**
       * use strange ethiopic unicode character so that it never delimits the properties
       *
       * <p>This is a workaround becuase config.setDelimiterParsingDisabled(true) doesn't disable
       * parsing
       */
      AbstractConfiguration.setDefaultListDelimiter('\u12BF');
      config = new XMLConfiguration(xmlFile);
      config.setDelimiterParsingDisabled(true);
      Map<String, String> instanceCollectionQueryMap = new TreeMap<String, String>();
      Map<String, String> instanceRelationshipQueryMap = new TreeMap<String, String>();
      Map<String, String> instanceAttributeQueryMap = new TreeMap<String, String>();

      @SuppressWarnings("unchecked")
      List<HierarchicalConfiguration> params = config.configurationsAt("configuration");
      for (HierarchicalConfiguration param : params) {
        this.jdbcDriver = param.getString("driver");
        this.validationQuery = param.getString("validationquery");
        this.url = param.getString("url");
        this.cycleTimeOffset = param.getInt("cycletimeoffset");
        if (log.isDebugEnabled()) {
          log.debug("jdbcDriver:" + param.getString("driver"));
          log.debug("validationQuery:" + param.getString("validationquery"));
          log.debug("url:" + param.getString("url"));
          log.debug("cycleTimeOffset:" + param.getInt("cycletimeoffset"));
        }
      }

      @SuppressWarnings("unchecked")
      List<HierarchicalConfiguration> queries = config.configurationsAt("queries.query");
      for (HierarchicalConfiguration sub : queries) {
        String name = sub.getString("name");
        String type = sub.getString("type");
        String sql = sub.getString("sql");

        if (type.equalsIgnoreCase("collection")) {
          instanceCollectionQueryMap.put(name, sql);
        } else if (type.equalsIgnoreCase("relationship")) {
          instanceRelationshipQueryMap.put(name, sql);
        } else if (type.equalsIgnoreCase("attribute")) {
          instanceAttributeQueryMap.put(name, sql);
        }
      }

      collectionQueries.put(instanceName, instanceCollectionQueryMap);
      relationshipQueries.put(instanceName, instanceRelationshipQueryMap);
      attributeQueries.put(instanceName, instanceAttributeQueryMap);

    } catch (ConfigurationException e) {
      log.error(e);
    }
  }
Exemple #28
0
  @Override
  public void call(EnunciateContext context) {
    jaxwsContext =
        new EnunciateJaxwsContext(this.jaxbModule.getJaxbContext(), isUseSourceParameterNames());
    boolean aggressiveWebMethodExcludePolicy = isAggressiveWebMethodExcludePolicy();

    Map<String, String> eiPaths = new HashMap<String, String>();
    File sunJaxwsXmlFile = getSunJaxwsXmlFile();
    if (sunJaxwsXmlFile != null) {
      XMLConfiguration config;
      try {
        config = new XMLConfiguration(sunJaxwsXmlFile);
      } catch (ConfigurationException e) {
        throw new EnunciateException(e);
      }

      List<HierarchicalConfiguration> endpoints = config.configurationsAt("endpoint");
      for (HierarchicalConfiguration endpoint : endpoints) {
        String impl = endpoint.getString("[@implementation]", null);
        String urlPattern = endpoint.getString("[@url-pattern]", null);
        if (impl != null && urlPattern != null) {
          eiPaths.put(impl, urlPattern);
        }
      }
    }

    DataTypeDetectionStrategy detectionStrategy = getDataTypeDetectionStrategy();
    if (detectionStrategy != DataTypeDetectionStrategy.passive) {
      Set<? extends Element> elements =
          detectionStrategy == DataTypeDetectionStrategy.local
              ? context.getLocalApiElements()
              : context.getApiElements();
      for (Element declaration : elements) {
        if (declaration instanceof TypeElement) {
          TypeElement element = (TypeElement) declaration;

          XmlRegistry registryMetadata = declaration.getAnnotation(XmlRegistry.class);
          if (registryMetadata != null) {
            this.jaxbModule.addPotentialJaxbElement(element, new LinkedList<Element>());
          }

          if (isEndpointInterface(element)) {
            EndpointInterface ei =
                new EndpointInterface(
                    element, elements, aggressiveWebMethodExcludePolicy, jaxwsContext);
            for (EndpointImplementation implementation : ei.getEndpointImplementations()) {
              String urlPattern = eiPaths.get(implementation.getQualifiedName().toString());
              if (urlPattern != null) {
                if (!urlPattern.startsWith("/")) {
                  urlPattern = "/" + urlPattern;
                }

                if (urlPattern.endsWith("/*")) {
                  urlPattern =
                      urlPattern.substring(0, urlPattern.length() - 2) + ei.getServiceName();
                }

                implementation.setPath(urlPattern);
              }
            }
            jaxwsContext.add(ei);
            addReferencedDataTypeDefinitions(ei);
          }
        }
      }
    }

    if (jaxwsContext.getEndpointInterfaces().size() > 0) {
      this.apiRegistry.getServiceApis().add(jaxwsContext);
      if (!this.apiRegistry.getSyntaxes().contains(jaxwsContext.getJaxbContext())) {
        this.apiRegistry.getSyntaxes().add(jaxwsContext.getJaxbContext());
      }
    }
  }
  public GraphConfigurationContainer(final List<HierarchicalConfiguration> configurations)
      throws GraphConfigurationException {

    if (configurations == null) {
      throw new GraphConfigurationException("No graph configurations");
    }

    // create one graph for each configuration for each <graph> element
    final Iterator<HierarchicalConfiguration> it = configurations.iterator();
    while (it.hasNext()) {
      final HierarchicalConfiguration graphConfig = it.next();
      final String graphName = graphConfig.getString(Tokens.REXSTER_GRAPH_NAME, "");

      if (graphName.equals("")) {
        // all graphs must have a graph name
        logger.warn("Could not load graph " + graphName + ".  The graph-name element was not set.");
        this.failedConfigurations.add(graphConfig);
      } else {
        // check for duplicate graph configuration
        if (!this.graphs.containsKey(graphName)) {

          if (graphConfig.getBoolean(Tokens.REXSTER_GRAPH_ENABLED, true)) {

            // one graph failing initialization will not prevent the rest in
            // their attempt to be created
            try {
              final Graph graph = getGraphFromConfiguration(graphConfig);
              final RexsterApplicationGraph rag = new RexsterApplicationGraph(graphName, graph);

              // loads extensions that are allowed to be served for this graph
              final List extensionConfigs =
                  graphConfig.getList(Tokens.REXSTER_GRAPH_EXTENSIONS_ALLOWS_PATH);
              rag.loadAllowableExtensions(extensionConfigs);

              // loads extension configuration for this graph
              final List<HierarchicalConfiguration> extensionConfigurations =
                  graphConfig.configurationsAt(Tokens.REXSTER_GRAPH_EXTENSIONS_PATH);
              rag.loadExtensionsConfigurations(extensionConfigurations);

              this.graphs.put(rag.getGraphName(), rag);

              logger.info("Graph " + graphName + " - " + graph + " loaded");
            } catch (GraphConfigurationException gce) {
              logger.warn(
                  "Could not load graph " + graphName + ". Please check the XML configuration.");
              logger.warn(gce.getMessage());

              if (gce.getCause() != null) {
                logger.warn(gce.getCause().getMessage());
              }

              failedConfigurations.add(graphConfig);
            } catch (Exception e) {
              logger.warn("Could not load graph " + graphName + ".", e);

              failedConfigurations.add(graphConfig);
            }
          } else {
            logger.info("Graph " + graphName + " - " + " not enabled and not loaded.");
          }
        } else {
          logger.warn(
              "A graph with the name "
                  + graphName
                  + " was already configured.  Please check the XML configuration.");

          failedConfigurations.add(graphConfig);
        }
      }
    }
  }
Exemple #30
0
  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'");
      }
      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);
        }
      }

      // pickup-locationId
      String pickupLocationId = shipmentConfig.getString("pickup.locationId");
      if (pickupLocationId != null) {
        builder.setPickupLocation(pickupLocationId);
      }

      // pickup-coord
      Coordinate pickupCoord = getCoord(shipmentConfig, "pickup.");
      if (pickupCoord != null) {
        builder.setPickupCoord(pickupCoord);
        if (pickupLocationId != null) {
          //					vrpBuilder.addLocation(pickupLocationId,pickupCoord);
        } else {
          //					vrpBuilder.addLocation(pickupCoord.toString(),pickupCoord);
          builder.setPickupLocation(pickupCoord.toString());
        }
      }
      // 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-locationId
      String deliveryLocationId = shipmentConfig.getString("delivery.locationId");
      if (deliveryLocationId != null) {
        builder.setDeliveryLocation(deliveryLocationId);
      }

      // delivery-coord
      Coordinate deliveryCoord = getCoord(shipmentConfig, "delivery.");
      if (deliveryCoord != null) {
        builder.setDeliveryCoord(deliveryCoord);
        if (deliveryLocationId != null) {
          //					vrpBuilder.addLocation(deliveryLocationId,deliveryCoord);
        } else {
          //					vrpBuilder.addLocation(deliveryCoord.toString(),deliveryCoord);
          builder.setDeliveryLocation(deliveryCoord.toString());
        }
      }
      // 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);
      }

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