Esempio n. 1
0
  /** 2、字符串的Trim */
  @Test
  public void test2() {
    // trim
    System.out.println(StringUtils.trim(null)); // null
    System.out.println(StringUtils.trim("")); // ""
    System.out.println(StringUtils.trim("     ")); // ""
    System.out.println(StringUtils.trim("abc")); // "abc"
    System.out.println(StringUtils.trim("    abc")); // "abc"
    System.out.println(StringUtils.trim("    abc  ")); // "abc"
    System.out.println(StringUtils.trim("    ab c  ")); // "ab c"

    // strip
    System.out.println(StringUtils.strip(null)); // null
    System.out.println(StringUtils.strip("")); // ""
    System.out.println(StringUtils.strip("   ")); // ""
    System.out.println(StringUtils.strip("abc")); // "abc"
    System.out.println(StringUtils.strip("  abc")); // "abc"
    System.out.println(StringUtils.strip("abc  ")); // "abc"
    System.out.println(StringUtils.strip(" abc ")); // "abc"
    System.out.println(StringUtils.strip(" ab c ")); // "ab c"

    System.out.println(StringUtils.strip("  abcyx", "xyz")); // "  abc"

    System.out.println(StringUtils.stripStart("yxabcxyz  ", "xyz")); // "abcxyz  "
    System.out.println(StringUtils.stripEnd("  xyzabcyx", "xyz")); // "  xyzabc"
  }
Esempio n. 2
0
  /**
   * Creates request against SPNEGO protected web-app with FORM fallback. It doesn't try to login
   * using SPNEGO - it uses FORM authn directly.
   *
   * @param contextUrl
   * @param page
   * @param user
   * @param pass
   * @param expectedStatusCode
   * @return
   * @throws IOException
   * @throws URISyntaxException
   * @throws PrivilegedActionException
   * @throws LoginException
   */
  public static String makeHttpCallWoSPNEGO(
      final String contextUrl,
      final String page,
      final String user,
      final String pass,
      final int expectedStatusCode)
      throws IOException, URISyntaxException, PrivilegedActionException, LoginException {
    final String strippedContextUrl = StringUtils.stripEnd(contextUrl, "/");
    final String url = strippedContextUrl + page;
    LOGGER.info("Requesting URL: " + url);
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.setRedirectStrategy(REDIRECT_STRATEGY);
    String unauthorizedPageBody = null;
    try {
      final HttpGet httpGet = new HttpGet(url);
      HttpResponse response = httpClient.execute(httpGet);
      int statusCode = response.getStatusLine().getStatusCode();
      if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
        assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
        return EntityUtils.toString(response.getEntity());
      }
      final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
      assertTrue(
          "WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0);
      final Set<String> authnHeaderValues = new HashSet<String>();
      for (final Header header : authnHeaders) {
        authnHeaderValues.add(header.getValue());
      }
      assertTrue(
          "WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate"));

      LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
      unauthorizedPageBody = EntityUtils.toString(response.getEntity());

      assertNotNull(unauthorizedPageBody);
      LOGGER.info(unauthorizedPageBody);
      assertTrue(unauthorizedPageBody.contains("j_security_check"));

      HttpPost httpPost = new HttpPost(strippedContextUrl + "/j_security_check");
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
      nameValuePairs.add(new BasicNameValuePair("j_username", user));
      nameValuePairs.add(new BasicNameValuePair("j_password", pass));
      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      response = httpClient.execute(httpPost);
      statusCode = response.getStatusLine().getStatusCode();
      assertEquals(
          "Unexpected status code returned after the authentication.",
          expectedStatusCode,
          statusCode);
      return EntityUtils.toString(response.getEntity());
    } finally {
      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      httpClient.getConnectionManager().shutdown();
    }
  }
