Exemple #1
0
  public CloudScriptObject eval(Context context) throws CloudScriptException {
    CloudScriptClass clazz = context.getCurrentClass();

    for (Map.Entry<String, String> entry : data.entrySet()) {
      final String key = entry.getKey();
      final String value = entry.getValue();

      if (!clazz.hasMethod(key)) {
        clazz.addMethod(
            key,
            new Method() {
              public CloudScriptObject call(
                  CloudScriptObject receiver, CloudScriptObject arguments[])
                  throws CloudScriptException {
                ValueObject content = new ValueObject(value);
                int numValue;

                try {
                  numValue = Integer.parseInt(value);
                  content = new ValueObject(numValue);
                } catch (NumberFormatException e) {
                }

                return content;
              }
            });
      }
    }
    return new ValueObject(this.content);
  }
  public Set<String> getOperatorClasses(String parent, String searchTerm)
      throws ClassNotFoundException {
    if (CollectionUtils.isEmpty(operatorClassNames)) {
      loadOperatorClass();
    }
    if (parent == null) {
      parent = Operator.class.getName();
    } else {
      if (!typeGraph.isAncestor(Operator.class.getName(), parent)) {
        throw new IllegalArgumentException("Argument must be a subclass of Operator class");
      }
    }

    Set<String> filteredClass =
        Sets.filter(
            operatorClassNames,
            new Predicate<String>() {
              @Override
              public boolean apply(String className) {
                OperatorClassInfo oci = classInfo.get(className);
                return oci == null || !oci.tags.containsKey("@omitFromUI");
              }
            });

    if (searchTerm == null && parent.equals(Operator.class.getName())) {
      return filteredClass;
    }

    if (searchTerm != null) {
      searchTerm = searchTerm.toLowerCase();
    }

    Set<String> result = new HashSet<String>();
    for (String clazz : filteredClass) {
      if (parent.equals(Operator.class.getName()) || typeGraph.isAncestor(parent, clazz)) {
        if (searchTerm == null) {
          result.add(clazz);
        } else {
          if (clazz.toLowerCase().contains(searchTerm)) {
            result.add(clazz);
          } else {
            OperatorClassInfo oci = classInfo.get(clazz);
            if (oci != null) {
              if (oci.comment != null && oci.comment.toLowerCase().contains(searchTerm)) {
                result.add(clazz);
              } else {
                for (Map.Entry<String, String> entry : oci.tags.entrySet()) {
                  if (entry.getValue().toLowerCase().contains(searchTerm)) {
                    result.add(clazz);
                    break;
                  }
                }
              }
            }
          }
        }
      }
    }
    return result;
  }
  public AuthenticatorWindow() {
    SESecurityManager.addPasswordListener(this);

    // System.out.println( "AuthenticatorWindow");

    Map cache = COConfigurationManager.getMapParameter(CONFIG_PARAM, new HashMap());

    try {
      Iterator it = cache.entrySet().iterator();

      while (it.hasNext()) {

        Map.Entry entry = (Map.Entry) it.next();

        String key = (String) entry.getKey();
        Map value = (Map) entry.getValue();

        String user = new String((byte[]) value.get("user"), "UTF-8");
        char[] pw = new String((byte[]) value.get("pw"), "UTF-8").toCharArray();

        auth_cache.put(key, new authCache(key, new PasswordAuthentication(user, pw), true));
      }

    } catch (Throwable e) {

      COConfigurationManager.setParameter(CONFIG_PARAM, new HashMap());

      Debug.printStackTrace(e);
    }
  }
  public static void main(String[] args) {
    String host = args[0];
    int port = Integer.parseInt(args[1]);
    long id = Long.parseLong(args[2]);
    String character = args[3];
    long actorId = Long.parseLong(args[4]);

    // Install an RMISecurityManager, if there is not a
    // SecurityManager already installed
    if (System.getSecurityManager() == null) {
      System.setSecurityManager(new RMISecurityManager());
    }

    String name = "rmi://" + host + ":" + port + "/MovieDatabase";

    try {
      MovieDatabase db = (MovieDatabase) Naming.lookup(name);
      db.noteCharacter(id, character, actorId);

      Movie movie = db.getMovie(id);
      out.println(movie.getTitle());
      for (Map.Entry entry : movie.getCharacters().entrySet()) {
        out.println("  " + entry.getKey() + "\t" + entry.getValue());
      }

    } catch (RemoteException | NotBoundException | MalformedURLException ex) {
      ex.printStackTrace(System.err);
    }
  }
