コード例 #1
0
ファイル: SmtpTransport.java プロジェクト: nulops/k-9
  /**
   * Decodes a SmtpTransport URI.
   *
   * <p>Possible forms:
   *
   * <pre>
   * smtp://user:password@server:port CONNECTION_SECURITY_NONE
   * smtp+tls://user:password@server:port CONNECTION_SECURITY_TLS_OPTIONAL
   * smtp+tls+://user:password@server:port CONNECTION_SECURITY_TLS_REQUIRED
   * smtp+ssl+://user:password@server:port CONNECTION_SECURITY_SSL_REQUIRED
   * smtp+ssl://user:password@server:port CONNECTION_SECURITY_SSL_OPTIONAL
   * </pre>
   */
  public static ServerSettings decodeUri(String uri) {
    String host;
    int port;
    ConnectionSecurity connectionSecurity;
    String authenticationType = AUTH_AUTOMATIC;
    String username = null;
    String password = null;

    URI smtpUri;
    try {
      smtpUri = new URI(uri);
    } catch (URISyntaxException use) {
      throw new IllegalArgumentException("Invalid SmtpTransport URI", use);
    }

    String scheme = smtpUri.getScheme();
    if (scheme.equals("smtp")) {
      connectionSecurity = ConnectionSecurity.NONE;
      port = 25;
    } else if (scheme.equals("smtp+tls")) {
      connectionSecurity = ConnectionSecurity.STARTTLS_OPTIONAL;
      port = 25;
    } else if (scheme.equals("smtp+tls+")) {
      connectionSecurity = ConnectionSecurity.STARTTLS_REQUIRED;
      port = 25;
    } else if (scheme.equals("smtp+ssl+")) {
      connectionSecurity = ConnectionSecurity.SSL_TLS_REQUIRED;
      port = 465;
    } else if (scheme.equals("smtp+ssl")) {
      connectionSecurity = ConnectionSecurity.SSL_TLS_OPTIONAL;
      port = 465;
    } else {
      throw new IllegalArgumentException("Unsupported protocol (" + scheme + ")");
    }

    host = smtpUri.getHost();

    if (smtpUri.getPort() != -1) {
      port = smtpUri.getPort();
    }

    if (smtpUri.getUserInfo() != null) {
      try {
        String[] userInfoParts = smtpUri.getUserInfo().split(":");
        username = URLDecoder.decode(userInfoParts[0], "UTF-8");
        if (userInfoParts.length > 1) {
          password = URLDecoder.decode(userInfoParts[1], "UTF-8");
        }
        if (userInfoParts.length > 2) {
          authenticationType = userInfoParts[2];
        }
      } catch (UnsupportedEncodingException enc) {
        // This shouldn't happen since the encoding is hardcoded to UTF-8
        throw new IllegalArgumentException("Couldn't urldecode username or password.", enc);
      }
    }

    return new ServerSettings(
        TRANSPORT_TYPE, host, port, connectionSecurity, authenticationType, username, password);
  }
コード例 #2
0
  public static String sanitizeUri(String uri) {
    // Decode the path.
    try {
      uri = URLDecoder.decode(uri, "UTF-8");
    } catch (UnsupportedEncodingException e) {
      try {
        uri = URLDecoder.decode(uri, "ISO-8859-1");
      } catch (UnsupportedEncodingException e1) {
        throw new Error();
      }
    }

    // Convert file separators.
    uri = uri.replace('/', File.separatorChar);

    // Simplistic dumb security check.
    // You will have to do something serious in the production environment.
    if (uri.contains(File.separator + ".")
        || uri.contains("." + File.separator)
        || uri.startsWith(".")
        || uri.endsWith(".")) {
      return null;
    }

    // Convert to absolute path.
    return uri;
  }
コード例 #3
0
  /**
   * @param queryString a query string of the form n1=v1&n2=v2&... to decode. May be null.
   * @param acceptAmp -> "&amp;" if true, "&" if false
   * @return a Map of String[] indexed by name, an empty Map if the query string was null
   */
  public static Map<String, String[]> decodeQueryString(
      final CharSequence queryString, final boolean acceptAmp) {

    final Map<String, String[]> result = new TreeMap<String, String[]>();
    if (queryString != null) {
      final Matcher matcher =
          acceptAmp ? PATTERN_AMP.matcher(queryString) : PATTERN_NO_AMP.matcher(queryString);
      int matcherEnd = 0;
      while (matcher.find()) {
        matcherEnd = matcher.end();
        try {
          // Group 0 is the whole match, e.g. a=b, while group 1 is the first group
          // denoted ( with parens ) in the expression.  Hence we start with group 1.
          final String name =
              URLDecoder.decode(matcher.group(1), NetUtils.STANDARD_PARAMETER_ENCODING);
          final String value =
              URLDecoder.decode(matcher.group(2), NetUtils.STANDARD_PARAMETER_ENCODING);

          StringUtils.addValueToStringArrayMap(result, name, value);
        } catch (UnsupportedEncodingException e) {
          // Should not happen as we are using a required encoding
          throw new OXFException(e);
        }
      }
      if (queryString.length() != matcherEnd) {
        // There was garbage at the end of the query.
        throw new OXFException("Malformed URL: " + queryString);
      }
    }
    return result;
  }