Esempio n. 3
0
 @DataBoundConstructor
 public CasSecurityRealm(
     String casServerUrl,
     CasProtocol casProtocol,
     Boolean forceRenewal,
     Boolean enableSingleSignOut) {
   this.casServerUrl = StringUtils.stripEnd(casServerUrl, "/") + "/";
   this.casProtocol = casProtocol;
   this.forceRenewal = forceRenewal;
   this.enableSingleSignOut = enableSingleSignOut;
 }
 public static String toPropertyPath(
     Expression<?> expr, char propertySeparator, char collectionSeparator) {
   Stack<String> results = new Stack<>();
   expr.accept(
       new PropertyPathExpressionVisitor(
           String.valueOf(propertySeparator), String.valueOf(collectionSeparator)),
       results);
   StringBuilder sb = new StringBuilder();
   while (!results.isEmpty()) {
     sb.append(results.pop());
   }
   return StringUtils.stripEnd(
       sb.toString(), String.valueOf(propertySeparator) + String.valueOf(collectionSeparator));
 }
  private List<String> getPartitionValues(String partitionSpec) {
    // Warning - incorrect for cases where there are commas in values and
    // other corner cases.
    String[] partitionSpecSplit = partitionSpec.split(",");
    List<String> partitionValues = new ArrayList<>();

    for (String columnSpec : partitionSpecSplit) {
      columnSpec = StringUtils.stripEnd(columnSpec, " \t\n");
      columnSpec = StringUtils.stripStart(columnSpec, " \t\n");
      // columnSpec should be something of the form ds='1'
      String[] columnSpecSplit = columnSpec.split("=");
      if (columnSpecSplit.length != 2) {
        throw new RuntimeException("Unexpected column spec " + columnSpec);
      }
      String partitionColumnValue = columnSpecSplit[1].replace("'", "");
      partitionValues.add(partitionColumnValue);
    }
    return partitionValues;
  }
  private InputStream stripLineEnds(InputStream is, String charset, char chartoStrip)
      throws IOException {
    log.debug("Stripping [ {} ] from the end of lines.", chartoStrip);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final PrintStream printStream = new PrintStream(baos);

    final LineIterator lineIterator = IOUtils.lineIterator(is, charset);

    while (lineIterator.hasNext()) {
      String line = StringUtils.stripToNull(lineIterator.next());
      if (line != null) {
        line = StringUtils.stripEnd(line, String.valueOf(chartoStrip));
        printStream.println(line);
      }
    }

    return new ByteArrayInputStream(baos.toByteArray());
  }
  protected void collectExpectedIssues(String comment, int line) {
    String expectedStart = getExpectedIssueTrigger();
    if (comment.startsWith(expectedStart)) {
      String cleanedComment = StringUtils.remove(comment, expectedStart);

      EnumMap<IssueAttribute, String> attr = new EnumMap<>(IssueAttribute.class);
      String expectedMessage = StringUtils.substringBetween(cleanedComment, "{{", "}}");
      if (StringUtils.isNotEmpty(expectedMessage)) {
        attr.put(IssueAttribute.MESSAGE, expectedMessage);
      }
      int expectedLine = line;
      String attributesSubstr = extractAttributes(comment, attr);

      cleanedComment =
          StringUtils.stripEnd(
              StringUtils.remove(
                  StringUtils.remove(cleanedComment, "[[" + attributesSubstr + "]]"),
                  "{{" + expectedMessage + "}}"),
              " \t");
      if (StringUtils.startsWith(cleanedComment, "@")) {
        final int lineAdjustment;
        final char firstChar = cleanedComment.charAt(1);
        final int endIndex = cleanedComment.indexOf(' ');
        if (endIndex == -1) {
          lineAdjustment = Integer.parseInt(cleanedComment.substring(2));
        } else {
          lineAdjustment = Integer.parseInt(cleanedComment.substring(2, endIndex));
        }
        if (firstChar == '+') {
          expectedLine += lineAdjustment;
        } else if (firstChar == '-') {
          expectedLine -= lineAdjustment;
        } else {
          Fail.fail("Use only '@+N' or '@-N' to shifts messages.");
        }
      }
      updateEndLine(expectedLine, attr);
      expected.put(expectedLine, attr);
    }
  }