Exemple #5
0
 public static void main(String[] args) {
   try {
     if (args.length == 1) {
       URL url = new URL(args[0]);
       System.out.println("Content-Type: " + url.openConnection().getContentType());
       // 				Vector links = extractLinks(url);
       // 				for (int n = 0; n < links.size(); n++) {
       // 					System.out.println((String) links.elementAt(n));
       // 				}
       Set links = extractLinksWithText(url).entrySet();
       Iterator it = links.iterator();
       while (it.hasNext()) {
         Map.Entry en = (Map.Entry) it.next();
         String strLink = (String) en.getKey();
         String strText = (String) en.getValue();
         System.out.println(strLink + " \"" + strText + "\" ");
       }
       return;
     } else if (args.length == 2) {
       writeURLtoFile(new URL(args[0]), args[1]);
       return;
     }
   } catch (Exception e) {
     System.err.println("An error occured: ");
     e.printStackTrace();
     // 			System.err.println(e.toString());
   }
   System.err.println("Usage: java SaveURL <url> [<file>]");
   System.err.println("Saves a URL to a file.");
   System.err.println("If no file is given, extracts hyperlinks on url to console.");
 }
Exemple #6
0
  @SuppressWarnings({"unchecked", "rawtypes"})
  private static Hashtable<Pair<DayPart, Weather>, String> getDetails(Map<String, Object> map)
      throws MissingMappingException, UnexpectedTypeException {
    Hashtable<Pair<DayPart, Weather>, String> details =
        new Hashtable<Pair<DayPart, Weather>, String>();

    Map<String, Map<String, String>> timesOfDay = (Map) validateAndGet(map, "detail", Map.class);

    // for each mapping in "detail" (e.g., for "day" -> ...)
    for (Map.Entry<String, Map<String, String>> todMapping : timesOfDay.entrySet()) {
      String key = todMapping.getKey();
      DayPart half = null;

      if (key.equals("day")) half = DayPart.DAY;
      else if (key.equals("night")) half = DayPart.NIGHT;

      // map of weather strings to descriptions ("fog" -> ...)
      Map<String, String> weatherMap = todMapping.getValue();

      for (Map.Entry<String, String> wMapping : weatherMap.entrySet()) {
        String weatherKey = wMapping.getKey();
        String description = wMapping.getValue();

        Weather w = Weather.fromString(weatherKey);

        Pair<DayPart, Weather> p = new Pair<DayPart, Weather>(half, w);

        details.put(p, description);
      }
    }

    return details;
  }
 /* マップを表示するためのメソッド  『HELP』*/
 private void printMap(Map map) throws IOException {
   for (Iterator i = map.entrySet().iterator(); i.hasNext(); ) {
     Map.Entry entry = (Map.Entry) i.next();
     Object key = entry.getKey();
     Object value = entry.getValue();
     this.send(key + " … " + value);
   }
 }
  public static List<NameValuePair> convertAttributesToNameValuePair(
      Map<String, String> aAttributes) {
    List<NameValuePair> myNameValuePairs = Lists.newArrayList();

    for (Map.Entry<String, String> myEntry : aAttributes.entrySet()) {
      myNameValuePairs.add(new BasicNameValuePair(myEntry.getKey(), myEntry.getValue()));
    }
    return myNameValuePairs;
  }
 /**
  * OPTION requests are treated as CORS preflight requests
  *
  * @param req the original request
  * @param resp the response the answer are written to
  */
 @Override
 protected void doOptions(HttpServletRequest req, HttpServletResponse resp)
     throws ServletException, IOException {
   Map<String, String> responseHeaders =
       requestHandler.handleCorsPreflightRequest(
           req.getHeader("Origin"), req.getHeader("Access-Control-Request-Headers"));
   for (Map.Entry<String, String> entry : responseHeaders.entrySet()) {
     resp.setHeader(entry.getKey(), entry.getValue());
   }
 }
 protected void initAuFeatureMap() {
   if (definitionMap.containsKey(DefinableArchivalUnit.KEY_AU_FEATURE_URL_MAP)) {
     Map<String, ?> featMap = definitionMap.getMap(DefinableArchivalUnit.KEY_AU_FEATURE_URL_MAP);
     for (Map.Entry ent : featMap.entrySet()) {
       Object val = ent.getValue();
       if (val instanceof Map) {
         ent.setValue(MapUtil.expandAlternativeKeyLists((Map) val));
       }
     }
   }
 }
  /**
   * Parses HTTP parameters in an appropriate format and return back map of values to predefined
   * list of names.
   *
   * @param req Request.
   * @return Map of parsed parameters.
   */
  @SuppressWarnings({"unchecked"})
  private Map<String, Object> parameters(ServletRequest req) {
    Map<String, String[]> params = req.getParameterMap();

    if (F.isEmpty(params)) return Collections.emptyMap();

    Map<String, Object> map = U.newHashMap(params.size());

    for (Map.Entry<String, String[]> entry : params.entrySet())
      map.put(entry.getKey(), parameter(entry.getValue()));

    return map;
  }
