Exemplo n.º 1
0
  /** implemented. */
  public void test_propertyNames() {
    th.checkPoint("propertyNames()java.util.Enumeration");
    Properties p = new Properties();
    try {
      p.load(bin);
    } catch (Exception e) {
    }

    Enumeration en = p.propertyNames();
    Enumeration ek = p.keys();
    boolean ok = true;
    Vector v = new Vector();
    Enumeration ek2 = p.keys();
    while (ek2.hasMoreElements()) {
      v.add(ek2.nextElement());
    }
    while (ek.hasMoreElements() && en.hasMoreElements()) {
      ek.nextElement();
      Object next = en.nextElement();
      if (!v.contains(next)) {
        ok = false;
        th.debug(next + " not in " + v);
      }
    }
    th.check(ok, "all elements are the same");
    th.check(
        !ek.hasMoreElements() && !en.hasMoreElements(), "make sure both enumerations are empty");
    p = new Properties(defProps);
    resetStreams();
    try {
      p.load(bin);
    } catch (Exception e) {
    }
    v.add("Smart");
    v.add("animal");
    en = p.propertyNames();
    ok = true;
    Object o;
    while (en.hasMoreElements()) {
      o = en.nextElement();
      if (v.contains(o)) v.removeElement(o);
      else {
        ok = false;
        th.debug("got extra element: " + o);
      }
    }
    th.check(ok, "see if no double were generated");
    th.check(v.isEmpty(), "check if all names were mentioned -- got:" + v);
  }
Exemplo n.º 2
0
  public Map getSystemProperties() {
    Map map = new HashMap();
    Properties props = System.getProperties();

    for (Enumeration e = props.keys(); e.hasMoreElements(); ) {
      String key = (String) e.nextElement();
      String val = (String) props.get(key);
      map.put(key, val);
    }
    return map;
  }
Exemplo n.º 3
0
 String hasProp(String prop, Properties p) {
   if (p == null) return null;
   Enumeration e = p.keys();
   while (e.hasMoreElements()) {
     String key = (String) e.nextElement();
     String val = p.getProperty(key);
     if (key.equalsIgnoreCase(prop)) {
       return val;
     }
   }
   return null;
 }
  /** {@inheritDoc} */
  public SynapseConfiguration createSynapseConfiguration() {

    String synapseXMLLocation = serverConfigurationInformation.getSynapseXMLLocation();
    Properties properties = SynapsePropertiesLoader.loadSynapseProperties();
    if (serverConfigurationInformation.getResolveRoot() != null) {
      properties.put(
          SynapseConstants.RESOLVE_ROOT, serverConfigurationInformation.getResolveRoot());
    }

    if (serverConfigurationInformation.getSynapseHome() != null) {
      properties.put(
          SynapseConstants.SYNAPSE_HOME, serverConfigurationInformation.getSynapseHome());
    }

    if (synapseXMLLocation != null) {
      synapseConfiguration =
          SynapseConfigurationBuilder.getConfiguration(synapseXMLLocation, properties);
    } else {
      log.warn(
          "System property or init-parameter '"
              + SynapseConstants.SYNAPSE_XML
              + "' is not specified. Using default configuration..");
      synapseConfiguration = SynapseConfigurationBuilder.getDefaultConfiguration();
    }

    Enumeration keys = properties.keys();
    while (keys.hasMoreElements()) {
      String key = (String) keys.nextElement();
      synapseConfiguration.setProperty(key, properties.getProperty(key));
    }

    // Set the Axis2 ConfigurationContext to the SynapseConfiguration
    synapseConfiguration.setAxisConfiguration(configurationContext.getAxisConfiguration());
    MessageContextCreatorForAxis2.setSynConfig(synapseConfiguration);

    // set the Synapse configuration into the Axis2 configuration
    Parameter synapseConfigurationParameter =
        new Parameter(SynapseConstants.SYNAPSE_CONFIG, synapseConfiguration);
    try {
      configurationContext.getAxisConfiguration().addParameter(synapseConfigurationParameter);
    } catch (AxisFault e) {
      handleFatal(
          "Could not set parameters '"
              + SynapseConstants.SYNAPSE_CONFIG
              + "' to the Axis2 configuration : "
              + e.getMessage(),
          e);
    }

    addServerIPAndHostEntries();

    return synapseConfiguration;
  }
 private static int getMaxLength(Properties props) {
   Enumeration<Object> keys = props.keys();
   int maxLength = -1;
   while (keys.hasMoreElements()) {
     String key = (String) keys.nextElement();
     if (maxLength < 0) {
       maxLength = key.getBytes().length;
     } else if (maxLength < key.getBytes().length) {
       maxLength = key.getBytes().length;
     }
   }
   return maxLength;
 }
 private static void print(StringBuilder builder, Properties props) {
   int maxLength = getMaxLength(props);
   Enumeration<Object> keys = props.keys();
   while (keys.hasMoreElements()) {
     String key = (String) keys.nextElement();
     String value = props.getProperty(key);
     builder
         .append("  ")
         .append(key)
         .append(getCharacter(maxLength - key.getBytes().length, " "))
         .append(" : ")
         .append(value)
         .append("\n");
   }
 }