コード例 #4
0
  protected String sanitizeUri(String uri) {
    try {
      uri = URLDecoder.decode(uri, "UTF-8");
    } catch (UnsupportedEncodingException e) {
      try {
        uri = URLDecoder.decode(uri, "ISO-8859-1");
      } catch (UnsupportedEncodingException e1) {
        throw new Error();
      }
    }

    uri = uri.replace('/', File.separatorChar);

    if (uri.contains(File.separator + ".")
        || uri.contains("." + File.separator)
        || uri.startsWith(".")
        || uri.endsWith(".")) {
      return null;
    }

    int pos = uri.indexOf("?");
    if (pos != -1) {
      uri = uri.substring(0, pos);
    }
    return uri;
  }
コード例 #5
0
ファイル: BatchCitationServlet.java プロジェクト: yllyx/sakai
  public static Map<String, String[]> getUrlParameters(String url)
      throws UnsupportedEncodingException {
    Map<String, List<String>> params = new HashMap<String, List<String>>();
    if (url != null) {
      for (String param : url.split("&")) {
        String pair[] = param.split("=");
        String key = URLDecoder.decode(pair[0], "UTF-8");
        String value = "";
        if (pair.length > 1) {
          value = URLDecoder.decode(pair[1], "UTF-8");
        }
        List<String> values = params.get(key);
        if (values == null) {
          values = new ArrayList<String>();
          params.put(key, values);
        }
        values.add(value);
      }
    }

    Map<String, String[]> ret = new HashMap<String, String[]>();
    for (String k : params.keySet()) {
      ret.put(k, (String[]) params.get(k).toArray(new String[] {}));
    }
    return ret;
  }
コード例 #6
0
  public void loadKeyValuesFromUrl(String url, int start) {
    String[] urlParts = url.split("[\\?\\&]");
    for (int i = start; i < urlParts.length; i++) {
      String part = urlParts[i];
      String[] kv = part.split("=", 2);
      if (kv.length == 2) {
        String key = kv[0];
        String value = kv[1];
        try {
          key = URLDecoder.decode(key, "UTF-8");
        } catch (UnsupportedEncodingException e) {
        }
        try {
          value = URLDecoder.decode(value, "UTF-8");
        } catch (UnsupportedEncodingException e) {
        }

        Log.d(TAG, "Returned " + key + " = " + value);
        put(key, value);
      } else if (kv.length == 1) {
        String key = kv[0];
        try {
          key = URLDecoder.decode(key, "UTF-8");
        } catch (UnsupportedEncodingException e) {
        }
        put(key, null);
      }
    }
  }
コード例 #7
0
 private String sanitizeUri(String uri) {
   try {
     uri = URLDecoder.decode(uri, "UTF-8");
   } catch (UnsupportedEncodingException e) {
     try {
       uri = URLDecoder.decode(uri, "ISO-8859-1");
     } catch (UnsupportedEncodingException e1) {
       throw new Error();
     }
   }
   if (!uri.startsWith(url)) {
     return null;
   }
   if (!uri.startsWith("/")) {
     return null;
   }
   uri = uri.replace('/', File.separatorChar);
   if (uri.contains(File.separator + '.')
       || uri.contains('.' + File.separator)
       || uri.startsWith(".")
       || uri.endsWith(".")
       || INSECURE_URI.matcher(uri).matches()) {
     return null;
   }
   return System.getProperty("user.dir") + File.separator + uri;
 }
コード例 #8
0
ファイル: WebUtils.java プロジェクト: liuqinggang/neixunutil
  public static String getAddressByIP(String ip) {
    try {
      String js = visitWeb("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=" + ip);
      JsonParser jsonParser = new JsonParser();
      js = js.trim();
      JsonObject jo = jsonParser.parse(js.substring(21, js.length() - 1)).getAsJsonObject();
      String province = "";
      String city = "";
      try {
        // 获取 省、市
        province =
            jo.get("province") == null
                ? ""
                : URLDecoder.decode(jo.get("province").toString(), "UTF-8");
        city = jo.get("city") == null ? "" : URLDecoder.decode(jo.get("city").toString(), "UTF-8");
        // 省为空用国家代替
        if (StringUtils.isEmpty(province)) {
          province =
              jo.get("country") == null
                  ? ""
                  : URLDecoder.decode(jo.get("country").toString(), "UTF-8");
        }

      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }

      return (province.equals("") || province.equals(city)) ? city : province + " " + city;
    } catch (Exception e) {
      e.printStackTrace();
      return "";
    }
  }