Exemple #12
0
  /**
   * Decodes a response recursively from MessagePackObject to a normal Java object
   *
   * @param src MessagePack response
   * @return decoded object
   */
  private static Object unMsg(Object src) {
    Object out = src;
    if (src instanceof ArrayType) {
      List l = ((ArrayType) src).asList();
      List outList = new ArrayList(l.size());
      out = outList;
      for (Object o : l) outList.add(unMsg(o));
    } else if (src instanceof BooleanType) {
      out = ((BooleanType) src).asBoolean();
    } else if (src instanceof FloatType) {
      out = ((FloatType) src).asFloat();
    } else if (src instanceof IntegerType) {
      try {
        out = ((IntegerType) src).asInt();
      } catch (Exception ex) {
        /* this is a bandaid until I have a chance to further examine what's happening */
        out = ((IntegerType) src).asLong();
      }
    } else if (src instanceof MapType) {
      Set ents = ((MapType) src).asMap().entrySet();
      out = new HashMap();
      for (Object ento : ents) {
        Map.Entry ent = (Map.Entry) ento;
        Object key = unMsg(ent.getKey());
        Object val = ent.getValue();
        // Hack - keep bytes of generated or encoded payload
        if (ents.size() == 1
            && val instanceof RawType
            && (key.equals("payload") || key.equals("encoded")))
          val = ((RawType) val).asByteArray();
        else val = unMsg(val);
        ((Map) out).put(key + "", val);
      }

      if (((Map) out).containsKey("error") && ((Map) out).containsKey("error_class")) {
        armitage.ArmitageMain.print_error(
            "Metasploit Framework Exception: "
                + ((Map) out).get("error_message").toString()
                + "\n"
                + ((Map) out).get("error_backtrace"));
        throw new RuntimeException(((Map) out).get("error_message").toString());
      }
    } else if (src instanceof NilType) {
      out = null;
    } else if (src instanceof RawType) {
      out = ((RawType) src).asString();
    }
    return out;
  }