Esempio n. 8
0
    public FormValidation doCheckCasServerUrl(@QueryParameter String value)
        throws IOException, ServletException {
      value = Util.fixEmptyAndTrim(value);
      if (value == null)
        return FormValidation.error(Messages.CasSecurityRealm_casServerUrl_missingUrl());

      try {
        URL url = new URL(StringUtils.stripEnd(value, "/") + "/login");
        String response = CommonUtils.getResponseFromServer(url, "UTF-8");
        if (!response.contains("username")) {
          return FormValidation.warning(Messages.CasSecurityRealm_casServerUrl_invalidResponse());
        }
      } catch (MalformedURLException e) {
        return FormValidation.error(
            Messages.CasSecurityRealm_casServerUrl_malformedUrl() + ": " + e.getMessage());
      } catch (RuntimeException e) {
        return FormValidation.error(
            Messages.CasSecurityRealm_casServerUrl_cannotGetResponse()
                + ": "
                + (e.getCause() == null ? e : e.getCause()));
      }

      return FormValidation.ok();
    }
 private String stripEndAndStart(String srcString, String stripChars) {
   srcString = StringUtils.stripEnd(srcString, stripChars);
   srcString = StringUtils.stripStart(srcString, stripChars);
   return srcString;
 }
Esempio n. 10
0
  /**
   * Creates request against SPNEGO protected web-app with FORM fallback. It tries to login using
   * SPNEGO first - if it fails, FORM is used.
   *
   * @param contextUrl
   * @param page
   * @param user
   * @param pass
   * @param expectedStatusCode
   * @return
   * @throws IOException
   * @throws URISyntaxException
   * @throws PrivilegedActionException
   * @throws LoginException
   */
  public static String makeHttpCallWithFallback(
      final String contextUrl,
      final String page,
      final String user,
      final String pass,
      final int expectedStatusCode)
      throws IOException, URISyntaxException, PrivilegedActionException, LoginException {
    final String strippedContextUrl = StringUtils.stripEnd(contextUrl, "/");
    final String url = strippedContextUrl + page;
    LOGGER.info("Requesting URL: " + url);
    final DefaultHttpClient httpClient = new DefaultHttpClient();
    httpClient.setRedirectStrategy(REDIRECT_STRATEGY);
    String unauthorizedPageBody = null;
    try {
      httpClient
          .getAuthSchemes()
          .register(AuthPolicy.SPNEGO, new JBossNegotiateSchemeFactory(true));
      httpClient
          .getCredentialsProvider()
          .setCredentials(new AuthScope(null, -1, null), new NullHCCredentials());

      final HttpGet httpGet = new HttpGet(url);
      final HttpResponse response = httpClient.execute(httpGet);
      int statusCode = response.getStatusLine().getStatusCode();
      if (HttpServletResponse.SC_UNAUTHORIZED != statusCode || StringUtils.isEmpty(user)) {
        assertEquals("Unexpected HTTP response status code.", expectedStatusCode, statusCode);
        return EntityUtils.toString(response.getEntity());
      }
      final Header[] authnHeaders = response.getHeaders("WWW-Authenticate");
      assertTrue(
          "WWW-Authenticate header is present", authnHeaders != null && authnHeaders.length > 0);
      final Set<String> authnHeaderValues = new HashSet<String>();
      for (final Header header : authnHeaders) {
        authnHeaderValues.add(header.getValue());
      }
      assertTrue(
          "WWW-Authenticate: Negotiate header is missing", authnHeaderValues.contains("Negotiate"));

      LOGGER.debug("HTTP response was SC_UNAUTHORIZED, let's authenticate the user " + user);
      unauthorizedPageBody = EntityUtils.toString(response.getEntity());

      // Use our custom configuration to avoid reliance on external config
      Configuration.setConfiguration(new Krb5LoginConfiguration());
      // 1. Authenticate to Kerberos.
      final LoginContext lc =
          new LoginContext(Utils.class.getName(), new UsernamePasswordHandler(user, pass));
      lc.login();

      // 2. Perform the work as authenticated Subject.
      final String responseBody =
          Subject.doAs(
              lc.getSubject(),
              new PrivilegedExceptionAction<String>() {
                public String run() throws Exception {
                  final HttpResponse response = httpClient.execute(httpGet);
                  int statusCode = response.getStatusLine().getStatusCode();
                  assertEquals(
                      "Unexpected status code returned after the authentication.",
                      expectedStatusCode,
                      statusCode);
                  return EntityUtils.toString(response.getEntity());
                }
              });
      lc.logout();
      return responseBody;
    } catch (LoginException e) {
      assertNotNull(unauthorizedPageBody);
      assertTrue(unauthorizedPageBody.contains("j_security_check"));

      HttpPost httpPost = new HttpPost(strippedContextUrl + "/j_security_check");
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
      nameValuePairs.add(new BasicNameValuePair("j_username", user));
      nameValuePairs.add(new BasicNameValuePair("j_password", pass));
      httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
      final HttpResponse response = httpClient.execute(httpPost);
      int statusCode = response.getStatusLine().getStatusCode();
      assertEquals(
          "Unexpected status code returned after the authentication.",
          expectedStatusCode,
          statusCode);
      return EntityUtils.toString(response.getEntity());
    } finally {
      // When HttpClient instance is no longer needed,
      // shut down the connection manager to ensure
      // immediate deallocation of all system resources
      httpClient.getConnectionManager().shutdown();
    }
  }