コード例 #9
0
    /**
     * Parse the parameters of a connection into a CoreNLP properties file that can be passed into
     * {@link StanfordCoreNLP}, and used in the I/O stages.
     *
     * @param httpExchange The http exchange; effectively, the request information.
     * @return A {@link Properties} object corresponding to a combination of default and passed
     *     properties.
     * @throws UnsupportedEncodingException Thrown if we could not decode the key/value pairs with
     *     UTF-8.
     */
    private Properties getProperties(HttpExchange httpExchange)
        throws UnsupportedEncodingException {
      // Load the default properties
      Properties props = new Properties();
      defaultProps
          .entrySet()
          .stream()
          .forEach(
              entry -> props.setProperty(entry.getKey().toString(), entry.getValue().toString()));

      // Try to get more properties from query string.
      Map<String, String> urlParams = getURLParams(httpExchange.getRequestURI());
      if (urlParams.containsKey("properties")) {
        StringUtils.decodeMap(URLDecoder.decode(urlParams.get("properties"), "UTF-8"))
            .entrySet()
            .forEach(entry -> props.setProperty(entry.getKey(), entry.getValue()));
      } else if (urlParams.containsKey("props")) {
        StringUtils.decodeMap(URLDecoder.decode(urlParams.get("properties"), "UTF-8"))
            .entrySet()
            .forEach(entry -> props.setProperty(entry.getKey(), entry.getValue()));
      }

      // Make sure the properties compile
      props.setProperty(
          "annotators",
          StanfordCoreNLP.ensurePrerequisiteAnnotators(
              props.getProperty("annotators").split("[, \t]+")));

      return props;
    }
コード例 #10
0
 /** 跳转至新增页面 */
 @RequestMapping("toAdd")
 public ModelAndView toAdd(HttpServletRequest request) throws Exception {
   String catalogId = StringUtils.getNullBlankStr(request.getParameter("catalogId"));
   String formKey =
       URLDecoder.decode(StringUtils.getNullBlankStr(request.getParameter("formKey")), "utf-8");
   ;
   String subject =
       URLDecoder.decode(StringUtils.getNullBlankStr(request.getParameter("subject")), "utf-8");
   String formDesc =
       URLDecoder.decode(StringUtils.getNullBlankStr(request.getParameter("formDesc")), "utf-8");
   String tableId = StringUtils.getNullBlankStr(request.getParameter("tableId"));
   String tableDesc =
       URLDecoder.decode(StringUtils.getNullBlankStr(request.getParameter("tableDesc")), "utf-8");
   String mainTmplId = StringUtils.getNullBlankStr(request.getParameter("mainTmplId"));
   BpmFormDef bpmFormDef = new BpmFormDef();
   bpmFormDef.setCatalogId(catalogId);
   bpmFormDef.setFormKey(formKey);
   bpmFormDef.setSubject(subject);
   bpmFormDef.setFormDesc(formDesc);
   bpmFormDef.setTableId(tableId);
   bpmFormDef.setTableDesc(tableDesc);
   String reult = genTemplate(tableId, mainTmplId);
   bpmFormDef.setHtml(reult);
   return new ModelAndView("workflow/form/bpmFormDefEdit")
       .addObject("bpmFormDef", bpmFormDef)
       .addObject("type", "add");
 }
コード例 #11
0
  private void utf8Fixup(HttpServletRequest req, Map<String, Object[]> params) {
    if (req.getQueryString() == null) return;

    String[] paramsInQueryString = req.getQueryString().split("&");
    if (paramsInQueryString != null) {
      for (String param : paramsInQueryString) {
        String[] paramTokens = param.split("=");
        if (paramTokens != null && paramTokens.length == 2) {
          String name = param.split("=")[0];
          String value = param.split("=")[1];

          try {
            name = URLDecoder.decode(name, "UTF-8");
          } catch (UnsupportedEncodingException e) {
          }
          try {
            value = URLDecoder.decode(value, "UTF-8");
          } catch (UnsupportedEncodingException e) {
          }
          params.put(name, new String[] {value});
        } else {
          s_logger.debug("Invalid paramemter in URL found. param: " + param);
        }
      }
    }
  }
コード例 #12
0
  @RequiresPermissions({"categoryWord-get"})
  @RequestMapping(
      method = RequestMethod.GET,
      value = "/getAll",
      headers = "Accept=application/json")
  public @ResponseBody Map<String, Object> getAll(HttpServletRequest req) {
    int pageNo = Integer.parseInt(req.getParameter("page"));
    int rowCount = Integer.parseInt(req.getParameter("rows"));
    String englishWord = req.getParameter("englishWord");
    String chineseWord = req.getParameter("chineseWord");
    String esglisgAb = req.getParameter("esglisgAb");
    String remark = req.getParameter("remark");

    List<SearchCondition> searchConds = new ArrayList<SearchCondition>();
    StringBuffer hql = new StringBuffer("select c from CategoryWord c where 1=1 ");
    if (null != englishWord && !"".equals(englishWord)) {
      hql.append(" and englishWord like ?");
      searchConds.add(new SearchCondition("englishWord", "%" + englishWord + "%"));
    }
    if (null != chineseWord && !"".equals(chineseWord)) {
      hql.append(" and chineseWord like ?");
      try {
        chineseWord = URLDecoder.decode(chineseWord, "utf-8");
      } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      searchConds.add(new SearchCondition("chineseWord", "%" + chineseWord + "%"));
    }
    if (null != esglisgAb && !"".equals(esglisgAb)) {
      hql.append(" and esglisgAb like ?");
      searchConds.add(new SearchCondition("esglisgAb", "%" + esglisgAb + "%"));
    }
    if (null != remark && !"".equals(remark)) {
      hql.append(" and remark like ?");
      try {
        remark = URLDecoder.decode(remark, "utf-8");
      } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      searchConds.add(new SearchCondition("remark", "%" + remark + "%"));
    }
    hql.append(" order by esglisgAb");
    //        Page page = categoryWordService.getAll(rowCount);
    Page page = new Page();
    if (searchConds.size() <= 0) {
      page = categoryWordService.getPageBy(hql.toString(), rowCount);
    } else {
      page = categoryWordService.getPageBy(hql.toString(), rowCount, searchConds);
    }

    page.setPage(pageNo);

    List<CategoryWord> list = categoryWordService.findBy(hql.toString(), page, searchConds);
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("total", page.getResultCount());
    map.put("rows", list);
    return map;
  }