Exemplo n.º 7
0
  public void testInvalid() {
    Enumeration e = invalidRsls.keys();
    String key;
    String rsl;
    while (e.hasMoreElements()) {
      key = (String) e.nextElement();
      rsl = invalidRsls.getProperty(key);

      System.out.println("Parsing invalid rsl " + key + ": " + rsl);
      try {
        RslNode tree = RSLParser.parse(rsl);
        fail("Failed to catch parse error of " + rsl);
      } catch (Exception ex) {
      }
    }
  }
Exemplo n.º 8
0
  public void testValid() {
    Enumeration e = validRsls.keys();
    String key;
    String rsl;
    while (e.hasMoreElements()) {
      key = (String) e.nextElement();
      rsl = validRsls.getProperty(key);

      System.out.println("Parsing valid rsl " + key + ": " + rsl);
      try {
        RSLParser.parse(rsl);
      } catch (Exception ex) {
        ex.printStackTrace();
        fail("Failed to parse!!!");
      }
    }
  }
Exemplo n.º 9
0
  /**
   * This method is used to get the String that contain key value pair from the propertise.
   *
   * @param String
   * @return String.
   */
  public String list(String propfile) {
    Properties properties = (Properties) cachedPropertyFiles.get(propfile);
    if (properties == null) return "";

    synchronized (properties) {
      StringBuffer buf = new StringBuffer(properties.size() * 50);

      for (Enumeration e = properties.keys(); e.hasMoreElements(); ) {
        String key = (String) e.nextElement();
        String val = (String) properties.get(key);
        if (val.length() > 40) {
          val = val.substring(0, 37) + "...";
        }
        buf.append(key);
        buf.append('=');
        buf.append(val);
        buf.append('\n');
      }
      return buf.toString();
    }
  }