Exemple #13
0
 protected Properties filterResponseProps(Properties props) {
   Properties res = new Properties();
   for (Map.Entry ent : props.entrySet()) {
     String key = (String) ent.getKey();
     if (StringUtil.startsWithIgnoreCase(key, "x-lockss")
         || StringUtil.startsWithIgnoreCase(key, "x_lockss")
         || key.equalsIgnoreCase("org.lockss.version.number")) {
       continue;
     }
     // We've lost the original case - capitalize them the way most people
     // expect
     res.put(StringUtil.titleCase(key, '-'), (String) ent.getValue());
   }
   return res;
 }
 static void mergeOptionalConfigs(Map<PluginId, IdeaPluginDescriptorImpl> descriptors) {
   final Map<PluginId, IdeaPluginDescriptorImpl> descriptorsWithModules =
       new HashMap<PluginId, IdeaPluginDescriptorImpl>(descriptors);
   addModulesAsDependents(descriptorsWithModules);
   for (IdeaPluginDescriptorImpl descriptor : descriptors.values()) {
     final Map<PluginId, IdeaPluginDescriptorImpl> optionalDescriptors =
         descriptor.getOptionalDescriptors();
     if (optionalDescriptors != null && !optionalDescriptors.isEmpty()) {
       for (Map.Entry<PluginId, IdeaPluginDescriptorImpl> entry : optionalDescriptors.entrySet()) {
         if (descriptorsWithModules.containsKey(entry.getKey())) {
           descriptor.mergeOptionalConfig(entry.getValue());
         }
       }
     }
   }
 }
Exemple #15
0
 String dumpMessages(HashMap map) {
   StringBuffer sb = new StringBuffer();
   Map.Entry entry;
   List l;
   if (map != null) {
     synchronized (map) {
       for (Iterator it = map.entrySet().iterator(); it.hasNext(); ) {
         entry = (Map.Entry) it.next();
         l = (List) entry.getValue();
         sb.append(entry.getKey()).append(": ");
         sb.append(l.size()).append(" msgs\n");
       }
     }
   }
   return sb.toString();
 }
  /**
   * sendAll: send all of the information to the print writer
   *
   * @return: the response
   */
  protected String sendAll() throws Exception {

    assert _out != null;
    String output = _server.getID() + " " + _server.getPrio() + " " + _server.getMaxClientNum();
    Map<String, ClientNode> mp = _server.getClients();
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
      Map.Entry pair = (Map.Entry) it.next();
      String name = (String) pair.getKey();
      ClientNode node = (ClientNode) pair.getValue();
      output += " " + name + " " + node.getPassword();
    }
    output = ProtocolConstants.PACK_STR_ID_HEAD + " " + output;
    String reply = NetComm.sendAndRecv(output, _out, _in);
    return reply;
  }