コード例 #13
0
  @RequestMapping("/getUserInfo2.do")
  public ModelAndView getUserInfo2(HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    String openid = request.getParameter("openid");
    String nickname = URLDecoder.decode(request.getParameter("nickname"), "UTF-8");
    String headimgurl = URLDecoder.decode(request.getParameter("headimgurl"), "UTF-8");
    System.out.println(
        new Date()
            + "\nopenid:"
            + openid
            + "--nickname:"
            + request.getParameter("nickname")
            + "--headimgurl:"
            + request.getParameter("headimgurl")
            + "--nickname2:"
            + nickname
            + "--headimgurl2:"
            + headimgurl);

    WxCalledRecord wxCalledRecord = wxQAManager.wxLogin(openid, nickname, headimgurl);
    wxQAManager.saveOpenid2Cache(request, response, wxCalledRecord);

    String requestPath = (String) request.getSession().getAttribute("requestPath");
    //        System.out.println("requestPath:" + requestPath);
    return new ModelAndView("redirect:" + requestPath);
  }
コード例 #14
0
  public String execute() throws Exception {
    String a_editNoticeId = ServletActionContext.getRequest().getParameter("editNoticeId");
    a_editNoticeId = URLDecoder.decode(a_editNoticeId, "utf-8");
    String a_editNoticeDetail = ServletActionContext.getRequest().getParameter("editNoticeDetail");
    a_editNoticeDetail = URLDecoder.decode(a_editNoticeDetail, "utf-8");
    String a_editNoticeReleaser =
        ServletActionContext.getRequest().getParameter("editNoticeReleaser");
    a_editNoticeReleaser = URLDecoder.decode(a_editNoticeReleaser, "utf-8");
    String a_editNoticePublishtime =
        ServletActionContext.getRequest().getParameter("editNoticePublishtime");
    a_editNoticePublishtime = URLDecoder.decode(a_editNoticePublishtime, "utf-8");

    String sql =
        "update notice set detail='"
            + a_editNoticeDetail
            + "',publishtime='"
            + a_editNoticePublishtime
            + "',releaser='"
            + a_editNoticeReleaser
            + "' where id='"
            + a_editNoticeId
            + "'";

    GetUpdate.updata(sql);

    return "success";
  }
コード例 #15
0
  @RequestMapping("uncompress")
  public String uncompress(
      @RequestParam(value = "descPath") String descPath,
      @RequestParam(value = "paths") String[] paths,
      @RequestParam(value = "conflict") String conflict,
      RedirectAttributes redirectAttributes)
      throws IOException {

    String rootPath = sc.getRealPath(ROOT_DIR);
    descPath = URLDecoder.decode(descPath, Constants.ENCODING);

    for (int i = 0, l = paths.length; i < l; i++) {
      String path = paths[i];
      path = URLDecoder.decode(path, Constants.ENCODING);
      // 只保留.zip的
      if (!path.toLowerCase().endsWith(".zip")) {
        continue;
      }
      paths[i] = rootPath + File.separator + path;
    }

    try {

      String descAbsolutePath = rootPath + File.separator + descPath;
      for (String path : paths) {
        CompressUtils.unzip(path, descAbsolutePath, "override".equals(conflict));
      }
      redirectAttributes.addFlashAttribute(Constants.MESSAGE, "解压成功!");
    } catch (Exception e) {
      redirectAttributes.addFlashAttribute(Constants.ERROR, e.getMessage());
    }

    redirectAttributes.addAttribute("path", URLEncoder.encode(descPath, Constants.ENCODING));
    return redirectToUrl(viewName("list"));
  }
コード例 #16
0
ファイル: ReportConstants.java プロジェクト: nirack/cambodia
  /**
   * 获取一个类的最外层包的上级目录
   *
   * @param cls
   * @return
   */
  @SuppressWarnings({"unchecked", "deprecation"})
  public static String getLastPackageParentPath(final Class cls) {
    // 类加载器
    final ClassLoader clsLoader = cls.getClassLoader();
    // 类路径
    final String clsAsResource = cls.getName().replace('.', '/').concat(".class");

    URL result = clsLoader.getResource(clsAsResource);
    String path = result.getPath();
    if ("jar".equalsIgnoreCase(result.getProtocol())) {
      // jar中的类处理
      try {
        path = new URL(path).getPath();
      } catch (MalformedURLException e) {
      }
      int location = path.indexOf("!/");
      if (location != -1) {
        path = path.substring(0, location);
      }
      path = URLDecoder.decode(path);
      path = new File(path).getParentFile().getParent();
    } else {
      // 非jar中类处理
      int location = path.lastIndexOf(clsAsResource);
      if (location != -1) {
        path = path.substring(0, location);
      }
      path = URLDecoder.decode(path);
      path = new File(path).getParent();
    }
    return path;
  }