Exemplo n.º 10
0
 /** this test will check if all forms lines are accepted in the load. */
 public void test_loadextra() {
   th.checkPoint("load(java.io.InputStream)void");
   Properties p = new Properties();
   buffer =
       new String(
               "   !comment\n \t  \nname = no\r    #morec\tomm\\\nents\r\n  dog=no\\\\cat   \nburps    :\ntest=\ndate today\n\n\nlong\\\n   value=tryin \\\n gto\n4:vier\nvier     :4")
           .getBytes();
   bin = new ByteArrayInputStream(buffer);
   try {
     p.load(bin);
   } catch (Exception e) {
   }
   Enumeration e = p.keys();
   Vector v = new Vector();
   // Note that there used to be code here checking whether the
   // "!comment" and "#morec" keys were found, on the theory that
   // leading whitespace mattered.  This no longer seems to be the
   // case, however.  In the past it apparently varied between JVMs,
   // but the 1.4 docs are unambiguous on this topic.  We check for
   // "ents" since line-continuation doesn't affect comments.
   v.add("ents=");
   v.add("name=no");
   v.add("dog=no\\cat   ");
   v.add("burps=");
   v.add("test=");
   v.add("date=today");
   v.add("longvalue=tryin gto");
   v.add("4=vier");
   v.add("vier=4");
   String s;
   while (e.hasMoreElements()) {
     s = (String) e.nextElement();
     th.debug("checkvalue -- got:$" + s + "=" + p.getProperty(s) + "$");
     th.check(
         v.contains(s + "=" + p.getProperty(s)),
         "checkvalue -- got:$" + s + "=" + p.getProperty(s) + "$");
     v.removeElement(s + "=" + p.getProperty(s));
   }
   th.check(v.isEmpty(), "check if all elements were found -- got: " + v);
 }
  public Map<String, HGLocation> getLocationList(String prefix)
      throws NumberFormatException, UnsupportedEncodingException {
    // iterate over props looking for keys that start with loc.
    Map<String, HGLocation> locations = new HashMap<String, HGLocation>();
    // HashSet<HGLocation> locations = new HashSet<HGLocation>();

    for (Enumeration<Object> e = worldlyProperties.keys(); e.hasMoreElements(); /**/ ) {
      String key = (String) e.nextElement();
      // String value = worldlyProperties.getProperty(key);
      // System.out.println(key + " = " + value);

      // Iterator<Object> iter = worldlyProperties.keySet().iterator();
      // for (String key = null; iter.hasNext(); key = (String) iter.next()) {
      if (key.startsWith(prefix)) {
        // populate locations
        String locArgs = worldlyProperties.getProperty(key);
        if (locArgs != null && !locArgs.isEmpty()) {
          String[] parts = locArgs.split(",");
          if (parts.length == 9) {
            HGLocation location =
                new HGLocation(
                    URLDecoder.decode(parts[0], HGStatics.UTF8), // playername
                    URLDecoder.decode(parts[1], HGStatics.UTF8), // locationname
                    URLDecoder.decode(parts[2], HGStatics.UTF8), // worldname
                    Integer.parseInt(URLDecoder.decode(parts[3], HGStatics.UTF8)), // x
                    Integer.parseInt(URLDecoder.decode(parts[4], HGStatics.UTF8)), // y
                    Integer.parseInt(URLDecoder.decode(parts[5], HGStatics.UTF8)), // z
                    Float.parseFloat(URLDecoder.decode(parts[6], HGStatics.UTF8)), // pitch
                    Float.parseFloat(URLDecoder.decode(parts[7], HGStatics.UTF8)), // yaw
                    Long.parseLong(URLDecoder.decode(parts[8], HGStatics.UTF8)));
            locations.put(parts[0] + parts[1], location);
          }
        }
      }
    }
    return locations;
  }
  /**
   * Loads the installation data. Also sets environment variables to <code>installdata</code>. All
   * system properties are available as $SYSTEM_<variable> where <variable> is the actual name _BUT_
   * with all separators replaced by '_'. Properties with null values are never stored. Example:
   * $SYSTEM_java_version or $SYSTEM_os_name
   *
   * @param installdata Where to store the installation data.
   * @throws Exception Description of the Exception
   */
  public void loadInstallData(AutomatedInstallData installdata) throws Exception {
    // Usefull variables
    InputStream in;
    ObjectInputStream objIn;
    int size;
    int i;

    // We load the variables
    Properties variables = null;
    in = InstallerBase.class.getResourceAsStream("/vars");
    if (null != in) {
      objIn = new ObjectInputStream(in);
      variables = (Properties) objIn.readObject();
      objIn.close();
    }

    // We load the Info data
    in = InstallerBase.class.getResourceAsStream("/info");
    objIn = new ObjectInputStream(in);
    Info inf = (Info) objIn.readObject();
    objIn.close();

    // We put the Info data as variables
    installdata.setVariable(ScriptParser.APP_NAME, inf.getAppName());
    if (inf.getAppURL() != null) {
      installdata.setVariable(ScriptParser.APP_URL, inf.getAppURL());
    }
    installdata.setVariable(ScriptParser.APP_VER, inf.getAppVersion());
    if (inf.getUninstallerCondition() != null) {
      installdata.setVariable("UNINSTALLER_CONDITION", inf.getUninstallerCondition());
    }
    // We read the panels order data
    in = InstallerBase.class.getResourceAsStream("/panelsOrder");
    objIn = new ObjectInputStream(in);
    List panelsOrder = (List) objIn.readObject();
    objIn.close();

    // We read the packs data
    in = InstallerBase.class.getResourceAsStream("/packs.info");
    objIn = new ObjectInputStream(in);
    size = objIn.readInt();
    ArrayList availablePacks = new ArrayList();
    ArrayList<Pack> allPacks = new ArrayList<Pack>();
    for (i = 0; i < size; i++) {
      Pack pk = (Pack) objIn.readObject();
      allPacks.add(pk);
      if (OsConstraint.oneMatchesCurrentSystem(pk.osConstraints)) {
        availablePacks.add(pk);
      }
    }
    objIn.close();

    // We determine the operating system and the initial installation path
    String dir;
    String installPath;
    if (OsVersion.IS_WINDOWS) {
      dir = buildWindowsDefaultPath();
    } else if (OsVersion.IS_OSX) {
      dir = "/Applications";
    } else {
      if (new File("/usr/local/").canWrite()) {
        dir = "/usr/local";
      } else {
        dir = System.getProperty("user.home");
      }
    }

    // We determine the hostname and IPAdress
    String hostname;
    String IPAddress;

    try {
      InetAddress addr = InetAddress.getLocalHost();

      // Get IP Address
      IPAddress = addr.getHostAddress();

      // Get hostname
      hostname = addr.getHostName();
    } catch (Exception e) {
      hostname = "";
      IPAddress = "";
    }

    installdata.setVariable("APPLICATIONS_DEFAULT_ROOT", dir);
    dir += File.separator;
    installdata.setVariable(ScriptParser.JAVA_HOME, System.getProperty("java.home"));
    installdata.setVariable(ScriptParser.CLASS_PATH, System.getProperty("java.class.path"));
    installdata.setVariable(ScriptParser.USER_HOME, System.getProperty("user.home"));
    installdata.setVariable(ScriptParser.USER_NAME, System.getProperty("user.name"));
    installdata.setVariable(ScriptParser.IP_ADDRESS, IPAddress);
    installdata.setVariable(ScriptParser.HOST_NAME, hostname);
    installdata.setVariable(ScriptParser.FILE_SEPARATOR, File.separator);

    Enumeration e = System.getProperties().keys();
    while (e.hasMoreElements()) {
      String varName = (String) e.nextElement();
      String varValue = System.getProperty(varName);
      if (varValue != null) {
        varName = varName.replace('.', '_');
        installdata.setVariable("SYSTEM_" + varName, varValue);
      }
    }

    if (null != variables) {
      Enumeration enumeration = variables.keys();
      String varName;
      String varValue;
      while (enumeration.hasMoreElements()) {
        varName = (String) enumeration.nextElement();
        varValue = variables.getProperty(varName);
        installdata.setVariable(varName, varValue);
      }
    }

    installdata.info = inf;
    installdata.panelsOrder = panelsOrder;
    installdata.availablePacks = availablePacks;
    installdata.allPacks = allPacks;

    // get list of preselected packs
    Iterator pack_it = availablePacks.iterator();
    while (pack_it.hasNext()) {
      Pack pack = (Pack) pack_it.next();
      if (pack.preselected) {
        installdata.selectedPacks.add(pack);
      }
    }
    // Set the installation path in a default manner
    installPath = dir + inf.getAppName();
    if (inf.getInstallationSubPath() != null) { // A subpath was defined, use it.
      installPath =
          IoHelper.translatePath(
              dir + inf.getInstallationSubPath(),
              new VariableSubstitutor(installdata.getVariables()));
    }
    installdata.setInstallPath(installPath);
    // Load custom action data.
    loadCustomData(installdata);
  }