Esempio n. 11
0
 private String trimWhitespace(String str) {
   str = StringUtils.stripEnd(str, " \t\n");
   str = StringUtils.stripStart(str, " \t\n");
   return str;
 }
  public void checkSchema(String[] clientConfigLocations)
      throws ClientPoolException, StorageClientException {
    checkClosed();
    Statement statement = null;
    try {

      statement = jcbcStorageClientConnection.getConnection().createStatement();
      try {
        statement.execute(getSql(SQL_CHECKSCHEMA));
        inc("schema");
        LOGGER.info("Schema Exists");
        return;
      } catch (SQLException e) {
        LOGGER.info("Schema does not exist {}", e.getMessage());
      }

      for (String clientSQLLocation : clientConfigLocations) {
        String clientDDL = clientSQLLocation + ".ddl";
        InputStream in = this.getClass().getClassLoader().getResourceAsStream(clientDDL);
        if (in != null) {
          try {
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF8"));
            int lineNo = 1;
            String line = br.readLine();
            StringBuilder sqlStatement = new StringBuilder();
            while (line != null) {
              line = StringUtils.stripEnd(line, null);
              if (!line.isEmpty()) {
                if (line.startsWith(SQL_COMMENT)) {
                  LOGGER.info("Comment {} ", line);
                } else if (line.endsWith(SQL_EOL)) {
                  sqlStatement.append(line.substring(0, line.length() - 1));
                  String ddl = sqlStatement.toString();
                  try {
                    statement.executeUpdate(ddl);
                    LOGGER.info("SQL OK    {}:{} {} ", new Object[] {clientDDL, lineNo, ddl});
                  } catch (SQLException e) {
                    LOGGER.warn(
                        "SQL ERROR {}:{} {} {} ",
                        new Object[] {clientDDL, lineNo, ddl, e.getMessage()});
                  }
                  sqlStatement = new StringBuilder();
                } else {
                  sqlStatement.append(line);
                }
              }
              line = br.readLine();
              lineNo++;
            }
            br.close();
            LOGGER.info("Schema Created from {} ", clientDDL);

            break;
          } catch (Throwable e) {
            LOGGER.error("Failed to load Schema from {}", clientDDL, e);
          } finally {
            try {
              in.close();
            } catch (IOException e) {
              LOGGER.error("Failed to close stream from {}", clientDDL, e);
            }
          }
        } else {
          LOGGER.info("No Schema found at {} ", clientDDL);
        }
      }

    } catch (SQLException e) {
      LOGGER.info("Failed to create schema ", e);
      throw new ClientPoolException("Failed to create schema ", e);
    } finally {
      try {
        statement.close();
        dec("schema");
      } catch (Throwable e) {
        LOGGER.debug("Failed to close statement in validate ", e);
      }
    }
  }