コード例 #17
0
ファイル: MemoService.java プロジェクト: yoojh128/community
  public int write(HttpServletRequest request) {
    String id = request.getParameter("id");
    String content = null;
    String sido = null;
    String sigugun = null;

    System.out.println("하기 전 : " + request.getParameter("sido"));
    try {
      System.out.println("하고난 후 : " + URLDecoder.decode(request.getParameter("sido"), "UTF-8"));
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }

    try {
      content = URLDecoder.decode(request.getParameter("content"), "UTF-8");
      sido = URLDecoder.decode(request.getParameter("sido"), "UTF-8");
      sigugun = URLDecoder.decode(request.getParameter("sigugun"), "UTF-8");
    } catch (UnsupportedEncodingException e1) {
      e1.printStackTrace();
    }
    String posvalue = request.getParameter("posvalue");

    Memo memo = new Memo();
    memo.setId(id);
    memo.setContent(content);
    memo.setSido(sido);
    memo.setSigugun(sigugun);
    memo.setPosvalue(posvalue);

    int result = 0;
    result = dao.insertMemo(memo);

    return result;
  }
コード例 #18
0
ファイル: Xml.java プロジェクト: fxprunayre/core-geonetwork
    /**
     * @param href
     * @param base
     * @return
     * @throws TransformerException
     */
    public Source resolve(String href, String base) throws TransformerException {
      Resolver resolver = ResolverWrapper.getInstance();
      CatalogResolver catResolver = resolver.getCatalogResolver();
      if (Log.isDebugEnabled(Log.XML_RESOLVER)) {
        Log.debug(Log.XML_RESOLVER, "Trying to resolve " + href + ":" + base);
      }
      String decodedBase;
      try {
        decodedBase = URLDecoder.decode(base, Jeeves.ENCODING);
      } catch (UnsupportedEncodingException e1) {
        decodedBase = base;
      }
      String decodedHref;
      try {
        decodedHref = URLDecoder.decode(href, Jeeves.ENCODING);
      } catch (UnsupportedEncodingException e1) {
        decodedHref = href;
      }
      Source s = catResolver.resolve(decodedHref, decodedBase);
      // If resolver has a blank XSL file to replace non existing resolved file ...
      String blankXSLFile = resolver.getBlankXSLFile();
      if (blankXSLFile != null && s.getSystemId().endsWith(".xsl")) {
        // The resolved resource does not exist, set it to blank file path to not trigger
        // FileNotFound Exception
        try {
          if (Log.isDebugEnabled(Log.XML_RESOLVER)) {
            Log.debug(Log.XML_RESOLVER, "  Check if exist " + s.getSystemId());
          }
          File f;
          if (SystemUtils.IS_OS_WINDOWS) {
            String path = s.getSystemId();
            // fxp
            path = path.replaceAll("file:\\/", "");
            // heikki
            path = path.replaceAll("file:", "");

            f = new File(path);
          } else {
            f = new File(new URI(s.getSystemId()));
          }
          if (!(f.exists())) {
            if (Log.isDebugEnabled(Log.XML_RESOLVER)) {
              Log.debug(
                  Log.XML_RESOLVER,
                  "  Resolved resource "
                      + s.getSystemId()
                      + " does not exist. blankXSLFile returned instead.");
            }
            s.setSystemId(blankXSLFile);
          }
        } catch (URISyntaxException e) {
          e.printStackTrace();
        }
      }

      if (Log.isDebugEnabled(Log.XML_RESOLVER) && s != null) {
        Log.debug(Log.XML_RESOLVER, "Resolved as " + s.getSystemId());
      }
      return s;
    }
コード例 #19
0
ファイル: VertxServerUtils.java プロジェクト: ravibrk/qbit
  private MultiMap<String, String> paramMap(ServerWebSocket vertxServerWebSocket) {
    String query = vertxServerWebSocket.query();
    MultiMap<String, String> paramMap = MultiMap.empty();

    if (!Str.isEmpty(query)) {
      final String[] params = StringScanner.split(query, '&');

      if (params.length > 0) {
        paramMap = new MultiMapImpl<>();

        for (String param : params) {
          final String[] keyValue = StringScanner.split(param, '=');

          if (keyValue.length == 2) {

            String key = keyValue[0];
            String value = keyValue[1];
            try {
              key = URLDecoder.decode(key, "UTF-8");
              value = URLDecoder.decode(value, "UTF-8");
              paramMap.add(key, value);
            } catch (UnsupportedEncodingException e) {
              logger.warn(sputs("Unable to url decode key or value in param", key, value), e);
            }
          }
        }
      }
    }
    return paramMap;
  }