Exemplo n.º 13
0
  /**
   * implemented. <br>
   * Add a test to determine of store generates a comment line with the current time <br>
   * <br>
   * depricated method !!!
   */
  public void test_save() {
    th.checkPoint("save(java.io.OutputStream,java.lang.String)void");
    Properties p = new Properties(defProps);
    try {
      p.save(null, "no comment");
      th.fail("should throw NullPointerException");
    } catch (NullPointerException ne) {
      th.check(true);
    } catch (Exception e) {
      th.fail("should throw an NullPointerEception instead of: " + e);
    }

    try {
      p.save(bout, null);
      th.check(true);
    } catch (NullPointerException ne) {
      th.fail("should not throw NullPointerException");
    } catch (Exception e) {
      th.fail("shouldn't throw any Exception, but got: " + e);
    }

    resetStreams();
    try {
      p.save(bout, null);
    } catch (Exception e) {
      th.fail("shouldn't throw any Exception, but got: " + e);
    }
    byte ba[] = bout.toByteArray();
    th.check((ba[0] == (byte) '#') && (ba[1] != (byte) '#'), "just date should be written");
    th.debug(ba.length + " -- got: " + new String(ba));
    th.check(ba.length < 50, "default properties are never printed out");
    resetStreams();
    try {
      p.load(bin);
    } catch (Exception e) {
    }
    try {
      p.save(bout, "no comments");
    } catch (Exception e) {
      th.fail("shouldn't throw any Exception, but got: " + e);
    }
    ba = bout.toByteArray();
    String s = new String(ba, 0, 12);
    th.check(s.equals("#no comments"), "got: " + s);
    int i = 0, count = 0;
    while (i < 2 && count < ba.length) {
      if (ba[count++] == (byte) '\n') i++;
    }
    // we will construct a vector containing all the lines with should be written
    Vector v = new Vector();
    Enumeration ek = p.keys();
    while (ek.hasMoreElements()) {
      s = (String) ek.nextElement();
      v.add(s + "=" + p.getProperty(s));
    }
    while (count < ba.length) {
      int start = count;
      while (count < ba.length) {
        if (ba[count] != '\n') count++;
        else break;
      }
      s = new String(ba, start, count - start);
      th.check(v.contains(s), "v does not contain: " + s);
      v.removeElement(s);
      count++;
    }
  }