Exemple #17
0
    void bundleAndSend() {
      Map.Entry entry;
      IpAddress dest;
      ObjectOutputStream out;
      InetAddress addr;
      int port;
      byte[] data;
      List l;

      if (Trace.trace) {
        Trace.info(
            "UDP.BundlingOutgoingPacketHandler.bundleAndSend()",
            "\nsending msgs:\n" + dumpMessages(msgs));
      }
      synchronized (msgs) {
        stopTimer();

        if (msgs.size() == 0) {
          return;
        }

        for (Iterator it = msgs.entrySet().iterator(); it.hasNext(); ) {
          entry = (Map.Entry) it.next();
          dest = (IpAddress) entry.getKey();
          addr = dest.getIpAddress();
          port = dest.getPort();
          l = (List) entry.getValue();
          try {
            out_stream.reset();
            // BufferedOutputStream bos=new BufferedOutputStream(out_stream);
            out_stream.write(Version.version_id, 0, Version.version_id.length); // write the version
            // bos.write(Version.version_id, 0, Version.version_id.length); // write the version
            out = new ObjectOutputStream(out_stream);
            // out=new ObjectOutputStream(bos);
            l.writeExternal(out);
            out.close(); // needed if out buffers its output to out_stream
            data = out_stream.toByteArray();
            doSend(data, addr, port);
          } catch (IOException e) {
            Trace.error(
                "UDP.BundlingOutgoingPacketHandle.bundleAndSend()",
                "exception sending msg (to dest=" + dest + "): " + e);
          }
        }
        msgs.clear();
      }
    }
  private void updateLocationLoaders() {
    if (NavigineApp.Navigation == null) return;

    long timeNow = DateTimeUtils.currentTimeMillis();
    mUpdateLocationLoadersTime = timeNow;

    synchronized (mLoaderMap) {
      Iterator<Map.Entry<String, LoaderState>> iter = mLoaderMap.entrySet().iterator();
      while (iter.hasNext()) {
        Map.Entry<String, LoaderState> entry = iter.next();

        LoaderState loader = entry.getValue();
        if (loader.state < 100) {
          loader.timeLabel = timeNow;
          if (loader.type == DOWNLOAD) loader.state = LocationLoader.checkLocationLoader(loader.id);
          if (loader.type == UPLOAD) loader.state = LocationLoader.checkLocationUploader(loader.id);
        } else if (loader.state == 100) {
          String archivePath = NavigineApp.Navigation.getArchivePath();
          String locationFile =
              LocationLoader.getLocationFile(NavigineApp.AppContext, loader.location);
          if (archivePath != null && archivePath.equals(locationFile)) {
            Log.d(TAG, "Reloading archive " + archivePath);
            if (NavigineApp.Navigation.loadArchive(archivePath)) {
              SharedPreferences.Editor editor = NavigineApp.Settings.edit();
              editor.putString("map_file", archivePath);
              editor.commit();
            }
          }
          if (loader.type == DOWNLOAD) LocationLoader.stopLocationLoader(loader.id);
          if (loader.type == UPLOAD) LocationLoader.stopLocationUploader(loader.id);
          iter.remove();
        } else {
          // Load failed
          if (Math.abs(timeNow - loader.timeLabel) > 5000) {
            if (loader.type == DOWNLOAD) LocationLoader.stopLocationLoader(loader.id);
            if (loader.type == UPLOAD) LocationLoader.stopLocationUploader(loader.id);
            iter.remove();
          }
        }
      }
    }
    updateLocalVersions();
    mAdapter.updateList();
  }
  private JSONObject setFieldAttributes(String clazz, CompactFieldNode field) throws JSONException {
    JSONObject port = new JSONObject();
    port.put("name", field.getName());

    TypeGraphVertex tgv = typeGraph.getTypeGraphVertex(clazz);
    putFieldDescription(field, port, tgv);

    List<CompactAnnotationNode> annotations = field.getVisibleAnnotations();
    CompactAnnotationNode firstAnnotation;
    if (annotations != null
        && !annotations.isEmpty()
        && (firstAnnotation = field.getVisibleAnnotations().get(0)) != null) {
      for (Map.Entry<String, Object> entry : firstAnnotation.getAnnotations().entrySet()) {
        port.put(entry.getKey(), entry.getValue());
      }
    }

    return port;
  }
 /** If in testing mode FOO, copy values from FOO_override map, if any, to main map */
 void processOverrides(TypedEntryMap map) {
   String testMode = getTestingMode();
   if (StringUtil.isNullString(testMode)) {
     return;
   }
   Object o = map.getMapElement(testMode + DefinableArchivalUnit.SUFFIX_OVERRIDE);
   if (o == null) {
     return;
   }
   if (o instanceof Map) {
     Map overrideMap = (Map) o;
     for (Map.Entry entry : (Set<Map.Entry>) overrideMap.entrySet()) {
       String key = (String) entry.getKey();
       Object val = entry.getValue();
       log.debug(getDefaultPluginName() + ": Overriding " + key + " with " + val);
       map.setMapElement(key, val);
     }
   }
 }
 protected void initFeatureVersions() throws PluginException.InvalidDefinition {
   if (definitionMap.containsKey(KEY_PLUGIN_FEATURE_VERSION_MAP)) {
     Map<Plugin.Feature, String> map = new HashMap<Plugin.Feature, String>();
     Map<String, String> spec =
         (Map<String, String>) definitionMap.getMap(KEY_PLUGIN_FEATURE_VERSION_MAP);
     log.debug2("features: " + spec);
     for (Map.Entry<String, String> ent : spec.entrySet()) {
       try {
         // Prefix version string with feature name to create separate
         // namespace for each feature
         String key = ent.getKey();
         map.put(Plugin.Feature.valueOf(key), key + "_" + ent.getValue());
       } catch (RuntimeException e) {
         log.warning(
             getPluginName()
                 + " set unknown feature: "
                 + ent.getKey()
                 + " to version "
                 + ent.getValue(),
             e);
         throw new PluginException.InvalidDefinition("Unknown feature: " + ent.getKey(), e);
       }
     }
     featureVersion = map;
   } else {
     featureVersion = null;
   }
 }
