コード例 #1
0
  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);
    }
  }
コード例 #2
0
 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;
   }
 }
コード例 #3
0
  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();
      }
    }
  }
コード例 #4
0
ファイル: UrlNode.java プロジェクト: g105b/CloudScript
  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);
  }
コード例 #5
0
  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);
    }
  }
コード例 #6
0
  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);
    }
  }
コード例 #7
0
ファイル: SaveURL.java プロジェクト: tchipwanya/cs458-f12
 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.");
 }
コード例 #8
0
ファイル: DungeonServer.java プロジェクト: abreen/Dungeon
  @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;
  }
コード例 #9
0
 /* マップを表示するためのメソッド  『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);
   }
 }
コード例 #10
0
  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;
  }
コード例 #11
0
 /**
  * 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());
   }
 }
コード例 #12
0
  /**
   * Sets configuration properties from the map.
   *
   * @param endpointCfg Map of properties.
   * @throws IgniteCheckedException If invalid property name or value.
   */
  public void setupConfiguration(Map<String, String> endpointCfg) throws IgniteCheckedException {
    for (Map.Entry<String, String> e : endpointCfg.entrySet()) {
      try {
        switch (e.getKey()) {
          case "type":
          case "host":
          case "management":
            // Ignore these properties
            break;

          case "port":
            setPort(Integer.parseInt(e.getValue()));
            break;

          case "size":
            setSize(Integer.parseInt(e.getValue()));
            break;

          case "tokenDirectoryPath":
            setTokenDirectoryPath(e.getValue());
            break;

          default:
            throw new IgniteCheckedException(
                "Invalid property '" + e.getKey() + "' of " + getClass().getSimpleName());
        }
      } catch (Throwable t) {
        if (t instanceof IgniteCheckedException || t instanceof Error) throw t;

        throw new IgniteCheckedException(
            "Invalid value '"
                + e.getValue()
                + "' of the property '"
                + e.getKey()
                + "' in "
                + getClass().getSimpleName(),
            t);
      }
    }
  }