Exemplo n.º 14
0
    public void doGeneric(String method, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
      try {
        startTransaction(request.getHeader("User-Agent"));

        // Marshal Jetty request parameters to Nano-style.

        // Note that getServletPath does an un-escape so that the %24 of job id's are turned into $
        // characters.
        String uri = request.getServletPath();

        Properties headers = new Properties();
        Enumeration<String> en = request.getHeaderNames();
        while (en.hasMoreElements()) {
          String key = en.nextElement();
          String value = request.getHeader(key);
          headers.put(key, value);
        }

        Properties parms = new Properties();
        Map<String, String[]> parameterMap;
        parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> entry : parameterMap.entrySet()) {
          String key = entry.getKey();
          String[] values = entry.getValue();
          for (String value : values) {
            parms.put(key, value);
          }
        }

        // Make Nano call.
        NanoHTTPD.Response resp = water.api.RequestServer.SERVER.serve(uri, method, headers, parms);

        // Un-marshal Nano response back to Jetty.
        String choppedNanoStatus = resp.status.substring(0, 3);
        assert (choppedNanoStatus.length() == 3);
        int sc = Integer.parseInt(choppedNanoStatus);
        setResponseStatus(response, sc);

        response.setContentType(resp.mimeType);

        Properties header = resp.header;
        Enumeration<Object> en2 = header.keys();
        while (en2.hasMoreElements()) {
          String key = (String) en2.nextElement();
          String value = header.getProperty(key);
          response.setHeader(key, value);
        }

        OutputStream os = response.getOutputStream();
        if (resp instanceof NanoHTTPD.StreamResponse) {
          NanoHTTPD.StreamResponse ssr = (NanoHTTPD.StreamResponse) resp;
          ssr.streamWriter.writeTo(os);
        } else {
          InputStream is = resp.data;
          FileUtils.copyStream(is, os, 1024);
        }
      } finally {
        logRequest(method, request, response);
        // Handle shutdown if it was requested.
        if (H2O.getShutdownRequested()) {
          (new Thread() {
                public void run() {
                  boolean[] confirmations = new boolean[H2O.CLOUD.size()];
                  if (H2O.SELF.index() >= 0) {
                    confirmations[H2O.SELF.index()] = true;
                  }
                  for (H2ONode n : H2O.CLOUD._memary) {
                    if (n != H2O.SELF)
                      new RPC(n, new ShutdownTsk(H2O.SELF, n.index(), 1000, confirmations)).call();
                  }
                  try {
                    Thread.sleep(2000);
                  } catch (Exception ignore) {
                  }
                  int failedToShutdown = 0;
                  // shutdown failed
                  for (boolean b : confirmations) if (!b) failedToShutdown++;
                  Log.info(
                      "Orderly shutdown: "
                          + (failedToShutdown > 0
                              ? failedToShutdown + " nodes failed to shut down! "
                              : "")
                          + " Shutting down now.");
                  H2O.closeAll();
                  H2O.exit(failedToShutdown);
                }
              })
              .start();
        }
        endTransaction();
      }
    }