Exemple #22
0
  public UrlNode(String location) {
    parser = new JSONParser();
    try {
      try {
        URLConnection conn = new URL(location).openConnection();
        InputStream response = conn.getInputStream();

        // STUPID hack to convert an InputStream to a String in one line:
        InputStream input = conn.getInputStream();
        try {
          this.content = new java.util.Scanner(input).useDelimiter("\\A").next();
          ContainerFactory containerFactory =
              new ContainerFactory() {
                public List creatArrayContainer() {
                  return new LinkedList();
                }

                public Map createObjectContainer() {
                  return new LinkedHashMap();
                }
              };

          try {
            Map json = (Map) parser.parse(content, containerFactory);
            Iterator iter = json.entrySet().iterator();
            data = new HashMap<String, String>();
            while (iter.hasNext()) {
              Map.Entry entry = (Map.Entry) iter.next();
              data.put(entry.getKey().toString(), entry.getValue().toString());
            }
          } catch (ParseException pe) {
          }
        } catch (java.util.NoSuchElementException e) {
          this.content = "{\"Error\": \"NO CONTENT\"}";
        }
      } catch (MalformedURLException e) {
      }
    } catch (IOException e) {
    }
  }
Exemple #23
0
  /**
   * 发起查询处理结果请求
   *
   * @param params 请求参数
   * @return 请求结果
   * @throws IOException
   */
  public Result getResult(Map<String, Object> params) throws IOException {
    InputStream is = null;
    HttpURLConnection conn;

    StringBuilder sb = new StringBuilder(HOST + "result");
    sb.append("?");
    for (Map.Entry<String, Object> mapping : params.entrySet()) {
      sb.append(mapping.getKey() + "=" + mapping.getValue().toString() + "&");
    }
    URL url = new URL(sb.toString().substring(0, sb.length() - 1));

    conn = (HttpURLConnection) url.openConnection();

    // 设置必要参数
    conn.setConnectTimeout(timeout);
    conn.setRequestMethod("GET");
    conn.setUseCaches(false);
    conn.setDoOutput(true);
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.setRequestProperty("User-Agent", UpYunUtils.VERSION);

    // 设置时间
    conn.setRequestProperty(DATE, getGMTDate());
    // 设置签名
    conn.setRequestProperty(AUTHORIZATION, sign(params));

    // 创建链接
    conn.connect();

    // 获取返回的信息
    Result result = getResp(conn);

    if (is != null) {
      is.close();
    }
    if (conn != null) {
      conn.disconnect();
    }
    return result;
  }