コード例 #20
0
ファイル: UDFURLDecode.java プロジェクト: zalot/cloudpack
 public Text evaluate(Text urlText, String flag1, String flag2) {
   if (urlText == null) {
     return null;
   }
   String url = urlText.toString();
   if (url != null) {
     try {
       url = url.trim();
       if (isgbk(url)) {
         url = URLDecoder.decode(url, "GBK");
       } else {
         url = URLDecoder.decode(url, "UTF-8");
       }
     } catch (Exception e) {
       try {
         url = evaluate(urlText, new Text("jsescape")).toString();
       } catch (Exception ee) {
         dstURL.set(url);
         return dstURL;
       }
     }
   }
   dstURL.set(url);
   return dstURL;
 }
コード例 #21
0
 @GET
 @Produces("application/json")
 @Path("/{id}")
 public String show(@PathParam("sid") String systemIdd, @PathParam("id") String idd) {
   String systemId = java.net.URLDecoder.decode(systemIdd);
   String id = java.net.URLDecoder.decode(idd);
   SCSCPClient sys = Wupsifer.getInstance().getClients().get(systemId);
   Computation c = sys.getComputation(id);
   //        System.out.println(" ----> " + c.toString() + " " + id + " " + systemId);
   DateFormat df = DateFormat.getInstance();
   JSONStringer js = new JSONStringer();
   try {
     js.object();
     js.key("id").value(c.getToken());
     js.key("startedAt").value(df.format(c.getStartedAt()));
     js.key("finishedAt").value(df.format(c.getStartedAt()));
     js.key("commandL").value(c.getRequest().toLatex());
     js.key("commandP").value(c.getRequest().toPopcorn());
     js.key("commandX").value(c.getRequest().toXml());
     js.key("resultL").value(c.getResult().toLatex());
     js.key("resultP").value(c.getResult().toPopcorn());
     js.key("resultX").value(c.getResult().toXml());
     js.endObject();
   } catch (Exception e) {
     e.printStackTrace();
     System.exit(1);
   }
   return js.toString();
 }
コード例 #22
0
ファイル: URIUtils.java プロジェクト: vdutat/nuxeo-common
 /** @return a map with request parameters information given an URI query. */
 public static Map<String, String> getRequestParameters(String uriQuery) {
   Map<String, String> parameters = null;
   if (uriQuery != null && uriQuery.length() > 0) {
     try {
       String[] items = uriQuery.split("&");
       if (items != null && items.length > 0) {
         parameters = new LinkedHashMap<String, String>();
         for (String item : items) {
           String[] param = item.split("=");
           if (param != null) {
             if (param.length == 2) {
               parameters.put(
                   URLDecoder.decode(param[0], "UTF-8"), URLDecoder.decode(param[1], "UTF-8"));
             } else if (param.length == 1) {
               parameters.put(URLDecoder.decode(param[0], "UTF-8"), null);
             }
           }
         }
       }
     } catch (UnsupportedEncodingException e) {
       log.error("Failed to get request parameters from uri", e);
     }
   }
   return parameters;
 }
コード例 #23
0
ファイル: Utils.java プロジェクト: jpetrell/gecko-dev
  /**
   * Takes a URI, extracting URI components.
   *
   * @param scheme the URI scheme on which to match.
   */
  @SuppressWarnings("deprecation")
  public static Map<String, String> extractURIComponents(String scheme, String uri) {
    if (uri.indexOf(scheme) != 0) {
      throw new IllegalArgumentException("URI scheme does not match: " + scheme);
    }

    // Do this the hard way to avoid taking a large dependency on
    // HttpClient or getting all regex-tastic.
    String components = uri.substring(scheme.length());
    HashMap<String, String> out = new HashMap<String, String>();
    String[] parts = components.split("&");
    for (int i = 0; i < parts.length; ++i) {
      String part = parts[i];
      if (part.length() == 0) {
        continue;
      }
      String[] pair = part.split("=", 2);
      switch (pair.length) {
        case 0:
          continue;
        case 1:
          out.put(URLDecoder.decode(pair[0]), null);
          break;
        case 2:
          out.put(URLDecoder.decode(pair[0]), URLDecoder.decode(pair[1]));
          break;
      }
    }
    return out;
  }
コード例 #24
0
 public static void triggerInstall(SolutionInstallationInfo info) {
   String installId = info.getInstallId();
   String mpcState = info.getState();
   CatalogDescriptor catalogDescriptor = info.getCatalogDescriptor();
   MarketplaceWizardCommand command = new MarketplaceWizardCommand();
   command.setSelectedCatalogDescriptor(catalogDescriptor);
   try {
     if (mpcState != null) {
       command.setWizardState(URLDecoder.decode(mpcState, UTF_8));
     }
     Map<String, Operation> nodeIdToOperation = new HashMap<String, Operation>();
     nodeIdToOperation.put(URLDecoder.decode(installId, UTF_8), Operation.INSTALL);
     command.setOperationByNodeId(nodeIdToOperation);
   } catch (UnsupportedEncodingException e1) {
     throw new IllegalStateException(e1);
   }
   try {
     command.execute(new ExecutionEvent());
   } catch (ExecutionException e) {
     IStatus status =
         MarketplaceClientUi.computeStatus(
             new InvocationTargetException(e),
             Messages.MarketplaceBrowserIntegration_cannotOpenMarketplaceWizard);
     StatusManager.getManager()
         .handle(status, StatusManager.SHOW | StatusManager.BLOCK | StatusManager.LOG);
   }
 }