Exemplo n.º 15
0
  /**
   * implemented. <br>
   * load is used by other tests to make a propeties file <br>
   * failures in load will mak other tests fail !
   */
  public void test_load() {
    th.checkPoint("load(java.io.InputStream)void");
    Properties p = new Properties();
    try {
      p.load((ByteArrayInputStream) null);
      th.fail("should throw NullPointerException");
    } catch (NullPointerException ne) {
      th.check(true);
    } catch (Exception e) {
      th.fail("should throw an NullPointerException instead of: " + e);
    }

    try {
      p.load(bin);
    } catch (Exception e) {
    }
    Enumeration ek1 = p.keys();
    resetStreams();
    try {
      p.load(bin);
    } catch (Exception e) {
    }
    Enumeration ek2 = p.keys();
    boolean ok = true;
    while (ek1.hasMoreElements() && ek2.hasMoreElements()) {
      if (ek1.nextElement() != ek2.nextElement()) ok = false;
    }
    th.check(
        !ek1.hasMoreElements() && !ek2.hasMoreElements(),
        "no extra elements may be added with same name");
    th.check(ok, " all elements are equal ");
    bin = new ByteArrayInputStream(new String("name=yes\nSmart=move\nanimal=dog").getBytes());
    try {
      p.load(bin);
    } catch (Exception e) {
    }
    th.check(p.getProperty("name").equals("yes"), "load overrides previous values");
    Vector v = new Vector();
    v.add("name");
    v.add("Smart");
    v.add("animal");
    v.add("dog");
    v.add("test");
    v.add("date");
    v.add("longvalue");
    v.add("40chars");
    ek1 = p.keys();
    ok = true;
    Object o;
    while (ek1.hasMoreElements()) {
      o = ek1.nextElement();
      if (v.contains(o)) v.removeElement(o);
      else {
        ok = false;
        th.debug("got extra element: " + (String) o);
      }
    }

    th.check(ok, "all elements were there");
    th.check(v.isEmpty(), "all elements should be gone, got" + v);
    setUpTest();
  }