Exemple #24
0
  /**
   * Makes a POST request and returns the server response.
   *
   * @param urlString the URL to post to
   * @param nameValuePairs a map of name/value pairs to supply in the request.
   * @return the server reply (either from the input stream or the error stream)
   */
  public static String doPost(String urlString, Map<String, String> nameValuePairs)
      throws IOException {
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);

    PrintWriter out = new PrintWriter(connection.getOutputStream());

    boolean first = true;
    for (Map.Entry<String, String> pair : nameValuePairs.entrySet()) {
      if (first) first = false;
      else out.print('&');
      String name = pair.getKey();
      String value = pair.getValue();
      out.print(name);
      out.print('=');
      out.print(URLEncoder.encode(value, "UTF-8"));
    }

    out.close();

    Scanner in;
    StringBuilder response = new StringBuilder();
    try {
      in = new Scanner(connection.getInputStream());
    } catch (IOException e) {
      if (!(connection instanceof HttpURLConnection)) throw e;
      InputStream err = ((HttpURLConnection) connection).getErrorStream();
      if (err == null) throw e;
      in = new Scanner(err);
    }

    while (in.hasNextLine()) {
      response.append(in.nextLine());
      response.append("\n");
    }

    in.close();
    return response.toString();
  }
  private void addTagsToProperties(MethodInfo mi, JSONObject propJ) throws JSONException {
    // create description object. description tag enables the visual tools to display description of
    // keys/values
    // of a map property, items of a list, properties within a complex type.
    JSONObject descriptionObj = new JSONObject();
    if (mi.comment != null) {
      descriptionObj.put("$", mi.comment);
    }
    for (Map.Entry<String, String> descEntry : mi.descriptions.entrySet()) {
      descriptionObj.put(descEntry.getKey(), descEntry.getValue());
    }
    if (descriptionObj.length() > 0) {
      propJ.put("descriptions", descriptionObj);
    }

    // create useSchema object. useSchema tag is added to enable visual tools to be able to render a
    // text field
    // as a dropdown with choices populated from the schema attached to the port.
    JSONObject useSchemaObj = new JSONObject();
    for (Map.Entry<String, String> useSchemaEntry : mi.useSchemas.entrySet()) {
      useSchemaObj.put(useSchemaEntry.getKey(), useSchemaEntry.getValue());
    }
    if (useSchemaObj.length() > 0) {
      propJ.put("useSchema", useSchemaObj);
    }
  }
 private ExternalizableMap loadMap(String extMapName, ClassLoader loader)
     throws FileNotFoundException {
   String first = null;
   String next = extMapName;
   List<String> urls = new ArrayList<String>();
   ExternalizableMap res = null;
   while (next != null) {
     // convert the plugin class name to an xml file name
     String mapFile = next.replace('.', '/') + MAP_SUFFIX;
     URL url = loader.getResource(mapFile);
     if (url != null && urls.contains(url.toString())) {
       throw new PluginException.InvalidDefinition("Plugin inheritance loop: " + next);
     }
     // load into map
     ExternalizableMap oneMap = new ExternalizableMap();
     oneMap.loadMapFromResource(mapFile, loader);
     urls.add(url.toString());
     // apply overrides one plugin at a time in inheritance chain
     processOverrides(oneMap);
     if (res == null) {
       res = oneMap;
     } else {
       for (Map.Entry ent : oneMap.entrySet()) {
         String key = (String) ent.getKey();
         Object val = ent.getValue();
         if (!res.containsKey(key)) {
           res.setMapElement(key, val);
         }
       }
     }
     if (oneMap.containsKey(KEY_PLUGIN_PARENT)) {
       next = oneMap.getString(KEY_PLUGIN_PARENT);
     } else {
       next = null;
     }
   }
   loadedFromUrls = urls;
   return res;
 }
  public static String doPost(String urlString, Map<Object, Object> nameValuePairs)
      throws IOException {
    URL url = new URL(urlString);
    URLConnection connection = url.openConnection();
    connection.setDoOutput(true);
    String encoding = connection.getContentEncoding();
    if (encoding == null) encoding = "ISO-8859-1";

    try (PrintWriter out = new PrintWriter(connection.getOutputStream())) {
      boolean first = true;
      for (Map.Entry<Object, Object> pair : nameValuePairs.entrySet()) {
        if (first) first = false;
        else out.print('&');
        String name = pair.getKey().toString();
        String value = pair.getValue().toString();
        out.print(name);
        out.print('=');
        out.print(URLEncoder.encode(value, encoding));
      }
    }

    StringBuilder response = new StringBuilder();
    try (Scanner in = new Scanner(connection.getInputStream(), encoding)) {
      while (in.hasNextLine()) {
        response.append(in.nextLine());
        response.append("\n");
      }
    } catch (IOException e) {
      if (!(connection instanceof HttpURLConnection)) throw e;
      InputStream err = ((HttpURLConnection) connection).getErrorStream();
      if (err == null) throw e;
      Scanner in = new Scanner(err);
      response.append(in.nextLine());
      response.append("\n");
    }

    return response.toString();
  }