コード例 #13
0
  /**
   * 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;
  }
コード例 #14
0
ファイル: MsgRpcImpl.java プロジェクト: rindong/armitage
  /**
   * 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;
  }
コード例 #15
0
ファイル: Exporter.java プロジェクト: edina/lockss-daemon
 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;
 }
コード例 #16
0
 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());
         }
       }
     }
   }
 }
コード例 #17
0
  /**
   * 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;
  }
コード例 #18
0
ファイル: UDP.java プロジェクト: NZDIS/jgroups
 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();
 }
コード例 #19
0
ファイル: UDP.java プロジェクト: NZDIS/jgroups
    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();
      }
    }
コード例 #20
0
 /** 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);
     }
   }
 }
コード例 #21
0
  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;
  }
コード例 #22
0
ファイル: PostTest.java プロジェクト: pkupzj/research
  /**
   * 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();
  }
コード例 #23
0
ファイル: MediaHandler.java プロジェクト: upyun/java-sdk
  /**
   * 发起查询处理结果请求
   *
   * @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;
  }
コード例 #24
0
ファイル: UrlNode.java プロジェクト: g105b/CloudScript
  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) {
    }
  }
コード例 #25
0
 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;
 }
コード例 #26
0
  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();
  }
コード例 #27
0
  // 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();
    }
  }
コード例 #28
0
ファイル: PingTask.java プロジェクト: huangweili/crate
  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();
  }
コード例 #29
0
  @SuppressWarnings({"HardCodedStringLiteral"})
  @Nullable
  public static IdeaPluginDescriptorImpl loadDescriptor(
      final File file, @NonNls final String fileName) {
    IdeaPluginDescriptorImpl descriptor = null;

    if (file.isDirectory()) {
      descriptor = loadDescriptorFromDir(file, fileName);

      if (descriptor == null) {
        File libDir = new File(file, "lib");
        if (!libDir.isDirectory()) {
          return null;
        }
        final File[] files = libDir.listFiles();
        if (files == null || files.length == 0) {
          return null;
        }
        Arrays.sort(
            files,
            new Comparator<File>() {
              @Override
              public int compare(File o1, File o2) {
                if (o2.getName().startsWith(file.getName())) return Integer.MAX_VALUE;
                if (o1.getName().startsWith(file.getName())) return -Integer.MAX_VALUE;
                if (o2.getName().startsWith("resources")) return -Integer.MAX_VALUE;
                if (o1.getName().startsWith("resources")) return Integer.MAX_VALUE;
                return 0;
              }
            });
        for (final File f : files) {
          if (FileUtil.isJarOrZip(f)) {
            descriptor = loadDescriptorFromJar(f, fileName);
            if (descriptor != null) {
              descriptor.setPath(file);
              break;
            }
            //           getLogger().warn("Cannot load descriptor from " + f.getName() + "");
          } else if (f.isDirectory()) {
            IdeaPluginDescriptorImpl descriptor1 = loadDescriptorFromDir(f, fileName);
            if (descriptor1 != null) {
              if (descriptor != null) {
                getLogger()
                    .info("Cannot load " + file + " because two or more plugin.xml's detected");
                return null;
              }
              descriptor = descriptor1;
              descriptor.setPath(file);
            }
          }
        }
      }
    } else if (StringUtil.endsWithIgnoreCase(file.getName(), ".jar") && file.exists()) {
      descriptor = loadDescriptorFromJar(file, fileName);
    }

    if (descriptor != null && !descriptor.getOptionalConfigs().isEmpty()) {
      final Map<PluginId, IdeaPluginDescriptorImpl> descriptors =
          new HashMap<PluginId, IdeaPluginDescriptorImpl>(descriptor.getOptionalConfigs().size());
      for (Map.Entry<PluginId, String> entry : descriptor.getOptionalConfigs().entrySet()) {
        String optionalDescriptorName = entry.getValue();
        assert !Comparing.equal(fileName, optionalDescriptorName)
            : "recursive dependency: " + fileName;

        IdeaPluginDescriptorImpl optionalDescriptor = loadDescriptor(file, optionalDescriptorName);
        if (optionalDescriptor == null && !FileUtil.isJarOrZip(file)) {
          for (URL url : getClassLoaderUrls()) {
            if ("file".equals(url.getProtocol())) {
              optionalDescriptor =
                  loadDescriptor(new File(decodeUrl(url.getFile())), optionalDescriptorName);
              if (optionalDescriptor != null) {
                break;
              }
            }
          }
        }
        if (optionalDescriptor != null) {
          descriptors.put(entry.getKey(), optionalDescriptor);
        } else {
          getLogger().info("Cannot find optional descriptor " + optionalDescriptorName);
        }
      }
      descriptor.setOptionalDescriptors(descriptors);
    }
    return descriptor;
  }
コード例 #30
0
  public CommandData parseCommandData(ArtifactData artifact) throws Exception {
    File source = new File(artifact.file);
    if (!source.isFile()) throw new FileNotFoundException();

    CommandData data = new CommandData();
    data.sha = artifact.sha;
    data.jpmRepoDir = repoDir.getCanonicalPath();
    JarFile jar = new JarFile(source);
    try {
      reporter.trace("Parsing %s", source);
      Manifest m = jar.getManifest();
      Attributes main = m.getMainAttributes();
      data.name = data.bsn = main.getValue("Bundle-SymbolicName");
      String version = main.getValue("Bundle-Version");
      if (version == null) data.version = Version.LOWEST;
      else data.version = new Version(version);

      data.main = main.getValue("Main-Class");
      data.description = main.getValue("Bundle-Description");
      data.title = main.getValue("JPM-Name");

      reporter.trace("name " + data.name + " " + data.main + " " + data.title);
      DependencyCollector path = new DependencyCollector(this);
      path.add(artifact);
      DependencyCollector bundles = new DependencyCollector(this);
      if (main.getValue("JPM-Classpath") != null) {
        Parameters requires = OSGiHeader.parseHeader(main.getValue("JPM-Classpath"));

        for (Map.Entry<String, Attrs> e : requires.entrySet()) {
          path.add(e.getKey(), e.getValue().get("name")); // coordinate
        }
      } else if (!artifact.local) { // No JPM-Classpath, falling back to
        // server's revision
        // Iterable<RevisionRef> closure =
        // library.getClosure(artifact.sha,
        // false);
        // System.out.println("getting closure " + artifact.url + " " +
        // Strings.join("\n",closure));

        // if (closure != null) {
        // for (RevisionRef ref : closure) {
        // path.add(Hex.toHexString(ref.revision));
        // }
        // }
      }

      if (main.getValue("JPM-Runbundles") != null) {
        Parameters jpmrunbundles = OSGiHeader.parseHeader(main.getValue("JPM-Runbundles"));

        for (Map.Entry<String, Attrs> e : jpmrunbundles.entrySet()) {
          bundles.add(e.getKey(), e.getValue().get("name"));
        }
      }

      reporter.trace("collect digests runpath");
      data.dependencies.addAll(path.getDigests());
      reporter.trace("collect digests bundles");
      data.runbundles.addAll(bundles.getDigests());

      Parameters command = OSGiHeader.parseHeader(main.getValue("JPM-Command"));
      if (command.size() > 1) reporter.error("Only one command can be specified");

      for (Map.Entry<String, Attrs> e : command.entrySet()) {
        data.name = e.getKey();

        Attrs attrs = e.getValue();

        if (attrs.containsKey("jvmargs")) data.jvmArgs = attrs.get("jvmargs");

        if (attrs.containsKey("title")) data.title = attrs.get("title");

        if (data.title != null) data.title = data.name;
      }
      return data;
    } finally {
      jar.close();
    }
  }