Exemplo n.º 16
0
  /** implemented. */
  public void test_list() {
    th.checkPoint("list(java.io.PrintStream)void");
    Properties p = new Properties();
    try {
      p.list((PrintStream) null);
      th.fail("should throw NullPointerException -- 1");
    } catch (NullPointerException ne) {
      th.check(true);
    }

    try {
      p.load(bin);
    } catch (Exception e) {
    }
    p.list(psout);
    byte ba[] = bout.toByteArray();
    Vector v = new Vector();
    Enumeration ek = p.keys();
    String s;
    while (ek.hasMoreElements()) {
      s = (String) ek.nextElement();
      v.add(s + "=" + p.getProperty(s));
    }
    v.add("Smart=move");
    v.add("animal=dog");

    int start, count = 0;
    v.removeElement("longvalue=I'mtryingtogiveavaluelongerthen40characters");
    v.add("longvalue=I'mtryingtogiveavaluelongerthen40char...");
    while (count < ba.length) {
      start = count;
      while (ba[count] != '\n' && count < ba.length) {
        count++;
      }
      s = new String(ba, start, count - start);
      if (!s.startsWith("--")) // list() adds a header
      th.check(v.contains(s), "v does not contain:$" + s + "$");
      v.removeElement(s);
      count++;
    }

    try {
      p.list((PrintStream) null);
      th.fail("should throw NullPointerException -- 2");
    } catch (NullPointerException ne) {
      th.check(true);
    }

    th.checkPoint("list(java.io.PrintWriter)void");
    resetStreams();
    p = new Properties();
    try {
      p.list((PrintWriter) null);
      th.fail("should throw NullPointerException -- 1");
    } catch (NullPointerException ne) {
      th.check(true);
    }

    try {
      p.load(bin);
    } catch (Exception e) {
    }
    p.list(pwout);
    ba = bout.toByteArray();
    v = new Vector();
    ek = p.keys();
    while (ek.hasMoreElements()) {
      s = (String) ek.nextElement();
      v.add(s + "=" + p.getProperty(s));
    }
    v.add("Smart=move");
    v.add("animal=dog");

    count = 0;
    v.removeElement("longvalue=I'mtryingtogiveavaluelongerthen40characters");
    v.add("longvalue=I'mtryingtogiveavaluelongerthen40char...");

    while (count < ba.length) {
      start = count;
      while (ba[count] != '\n' && count < ba.length) {
        count++;
      }
      s = new String(ba, start, count - start);
      if (!s.startsWith("--")) // list() adds a header
      th.check(v.contains(s), "v does not contain:$" + s + "$");
      v.removeElement(s);
      count++;
    }

    try {
      p.list((PrintStream) null);
      th.fail("should throw NullPointerException -- 2");
    } catch (NullPointerException ne) {
      th.check(true);
    }
  }