Exemple #28
0
  private URL buildPingUrl() throws URISyntaxException, IOException, NoSuchAlgorithmException {

    URI uri = new URI(this.pingUrl);

    Map<String, String> queryMap = new HashMap<>();
    queryMap.put("cluster_id", getClusterId()); // block until clusterId is available
    queryMap.put("kernel", XContentFactory.jsonBuilder().map(getKernelData()).string());
    queryMap.put("master", isMasterNode().toString());
    queryMap.put("ping_count", XContentFactory.jsonBuilder().map(getCounters()).string());
    queryMap.put("hardware_address", getHardwareAddress());
    queryMap.put("crate_version", getCrateVersion());
    queryMap.put("java_version", getJavaVersion());

    if (logger.isDebugEnabled()) {
      logger.debug("Sending data: {}", queryMap);
    }

    final Joiner joiner = Joiner.on('=');
    List<String> params = new ArrayList<>(queryMap.size());
    for (Map.Entry<String, String> entry : queryMap.entrySet()) {
      if (entry.getValue() != null) {
        params.add(joiner.join(entry.getKey(), entry.getValue()));
      }
    }
    String query = Joiner.on('&').join(params);

    return new URI(
            uri.getScheme(),
            uri.getUserInfo(),
            uri.getHost(),
            uri.getPort(),
            uri.getPath(),
            query,
            uri.getFragment())
        .toURL();
  }
  // Used for debugging in main.
  private static void printDataMap(Map map) throws Exception {
    TreeMap res = new TreeMap(map);
    Iterator key_itr = map.keySet().iterator();
    while (key_itr.hasNext()) {
      Object key = key_itr.next();
      Object val = map.get(key);
      if (val instanceof byte[]) {
        String as_bytes = ByteFormatter.nicePrint((byte[]) val);
        String as_text = new String((byte[]) val, Constants.BYTE_ENCODING);
        res.put(key, as_text + " [" + as_bytes + "]");
      }
    }

    Iterator entries = res.entrySet().iterator();
    Map.Entry entry;
    while (entries.hasNext()) {
      entry = (Map.Entry) entries.next();
      System.out.print("  ");
      System.out.print(entry.getKey());
      System.out.print(": ");
      System.out.print(entry.getValue());
      System.out.println();
    }
  }
  private T requestInfo(URI baseUrl, RenderingContext context)
      throws IOException, URISyntaxException, ParserConfigurationException, SAXException {
    URL url = loader.createURL(baseUrl, context);

    GetMethod method = null;
    try {
      final InputStream stream;

      if ((url.getProtocol().equals("http") || url.getProtocol().equals("https"))
          && context.getConfig().localHostForwardIsFrom(url.getHost())) {
        String scheme = url.getProtocol();
        final String host = url.getHost();
        if (url.getProtocol().equals("https")
            && context.getConfig().localHostForwardIsHttps2http()) {
          scheme = "http";
        }
        URL localUrl = new URL(scheme, "localhost", url.getPort(), url.getFile());
        HttpURLConnection connexion = (HttpURLConnection) localUrl.openConnection();
        connexion.setRequestProperty("Host", host);
        for (Map.Entry<String, String> entry : context.getHeaders().entrySet()) {
          connexion.setRequestProperty(entry.getKey(), entry.getValue());
        }
        stream = connexion.getInputStream();
      } else {
        method = new GetMethod(url.toString());
        for (Map.Entry<String, String> entry : context.getHeaders().entrySet()) {
          method.setRequestHeader(entry.getKey(), entry.getValue());
        }
        context.getConfig().getHttpClient(baseUrl).executeMethod(method);
        int code = method.getStatusCode();
        if (code < 200 || code >= 300) {
          throw new IOException(
              "Error "
                  + code
                  + " while reading the Capabilities from "
                  + url
                  + ": "
                  + method.getStatusText());
        }
        stream = method.getResponseBodyAsStream();
      }
      final T result;
      try {
        result = loader.parseInfo(stream);
      } finally {
        stream.close();
      }
      return result;
    } finally {
      if (method != null) {
        method.releaseConnection();
      }
    }
  }