Esempio n. 13
0
  public List getAttributes() {
    List attrs = new ArrayList();
    String content = null;
    int state = TAG;
    int start = -1;
    int startLength = 0;
    int endLength = 0;
    if (ITypeConstants.PI.equals(getType())) {
      startLength = 2;
      endLength = 2;
    } else if (ITypeConstants.DECL.equals(getType())) {
      //      if ("!DOCTYPE".equals(getName()))
      //        return getDoctypeAttributes();
      startLength = 1;
      endLength = 1;
    } else if (ITypeConstants.TAG.equals(getType())) {
      startLength = 1;
      endLength = 1;
    } else if (ITypeConstants.EMPTYTAG.equals(getType())) {
      startLength = 1;
      endLength = 2;
    } else {
      return attrs;
    }

    try {
      content = document.get(getOffset(), getLength());
    } catch (BadLocationException e) {
      UIPlugin.log(e);
      return attrs;
    }

    String name = getName();
    int initial = name == null ? 0 : content.indexOf(name) + name.length();

    for (int i = startLength + initial; i < content.length() - endLength; i++) {
      char c = content.charAt(i);
      switch (c) {
        case '"':
          if (state == DOUBLEQUOTE) {
            attrs.add(
                new XMLNode(getOffset() + start, i - start + 1, ITypeConstants.ATTR, document));
            start = -1;
            state = TAG;
          } else if (state == SINGLEQUOTE) {
            break;
          } else if (state != ATTR) {
            start = i;
            state = DOUBLEQUOTE;
          } else {
            state = DOUBLEQUOTE;
          }
          break;
        case '\'':
          if (state == SINGLEQUOTE) {
            attrs.add(
                new XMLNode(getOffset() + start, i - start + 1, ITypeConstants.ATTR, document));
            start = -1;
            state = TAG;
          } else if (state == DOUBLEQUOTE) {
            break;
          } else if (state != ATTR) {
            start = i;
            state = SINGLEQUOTE;
          } else {
            state = SINGLEQUOTE;
          }
          break;
        default:
          if (!Character.isWhitespace(c)) {
            if (state == TAG) {
              start = i;
              state = ATTR;
            }
          } else if (state == ATTR) {
            boolean stop = false;
            int j = i;
            // lookahead to see if this is an attribute name with no value
            for (; j < content.length() - endLength; j++) {
              char lookahead = content.charAt(j);

              switch (lookahead) {
                case '=':
                  break;
                case '"':
                  break;
                case '\'':
                  break;
                default:
                  stop = !Character.isWhitespace(lookahead);
                  break;
              }
              if (stop) break;
            }
            if (stop) {

              attrs.add(
                  new XMLNode(getOffset() + start, i - start + 1, ITypeConstants.ATTR, document));
              start = -1;
              state = TAG;
            }
          }
      }
    }

    if (start != -1) {
      attrs.add(
          new XMLNode(
              getOffset() + start,
              content.length()
                  - startLength
                  - start
                  - (!getType().equals(ITypeConstants.TAG) ? 1 : 0),
              ITypeConstants.ATTR,
              document));
    }
    for (Iterator iter = attrs.iterator(); iter.hasNext(); ) {
      XMLNode attr = (XMLNode) iter.next();
      attr.length = StringUtils.stripEnd(attr.getContent(), null).length();
    }

    return attrs;
  }