Exemplo n.º 17
0
  /**
   * Construct a new MappedMessageHandler from the provided configuration.
   *
   * @param config the {@link MessageHandlerConfiguration} used to configure this instance
   * @throws ToolkitException rethrown from {@link
   *     MessageHandlerConfigurationFactory#getConfiguration()}.
   */
  public MappedMessageHandler(MessageHandlerConfiguration config) throws ToolkitException {

    supportedServices = new HashMap<String, NCIPService<NCIPInitiationData, NCIPResponseData>>();
    Properties properties = config.getProperties();
    for (Enumeration enumeration = properties.keys(); enumeration.hasMoreElements(); /**/ ) {
      String key = (String) enumeration.nextElement();
      LOG.debug("Property key=" + key);
      if (key.compareToIgnoreCase("java.version") == 0) {
        LOG.debug("Java version is " + properties.get(key));
      }
      if (key.matches("(?i)[A-Za-z]+Service\\.Class")) {
        String className = (String) properties.get(key);
        LOG.debug("Class name=" + className);

        if (className == null
            || className.isEmpty()
            || className.compareToIgnoreCase("null") == 0) {

          continue;
        }

        try {

          Class<?> clazz = Class.forName(className);
          Class<? extends NCIPService> xc = clazz.asSubclass(NCIPService.class);
          LOG.debug("Class as subclass=" + xc.getName());

          try {

            NCIPService<NCIPInitiationData, NCIPResponseData> serviceInstance;

            try {

              Constructor<? extends NCIPService> propertiesCtor =
                  xc.getConstructor(Properties.class);
              serviceInstance = propertiesCtor.newInstance(properties);

            } catch (NoSuchMethodException e) {

              serviceInstance = xc.newInstance();

            } catch (InvocationTargetException e) {

              throw new ToolkitException(
                  "Exception constructing " + className + " using Properties:", e);
            }

            Method[] methods = clazz.getMethods();
            Class initDataClass = null;
            // TODO: Try replacing this with getMethod("performService", NCIPInitiationData.class,
            // ServiceContext.class, RemoteServiceManager.class);
            for (Method method : methods) {

              LOG.debug("Testing method " + method.getName());

              if (method.getName().compareToIgnoreCase("performService") == 0) {

                LOG.debug("Method is performService.");

                Class[] parameterTypes = method.getParameterTypes();

                // This assumes there will only be one performService method on any class,
                // i.e. the one required by the NCIPService interface definition.
                // While the definition of NCIPService doesn't actually enforce this,
                // it would be perverse to define an additional method with that name
                // taking similar parameter types.
                if (parameterTypes.length == NUMBER_OF_PARAMETERS_TO_PERFORM_SERVICE_METHOD) {

                  LOG.debug("Method takes " + parameterTypes.length + " parameters.");

                  Class parameterClass = parameterTypes[0];
                  LOG.debug("ParameterType[0] is " + parameterClass.getName());

                  if (parameterClass.getName().compareTo(Class.class.getName()) != 0) {

                    initDataClass = parameterClass;
                    if (initDataClass.getName().compareTo(Object.class.getName()) == 0) {
                      LOG.warn(
                          "Class first parameter is 'Object'; trying to use property key to get actual initDataClass.");
                      String serviceName =
                          key.substring(0, key.length() - "Service.Class".length());
                      initDataClass = ServiceHelper.constructInitiationDataClass(serviceName);
                    } else {
                      LOG.debug("The initDataClass is not 'Object'.");
                    }
                    LOG.debug("Selecting " + initDataClass.getName() + " as initDataClass.");
                    break;

                  } else {

                    LOG.debug(
                        "The performService method for class "
                            + clazz.getName()
                            + " takes a Class parameter, which is disallowed.");
                  }

                } else {

                  LOG.debug(
                      "The performService method for class "
                          + clazz.getName()
                          + " has no parameters.");
                }
              } else {

                LOG.debug("Method is not performService.");
              }
            }
            LOG.debug("Finished checking methods.");

            if (initDataClass != null) {

              LOG.debug(
                  "Putting "
                      + serviceInstance.getClass().getName()
                      + " into supportedServices map "
                      + "with key of "
                      + initDataClass.getName()
                      + ".");
              supportedServices.put(initDataClass.getName(), serviceInstance);

            } else {

              throw new ToolkitException(
                  "Unable to determine NCIPInitiationData sub-class with "
                      + "name '"
                      + className
                      + "' for "
                      + key);
            }

          } catch (InstantiationException e) {
            throw new ToolkitException("Exception while populating supported services.", e);
          } catch (IllegalAccessException e) {
            throw new ToolkitException("Exception while populating supported services.", e);
          }

        } catch (ClassNotFoundException e) {

          throw new ToolkitException(
              "Class not found exception while populating supported services.", e);
        }

      } else if (key.matches("(?i)RemoteServiceManager\\.Class")) {

        try {
          Class<?> clazz = Class.forName(properties.getProperty(key));
          Constructor ctor = clazz.getConstructor(Properties.class);
          serviceManager = (RemoteServiceManager) ctor.newInstance(properties);
        } catch (ClassNotFoundException e) {
          throw new ToolkitException("Exception while populating supported services.", e);
        } catch (NoSuchMethodException e) {
          throw new ToolkitException("Exception while populating supported services.", e);
        } catch (InvocationTargetException e) {
          throw new ToolkitException("Exception while populating supported services.", e);
        } catch (InstantiationException e) {
          throw new ToolkitException("Exception while populating supported services.", e);
        } catch (IllegalAccessException e) {
          throw new ToolkitException("Exception while populating supported services.", e);
        }
      }
    }
    LOG.debug("Finished with properties.");
    if (LOG.isDebugEnabled()) {

      LOG.debug("Service map for " + this + ":");
      for (Map.Entry<String, NCIPService<NCIPInitiationData, NCIPResponseData>> entry :
          supportedServices.entrySet()) {

        LOG.debug(entry.getKey() + "=" + entry.getValue());
      }
    }
  }