List of usage examples for org.apache.commons.lang3 StringUtils trimToEmpty
public static String trimToEmpty(final String str)
Removes control characters (char <= 32) from both ends of this String returning an empty String ("") if the String is empty ("") after the trim or if it is null .
From source file:com.streamsets.pipeline.stage.origin.jdbc.cdc.postgres.PostgresCDCSource.java
@Override public String produce(String lastSourceOffset, int maxBatchSize, final BatchMaker batchMaker) throws StageException { Long offsetAsLong = Long.valueOf(0); if (dummyRecord == null) { dummyRecord = getContext().createRecord("DUMMY"); }/*from www . j a va2s . c o m*/ final int batchSize = Math.min(configBean.baseConfigBean.maxBatchSize, maxBatchSize); int recordGenerationAttempts = 0; boolean recordsProduced = false; if (lastSourceOffset != null) { setOffset(StringUtils.trimToEmpty(lastSourceOffset)); } if (getOffset() != null) { offsetAsLong = LogSequenceNumber.valueOf(getOffset()).asLong(); } PostgresWalRecord postgresWalRecord = null; if (!runnerCreated) { createRunner(); runnerCreated = true; } if ((!generationStarted) && runnerCreated) { startGeneration(); generationStarted = true; } while (generationStarted && !getContext().isStopped() && !recordsProduced && recordGenerationAttempts++ < MAX_RECORD_GENERATION_ATTEMPTS) { postgresWalRecord = cdcQueue.poll(); if ((postgresWalRecord != null) && (postgresWalRecord.getLsn().asLong() > offsetAsLong)) { final Record record = processWalRecord(postgresWalRecord); if (record != null) { Map<String, String> attributes = new HashMap<>(); attributes.put(LSN, postgresWalRecord.getLsn().asString()); attributes.put(XID, postgresWalRecord.getXid()); attributes.put(TIMESTAMP_HEADER, postgresWalRecord.getTimestamp()); attributes.forEach((k, v) -> record.getHeader().setAttribute(k, v)); batchMaker.addRecord(record); walReceiver.setLsnFlushed(postgresWalRecord.getLsn()); this.setOffset(postgresWalRecord.getLsn().asString()); } } try { Thread.sleep(100); } catch (InterruptedException e) { LOG.debug("Interrupted wait"); } } return getOffset(); }
From source file:com.widowcrawler.terminator.parse.Parser.java
private String rulePath() { //System.out.println("rulePath()"); int start = dataPtr; while (!isEndOfFile() && !isCommentStart() && !isEndline() && !isWhitespace()) { next();/*from w w w. ja va2s . com*/ } String path = StringUtils.trimToEmpty(data.substring(start, dataPtr)); whitespace(); return path; }
From source file:com.jiangyifen.ec2.globaldata.license.LicenseManager.java
/** * license/*w w w. j a v a 2s. c o m*/ * * @param localmd5 * @param mac * @param date * @param count * @return */ private static Boolean licenseValidate(String localmd5, String mac, String date, String count) { // ?md5 ?? localmd5 = StringUtils.trimToEmpty(localmd5); // ? mac = StringUtils.trimToEmpty(mac); date = StringUtils.trimToEmpty(date); count = StringUtils.trimToEmpty(count); // mac?date?count?? Boolean isWellformat = regexMatchCheck(mac, date, count); if (isWellformat) { //continue } else { return false; } // 32?md5 String saltedLicense = mac + LicenseManager.LICENSE_SALT + date + count; String bit32_md5_result = bit32_md5(saltedLicense); // ? if (localmd5.equals(bit32_md5_result)) { //? // LicenseManager.LICENSE_DATE try { Date expiredate = simpleDateFormat.parse(date); if (new Date().after(expiredate)) { logger.warn("chb: License expires, license expiredate is " + date); return false; } } catch (ParseException e) { e.printStackTrace(); logger.warn("chb: License date parse exception"); return false; } return true; } else { logger.warn("chb: License and bit32_md5_result not match , changed !!!"); return false; } }
From source file:com.mirth.connect.plugins.httpauth.digest.DigestAuthenticator.java
@Override public AuthenticationResult authenticate(RequestInfo request) { DigestHttpAuthProperties properties = getReplacedProperties(request); List<String> authHeaderList = request.getHeaders().get(HttpHeader.AUTHORIZATION.asString()); Map<String, String> directives = new CaseInsensitiveMap<String, String>(); String nonceString = null;/*from w w w .jav a 2 s . c o m*/ String nonceCountString = null; String nonceOpaque = ""; /* * This status is used to determine whether or not to send back a challenge. It's also used * to determine whether the nonce used by the client is stale (expired past the max nonce * age, or the max nonce count). */ Status status = Status.INVALID; if (CollectionUtils.isNotEmpty(authHeaderList)) { String authHeader = authHeaderList.iterator().next(); /* * This splits up the Authorization header into name-value pairs and puts them into the * directives map. */ QuotedStringTokenizer tokenizer = new QuotedStringTokenizer(authHeader, "=, ", true, false); String directive = null; String lastToken = null; while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); char c; if (token.length() == 1 && ((c = token.charAt(0)) == '=' || c == ',' || c == ' ')) { if (c == '=') { directive = lastToken; } else if (c == ',') { directive = null; } } else { if (directive != null) { directives.put(directive, token); directive = null; } lastToken = token; } } nonceString = directives.get(NONCE); nonceCountString = directives.get(NONCE_COUNT); // The authentication attempt isn't valid without a nonce if (StringUtils.isNotBlank(nonceString)) { Nonce nonce = nonceMap.get(nonceString); if (nonce != null) { // Nonce was found nonceOpaque = nonce.getOpaque(); if (nonce.isExpired()) { status = Status.STALE; } else if (StringUtils.isNotBlank(nonceCountString)) { /* * Nonce count is supplied, so update the nonce with it. If the count is * less than or equal to the current counter, it's an invalid request. If * the count is greater than the max nonce count, the nonce is stale. */ try { status = nonce.updateCount(Long.parseLong(nonceCountString, 16)); } catch (NumberFormatException e) { // If an exception occurs parsing the nonce count, leave the status as invalid } } else { /* * If no nonce count was supplied, just increment the internal counter by 1. * If the count is greater than the max nonce count, the nonce is stale. */ status = nonce.incrementCount(); } } else { // Nonce has expired or never existed status = Status.STALE; } } } // Remove expired nonces from the cache cleanupNonces(); /* * If the status is valid or stale, attempt to calculate the digest and compare it to the * response hash. If the response hash is incorrect, the status should always be set to * invalid. If the response hash is correct but the nonce is stale, the stale directive * should be set to true in the response challenge. */ if (status != Status.INVALID) { try { // Retrieve directives from the map String username = directives.get(USERNAME); String realm = directives.get(REALM); String uri = directives.get(URI); String response = directives.get(RESPONSE); String clientNonceString = directives.get(CLIENT_NONCE); String qop = directives.get(QOP); String algorithm = directives.get(ALGORITHM); String opaque = StringUtils.trimToEmpty(directives.get(OPAQUE)); // Do some initial validation on required directives if (StringUtils.isBlank(username)) { throw new Exception("Username missing."); } else if (StringUtils.isBlank(realm)) { throw new Exception("Realm missing."); } else if (uri == null) { throw new Exception("URI missing."); } else if (StringUtils.isBlank(response)) { throw new Exception("Response digest missing."); } String requestURI = request.getRequestURI(); // Allow empty URI to match "/" if (StringUtils.isEmpty(uri) && StringUtils.equals(requestURI, "/")) { requestURI = ""; } if (!StringUtils.equalsIgnoreCase(properties.getRealm(), realm)) { throw new Exception("Realm \"" + realm + "\" does not match expected realm \"" + properties.getRealm() + "\"."); } else if (!StringUtils.equalsIgnoreCase(requestURI, uri)) { throw new Exception( "URI \"" + uri + "\" does not match the request URI \"" + requestURI + "\"."); } else if (!StringUtils.equals(opaque, nonceOpaque)) { throw new Exception("Opaque value \"" + opaque + "\" does not match the expected value \"" + properties.getOpaque() + "\"."); } String password = properties.getCredentials().get(username); if (password == null) { throw new Exception("Credentials for username " + username + " not found."); } /* * Calculate H(A1). * * Algorithm MD5: A1 = username:realm:password * * Algorithm MD5-sess: A1 = H(username:realm:password):nonce:cnonce */ String ha1; if (algorithm == null || (StringUtils.equalsIgnoreCase(algorithm, Algorithm.MD5.toString()) && properties.getAlgorithms().contains(Algorithm.MD5))) { ha1 = digest(username, realm, password); } else if (StringUtils.equalsIgnoreCase(algorithm, Algorithm.MD5_SESS.toString()) && properties.getAlgorithms().contains(Algorithm.MD5_SESS)) { if (StringUtils.isBlank(clientNonceString)) { throw new Exception("Client nonce missing."); } String credentialsDigest = digest(username, realm, password); ha1 = digest(credentialsDigest, nonceString, clientNonceString); } else { throw new Exception("Algorithm \"" + algorithm + "\" not supported."); } /* * Calculate H(A2). * * QOP undefined/auth: A2 = method:uri * * QOP auth-int: A2 = method:uri:H(entityBody) */ String ha2; if (qop == null || (StringUtils.equalsIgnoreCase(qop, QOPMode.AUTH.toString()) && properties.getQopModes().contains(QOPMode.AUTH))) { ha2 = digest(request.getMethod(), uri); } else if (StringUtils.equalsIgnoreCase(qop, QOPMode.AUTH_INT.toString()) && properties.getQopModes().contains(QOPMode.AUTH_INT)) { String entityDigest = digest(request.getEntityProvider().getEntity()); ha2 = digest(request.getMethod(), uri, entityDigest); } else { throw new Exception("Quality of protection mode \"" + qop + "\" not supported."); } /* * Calculate response. * * QOP undefined: response = H(H(A1):nonce:H(A2)) * * QOP auth/auth-int: response = H(H(A1):nonce:nc:cnonce:qop:H(A2)) */ String rsp; if (qop == null) { rsp = digest(ha1, nonceString, ha2); } else { if (StringUtils.isBlank(nonceCountString)) { throw new Exception("Nonce count missing."); } else if (StringUtils.isBlank(clientNonceString)) { throw new Exception("Client nonce missing."); } rsp = digest(ha1, nonceString, nonceCountString, clientNonceString, qop, ha2); } if (logger.isTraceEnabled()) { logger.trace("H(A1): " + ha1); logger.trace("H(A2): " + ha2); logger.trace("response: " + rsp); } if (StringUtils.equalsIgnoreCase(rsp, response)) { /* * If the status is valid, return a successful result. Otherwise, the status * will remain stale and a challenge will be reissued. */ if (status == Status.VALID) { return AuthenticationResult.Success(username, realm); } } else { throw new Exception( "Response digest \"" + response + "\" does not match expected digest \"" + rsp + "\"."); } } catch (Exception e) { logger.debug("Error validating digest response.", e); status = Status.INVALID; } } /* * If we got to this point, an authentication challenge will be sent back, with a new nonce. * If the status is stale, the stale directive will also be set to true. */ Nonce nonce = new Nonce(properties.getOpaque()); nonceMap.put(nonce.getValue(), nonce); String contextPath = "/"; try { contextPath = new URI(request.getRequestURI()).getPath(); } catch (URISyntaxException e) { } Map<String, String> responseDirectives = new HashMap<String, String>(); responseDirectives.put(REALM, properties.getRealm()); responseDirectives.put(DOMAIN, contextPath); responseDirectives.put(NONCE, nonce.getValue()); responseDirectives.put(ALGORITHM, StringUtils.join(properties.getAlgorithms(), ',')); if (CollectionUtils.isNotEmpty(properties.getQopModes())) { responseDirectives.put(QOP, StringUtils.join(properties.getQopModes(), ',')); } if (StringUtils.isNotBlank(nonce.getOpaque())) { responseDirectives.put(OPAQUE, nonce.getOpaque()); } if (status == Status.STALE) { responseDirectives.put(STALE, "true"); } /* * Build up the WWW-Authenticate header to be sent back in the response. */ StringBuilder digestBuilder = new StringBuilder("Digest "); for (Iterator<Entry<String, String>> it = responseDirectives.entrySet().iterator(); it.hasNext();) { Entry<String, String> entry = it.next(); digestBuilder.append(entry.getKey()); digestBuilder.append("=\""); digestBuilder.append(entry.getValue()); digestBuilder.append('"'); if (it.hasNext()) { digestBuilder.append(", "); } } return AuthenticationResult.Challenged(digestBuilder.toString()); }
From source file:kenh.xscript.elements.Debug.java
private void list(JList c) { if (result == null) return;//from w w w . j a v a 2 s . com if (StringUtils.isBlank(c.getSelectedValue().toString())) return; if (this.getEnvironment() != null) { String context = ""; try { Object obj = this.getEnvironment().getVariable(c.getSelectedValue().toString()); if (obj != null) { context = c.getSelectedValue().toString() + LINE_SEP + LINE_SEP; context += "-- Class: " + obj.getClass().getCanonicalName() + LINE_SEP; context += LINE_SEP; context += "-- Fields: " + LINE_SEP; Field[] fields = obj.getClass().getFields(); for (Field field : fields) { int i = field.getModifiers(); String retval = Modifier.toString(i); if (StringUtils.contains(retval, "public")) { context += "\t" + field.getName() + " - " + retval + LINE_SEP; } } context += LINE_SEP; context += "-- Method: " + LINE_SEP; java.lang.reflect.Method[] methods = obj.getClass().getMethods(); for (java.lang.reflect.Method method : methods) { int i = method.getModifiers(); String retval = Modifier.toString(i); if (StringUtils.contains(retval, "public")) { Class[] pcs = method.getParameterTypes(); StringBuffer sb = new StringBuffer(); for (Class c_ : pcs) { String s = c_.getSimpleName(); sb.append(s + ", "); } String p = StringUtils.trimToEmpty(StringUtils.substringBeforeLast(sb.toString(), ",")); context += "\t" + method.getName() + "(" + p + ") - " + retval + LINE_SEP; } } } else { context = "<null>"; } } catch (Exception e) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); e.printStackTrace(pw); context = sw.toString(); } result.setText(context); } else { result.setText(c.getSelectedValue().toString()); } result.setCaretPosition(0); c.requestFocus(); }
From source file:alfio.manager.PaypalManager.java
private static String computeHMAC(CustomerName customerName, String email, String billingAddress, Event event) { return new HmacUtils(HmacAlgorithms.HMAC_SHA_256, event.getPrivateKey()) .hmacHex(StringUtils.trimToEmpty(customerName.getFullName()) + StringUtils.trimToEmpty(email) + StringUtils.trimToEmpty(billingAddress)); }
From source file:com.moviejukebox.tools.PropertiesUtil.java
/** * Convert the value to a Float/*www . j a v a 2 s . c om*/ * * @param key * @param valueToConvert * @param defaultValue * @return */ private static float convertFloatProperty(String valueToConvert, float defaultValue) { return NumberUtils.toFloat(StringUtils.trimToEmpty(valueToConvert), defaultValue); }
From source file:gov.ca.cwds.data.persistence.cms.BaseSubstituteCareProvider.java
/** * @return the lastName */ @Override public String getLastName() { return StringUtils.trimToEmpty(lastName); }
From source file:com.esri.geoportal.commons.http.BotsHttpClient.java
private PHP parsePHP(String host) { host = StringUtils.trimToEmpty(host); if (!host.isEmpty()) { // parse protocol String protocolPart = null; int protocolStopIdx = host.indexOf("://"); if (protocolStopIdx >= 0) { protocolPart = protocolStopIdx > 0 ? host.substring(0, protocolStopIdx) : null; host = host.substring(protocolStopIdx + "://".length()); }//ww w. j a v a 2 s . c o m // parse host:port String hostPart = null; Integer portPart = null; if (!host.isEmpty()) { int hostStopIdx = host.indexOf(":"); if (hostStopIdx < 0) { hostPart = host; } else { hostPart = hostStopIdx > 0 ? host.substring(0, hostStopIdx) : null; try { portPart = Integer.parseInt(host.substring(hostStopIdx + ":".length())); } catch (NumberFormatException ex) { } } } if (protocolPart != null || hostPart != null || portPart != null) { return new PHP(protocolPart, hostPart, portPart); } } return null; }
From source file:gov.ca.cwds.data.persistence.cms.BaseSubstituteCareProvider.java
/** * @return the lisOwnershipIndicator */ public String getLisOwnershipIndicator() { return StringUtils.trimToEmpty(lisOwnershipIndicator); }