コード例 #25
0
  private String getVerifier(String callbackUrl) {
    String verifier = "";

    try {
      callbackUrl = callbackUrl.replace("twitterapp", "http");

      URL url = new URL(callbackUrl);
      String query = url.getQuery();

      String array[] = query.split("&");

      for (String parameter : array) {
        String v[] = parameter.split("=");

        if (URLDecoder.decode(v[0]).equals(oauth.signpost.OAuth.OAUTH_VERIFIER)) {
          verifier = URLDecoder.decode(v[1]);
          break;
        }
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    }

    return verifier;
  }
コード例 #26
0
  @DB
  @Override
  @ActionEvent(
      eventType = EventTypes.EVENT_LB_CERT_UPLOAD,
      eventDescription = "Uploading a certificate to cloudstack",
      async = false)
  public SslCertResponse uploadSslCert(UploadSslCertCmd certCmd) {
    try {

      String cert = URLDecoder.decode(certCmd.getCert(), "UTF-8");
      String key = URLDecoder.decode(certCmd.getKey(), "UTF-8");
      String password = certCmd.getPassword();
      String chain =
          certCmd.getChain() == null ? null : URLDecoder.decode(certCmd.getChain(), "UTF-8");

      validate(cert, key, password, chain);
      s_logger.debug("Certificate Validation succeeded");

      String fingerPrint = generateFingerPrint(parseCertificate(cert));

      Long accountId = CallContext.current().getCallingAccount().getId();
      Long domainId = CallContext.current().getCallingAccount().getDomainId();

      SslCertVO certVO =
          new SslCertVO(cert, key, password, chain, accountId, domainId, fingerPrint);
      _sslCertDao.persist(certVO);

      return createCertResponse(certVO, null);

    } catch (UnsupportedEncodingException e) {
      throw new CloudRuntimeException("Error decoding certificate data");
    }
  }
コード例 #27
0
  /** Tests the usage of complex keys for supported methods. */
  @Test
  public void testComplexKeys() throws UnsupportedEncodingException {
    ComplexKey start = ComplexKey.of(2012, 05, 05);
    ComplexKey end = ComplexKey.of(2012, 05, 12);
    ComplexKey key = ComplexKey.of("mykey");
    ComplexKey keys = ComplexKey.of("users:10", "users:11");

    Query query = new Query();
    query.setRangeStart(start);
    query.setRangeEnd(end);
    assertEquals(2, query.getArgs().size());
    String result = URLDecoder.decode(query.toString(), "UTF-8");
    assertEquals("?startkey=[2012,5,5]&endkey=[2012,5,12]", result);

    query = new Query();
    query.setRange(start, end);
    assertEquals(2, query.getArgs().size());
    result = URLDecoder.decode(query.toString(), "UTF-8");
    assertEquals("?startkey=[2012,5,5]&endkey=[2012,5,12]", result);

    query = new Query();
    query.setKey(key);
    assertEquals(1, query.getArgs().size());
    result = URLDecoder.decode(query.toString(), "UTF-8");
    assertEquals("?key=\"mykey\"", result);

    query = new Query();
    query.setKeys(keys);
    assertEquals(1, query.getArgs().size());
    result = URLDecoder.decode(query.toString(), "UTF-8");
    assertEquals("?keys=[\"users:10\",\"users:11\"]", result);
  }
コード例 #28
0
ファイル: WebDavWagon.java プロジェクト: shawjef3/maven-wagon
  public List<String> getFileList(String destinationDirectory)
      throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
    String repositoryUrl = repository.getUrl();
    String url = repositoryUrl + (repositoryUrl.endsWith("/") ? "" : "/") + destinationDirectory;

    PropFindMethod method = null;
    try {
      if (isDirectory(url)) {
        DavPropertyNameSet nameSet = new DavPropertyNameSet();
        nameSet.add(DavPropertyName.create(DavConstants.PROPERTY_DISPLAYNAME));

        method = new PropFindMethod(url, nameSet, DavConstants.DEPTH_1);
        int status = execute(method);
        if (method.succeeded()) {
          ArrayList<String> dirs = new ArrayList<String>();
          MultiStatus multiStatus = method.getResponseBodyAsMultiStatus();

          for (int i = 0; i < multiStatus.getResponses().length; i++) {

            MultiStatusResponse response = multiStatus.getResponses()[i];

            String entryUrl = response.getHref();
            String fileName = PathUtils.filename(URLDecoder.decode(entryUrl));
            if (entryUrl.endsWith("/")) {
              if (i == 0) {
                // by design jackrabbit webdav sticks parent directory as the first entry
                // so we need to ignore this entry
                // http://www.nabble.com/Extra-entry-in-get-file-list-with-jackrabbit-webdav-td21262786.html
                // http://www.webdav.org/specs/rfc4918.html#rfc.section.9.1
                continue;
              }

              // extract "dir/" part of "path.to.dir/"
              fileName = PathUtils.filename(PathUtils.dirname(URLDecoder.decode(entryUrl))) + "/";
            }

            if (!StringUtils.isEmpty(fileName)) {
              dirs.add(fileName);
            }
          }
          return dirs;
        }

        if (status == HttpStatus.SC_NOT_FOUND) {
          throw new ResourceDoesNotExistException("Destination directory does not exist: " + url);
        }
      }
    } catch (DavException e) {
      throw new TransferFailedException(e.getMessage(), e);
    } catch (IOException e) {
      throw new TransferFailedException(e.getMessage(), e);
    } finally {
      if (method != null) {
        method.releaseConnection();
      }
    }
    throw new ResourceDoesNotExistException(
        "Destination path exists but is not a " + "WebDAV collection (directory): " + url);
  }
コード例 #29
0
ファイル: TransportToken.java プロジェクト: aldaris/opensso
  private void initializeFromString(String transportString) throws AgentException {

    if (!transportString.startsWith(VERSION_HEADER)) {
      throw new AgentException("Invalid transport string");
    }

    StringTokenizer stok = new StringTokenizer(transportString, FIELD_SEPARATOR);
    int numTokens = stok.countTokens();

    if (numTokens < 3) {
      throw new AgentException("Malformed transport string");
    }

    // Check Version
    String versionString = getFieldValue(stok.nextToken(), VERSION_HEADER_MARKER);
    if (!versionString.equals(VERSION_STRING)) {
      throw new AgentException("Invalid transport version");
    }

    // Set SSO Token
    setSSOTokenID(URLDecoder.decode(getFieldValue(stok.nextToken(), SSO_HEADER_MARKER)));

    // Set IP Address
    setIPAddress(getFieldValue(stok.nextToken(), IP_HEADER_MARKER));

    // Initialize token prefix
    initTokenPrefix();

    // Parse attributes
    if (numTokens > 3) {
      int attributeCount = 0;
      boolean attributeReadOK = true;
      try {
        attributeCount =
            Integer.parseInt(getFieldValue(stok.nextToken(), ATTRIBUTE_COUNT_HEADER_MARKER));
      } catch (NumberFormatException ex) {
        attributeReadOK = false;
      }

      if (!attributeReadOK || attributeCount <= 0) {
        throw new AgentException("Invalid attirbute count");
      }

      for (int i = 0; i < attributeCount; i++) {
        if (!stok.hasMoreTokens()) {
          throw new AgentException("Missing attribute detected in transport");
        }
        String nextField = stok.nextToken();
        int index = nextField.indexOf('=');
        if (index > 0 && index < nextField.length() - 1) {
          String attributeName = nextField.substring(0, index);
          String attributeValue = nextField.substring(index + 1);
          getAttributes().put(URLDecoder.decode(attributeName), URLDecoder.decode(attributeValue));
        } else {
          throw new AgentException("Invalid attribute field");
        }
      }
    }
  }
コード例 #30
0
  protected void updateDoc(
      Document doc,
      String base,
      Map<String, Definition> mp,
      Map<String, SchemaReference> smp,
      EndpointInfo ei) {
    List<Element> elementList = null;

    try {
      elementList =
          DOMUtils.findAllElementsByTagNameNS(
              doc.getDocumentElement(), "http://www.w3.org/2001/XMLSchema", "import");
      for (Element el : elementList) {
        String sl = el.getAttribute("schemaLocation");
        if (smp.containsKey(URLDecoder.decode(sl, "utf-8"))) {
          el.setAttribute("schemaLocation", rewriteSchemaLocation(base, sl));
        }
      }

      elementList =
          DOMUtils.findAllElementsByTagNameNS(
              doc.getDocumentElement(), "http://www.w3.org/2001/XMLSchema", "include");
      for (Element el : elementList) {
        String sl = el.getAttribute("schemaLocation");
        if (smp.containsKey(URLDecoder.decode(sl, "utf-8"))) {
          el.setAttribute("schemaLocation", rewriteSchemaLocation(base, sl));
        }
      }
      elementList =
          DOMUtils.findAllElementsByTagNameNS(
              doc.getDocumentElement(), "http://www.w3.org/2001/XMLSchema", "redefine");
      for (Element el : elementList) {
        String sl = el.getAttribute("schemaLocation");
        if (smp.containsKey(URLDecoder.decode(sl, "utf-8"))) {
          el.setAttribute("schemaLocation", rewriteSchemaLocation(base, sl));
        }
      }
      elementList =
          DOMUtils.findAllElementsByTagNameNS(
              doc.getDocumentElement(), "http://schemas.xmlsoap.org/wsdl/", "import");
      for (Element el : elementList) {
        String sl = el.getAttribute("location");
        if (mp.containsKey(URLDecoder.decode(sl, "utf-8"))) {
          el.setAttribute("location", base + "?wsdl=" + sl.replace(" ", "%20"));
        }
      }
    } catch (UnsupportedEncodingException e) {
      throw new WSDLQueryException(
          new org.apache.cxf.common.i18n.Message("COULD_NOT_PROVIDE_WSDL", LOG, base), e);
    }

    rewriteOperationAddress(ei, doc, base);

    try {
      doc.setXmlStandalone(true);
    } catch (Exception ex) {
      // likely not DOM level 3
    }
  }