Java Code Examples for org.apache.commons.lang3.StringUtils#strip()

The following examples show how to use org.apache.commons.lang3.StringUtils#strip() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@Test(expected = ConnectionException.class)
public void testSalesForcePasswordExpired() throws ConnectionException {
    SalesforceSourceOrSink salesforceSourceOrSink = new SalesforceSourceOrSink();
    TSalesforceInputProperties properties = (TSalesforceInputProperties) new TSalesforceInputProperties(null).init();
    salesforceSourceOrSink.initialize(null, properties);

    ConnectorConfig config = new ConnectorConfig();
    config.setUsername(StringUtils.strip(USER_ID_EXPIRED, "\""));
    String password = StringUtils.strip(PASSWORD_EXPIRED, "\"");
    String securityKey = StringUtils.strip(SECURITY_KEY_EXPIRED, "\"");
    if (StringUtils.isNotEmpty(securityKey)) {
        password = password + securityKey;
    }
    config.setPassword(password);

    PartnerConnection connection = null;
    try {
        connection = salesforceSourceOrSink.doConnection(config, true);
    } catch (LoginFault ex) {
        Assert.fail("Must be an exception related to expired password, not the Login Fault.");
    } finally {
        if (null != connection) {
            connection.logout();
        }
    }
}
 
Example 2
Source Project: SciGraph   File: VocabularyNeo4jImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Optional<Concept> getConceptFromId(Query query) {
  String idQuery = StringUtils.strip(query.getInput(), "\"");
  idQuery = curieUtil.getIri(idQuery).orElse(idQuery);
  try (Transaction tx = graph.beginTx()) {
    Node node =
        graph.index().getNodeAutoIndexer().getAutoIndex().get(CommonProperties.IRI, idQuery)
            .getSingle();
    tx.success();
    Concept concept = null;
    if (null != node) {
      concept = transformer.apply(node);
    }
    return Optional.ofNullable(concept);
  }
}
 
Example 3
public static TextFeatsCfg fromConfigString(String str) throws IllegalAccessException, InvocationTargetException, NullValueException {
		if (StringUtils.isEmpty(str)) {
			throw new NullValueException("String cannot be empty!");
		}
		
		TextFeatsCfg cfg = new TextFeatsCfg();
		String[] keyValuePairs = str.replace(CONFIG_STR_PREFIX, "").replaceAll("[{}]", "").split("; ");
		for (String keyValuePair : keyValuePairs) {
//			logger.debug("keyValuePair = "+keyValuePair);
			String splits[] = keyValuePair.split("=");
			if (splits.length==2) {
				String key = splits[0].trim();
				String value = splits[1].trim();
				value = StringUtils.strip(value, "\"'");
//				logger.debug("key = "+key+", value = "+value);
				BeanUtils.setProperty(cfg, key, value);
			}
			else {
				logger.warn("Ignoring invalid key/value pair: "+keyValuePair);
			}
		}

		return cfg;
	}
 
Example 4
/**
 * Extracts the text found in a specific page bound to a specific rectangle area Eg: extract footer text from a certain page
 * 
 * @param page
 *            the page to extract the text from
 * @param area
 *            the rectangular area to extract
 * @return the extracted text
 * @throws TaskIOException
 */
public String extractTextFromArea(PDPage page, Rectangle2D area) throws TaskIOException {
    try {
        PDFTextStripperByArea stripper = new PDFTextStripperByArea();

        stripper.setSortByPosition(true);
        stripper.addRegion("area1", area);
        stripper.extractRegions(page);

        String result = stripper.getTextForRegion("area1");
        result = defaultIfBlank(result, "");
        result = StringUtils.strip(result);
        result = org.sejda.commons.util.StringUtils.normalizeWhitespace(result).trim();
        return result;
    } catch (IOException e) {
        throw new TaskIOException("An error occurred extracting text from page.", e);
    }
}
 
Example 5
Source Project: tcases   File: SystemInputDocReader.java    License: MIT License 5 votes vote down vote up
/**
 * Converts the given attribute value to a set of property names.
 */
public Set<String> toProperties( Attributes attributes, String attributeName) throws SAXParseException
  {
  Set<String> propertySet = null;

  String propertyList = StringUtils.strip( getAttribute( attributes, attributeName));
  String[] properties = propertyList==null? null : propertyList.split( ",");
  if( properties != null && properties.length > 0)
    {
    propertySet = new HashSet<String>();
    for( int i = 0; i < properties.length; i++)
      {
      String propertyName = StringUtils.trimToNull( properties[i]);
      if( propertyName != null)
        {
        propertySet.add( propertyName);
        }
      }

    try
      {
      assertPropertyIdentifiers( propertySet);
      }
    catch( Exception e)
      {
      throw new SAXParseException( "Invalid \"" + attributeName + "\" attribute: " + e.getMessage(), getDocumentLocator()); 
      }
    }
  
  return propertySet;
  }
 
Example 6
Source Project: app-engine   File: DefaultProfileLoader.java    License: Apache License 2.0 5 votes vote down vote up
private Optional<String> readFromProperties() {
    String env = null;
    try {
        env = PropertiesLoaderUtils.loadAllProperties("application.properties").getProperty("profile");
        env = StringUtils.strip(env);
    } catch (IOException e) {
        LOGGER.error(e.getMessage());
    }
    return Optional.ofNullable(env);
}
 
Example 7
public static String formatAccountAge(long durationMillis) {
    durationMillis = Math.max(0, durationMillis);
    String day = Res.get("time.day").toLowerCase();
    String days = Res.get("time.days");
    String format = " d\' " + days + "\'";
    return StringUtils.strip(StringUtils.replaceOnce(DurationFormatUtils.formatDuration(durationMillis, format), " 1 " + days, " 1 " + day));
}
 
Example 8
private String readString(DataInputStream dis, int length, String charset) throws IOException {
    byte [] bytes = new byte[length];
    dis.readFully(bytes, 0, length);

    // Remove spaces at start and end of the string
    return StringUtils.strip(new String(bytes, charset));
}
 
Example 9
Source Project: kylin   File: BeelineHiveClient.java    License: Apache License 2.0 5 votes vote down vote up
private String stripQuotes(String input) {
    if (input.startsWith("'") && input.endsWith("'")) {
        return StringUtils.strip(input, "'");
    } else if (input.startsWith("\"") && input.endsWith("\"")) {
        return StringUtils.strip(input, "\"");
    } else {
        return input;
    }
}
 
Example 10
/**
 * Creates a internal molgenis id from a vcf entity
 *
 * @return the id
 */
public static String createId(Entity vcfEntity) {
  String idStr =
      StringUtils.strip(vcfEntity.get(CHROM).toString())
          + "_"
          + StringUtils.strip(vcfEntity.get(POS).toString())
          + "_"
          + StringUtils.strip(vcfEntity.get(REF).toString())
          + "_"
          + StringUtils.strip(vcfEntity.get(ALT).toString())
          + "_"
          + StringUtils.strip(vcfEntity.get(ID).toString())
          + "_"
          + StringUtils.strip(vcfEntity.get(QUAL) != null ? vcfEntity.get(QUAL).toString() : "")
          + "_"
          + StringUtils.strip(
              vcfEntity.get(FILTER) != null ? vcfEntity.get(FILTER).toString() : "");

  // use MD5 hash to prevent ids that are too long
  MessageDigest messageDigest;
  try {
    messageDigest = MessageDigest.getInstance("MD5");
  } catch (NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
  }
  byte[] md5Hash = messageDigest.digest(idStr.getBytes(UTF_8));

  // convert MD5 hash to string ids that can be safely used in URLs
  return Base64.getUrlEncoder().withoutPadding().encodeToString(md5Hash);
}
 
Example 11
protected String getScriptUrlForContentType(String contentType) {
    Matcher contentTypeMatcher = contentTypePattern.matcher(contentType);
    if (contentTypeMatcher.matches()) {
        String contentTypeName = contentTypeMatcher.group(1);
        contentTypeName = StringUtils.strip(contentTypeName, "/");

        return String.format(scriptUrlFormat, contentTypeName);
    } else {
        return null;
    }
}
 
Example 12
/**
 * Strips unneeded spaces.
 */
private Set<String> getFormattedAliases(Properties aliasProperties, String propertyKey) {
    Set<String> formattedAliases = new HashSet<String>();
    if (aliasProperties.containsKey(propertyKey)) {
        String aliasList = aliasProperties.getProperty(propertyKey);
        String[] aliases = StringUtils.split(aliasList, ",");
        for (String alias : aliases) {
            String formattedAlias = StringUtils.strip(alias);
            formattedAliases.add(formattedAlias);
        }
    }
    return formattedAliases;
}
 
Example 13
Source Project: swagger2markup   File: IOUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a normalized name from an arbitrary string.<br>
 * Paths separators are replaced, so this function can't be applied on a whole path, but must be called on each path sections.
 *
 * @param name current name of the file
 * @return a normalized filename
 */
public static String normalizeName(String name) {
    String fileName = NAME_FORBIDDEN_PATTERN.matcher(name).replaceAll("_");
    fileName = fileName.replaceAll(String.format("([%1$s])([%1$s]+)", "-_"), "$1");
    fileName = StringUtils.strip(fileName, "_-");
    fileName = fileName.trim();
    return fileName;
}
 
Example 14
private List<String> classesToFilteredList(
    Set<?> components,
    String componentPackage,
    List<Class<?>> excludeClass,
    List<String> excludePackage) {
  List<String> ret = new ArrayList<>();
  for (Object o : components) {

    try {
      Class<?> c = (Class<?>) o;

      String s = c.getName();
      String p = c.getPackage().getName();

      if (excludeByPackage(p, excludePackage)
          || excludeByClass(c, excludeClass)
          || isAbstract(c)) {
        continue;
      }

      if (s.startsWith(componentPackage)) {
        s = s.substring(componentPackage.length());
        s = StringUtils.strip(s, ".");
      }

      ret.add(s);
    } catch (ClassCastException cce) {
      LoggerFactory.getLogger(clazz).warn("Unable to cast to class", cce);
    }
  }

  Collections.sort(ret);

  return ret;
}
 
Example 15
private String prepareContext(String profile) {
    profile = StringUtils.substringBeforeLast(profile, "#");
    return StringUtils.strip(profile, "\"");
}
 
Example 16
public void setFormat(String format) {
//		this.format = format;
		this.format = StringUtils.strip(format, "\"'");
	}
 
Example 17
public void setType(String type) {
//		this.type = type;
		this.type = StringUtils.strip(type, "\"'");
	}
 
Example 18
/**
 * Returns the line from the given file, stripped from whitespace
 * 
 * @param file
 * @param line
 * @return
 * @throws IOException
 */
protected String getStrippedContentFromFile(File file, int line) throws IOException {
	String result;
	try (Stream<String> lines = Files.lines(Paths.get(file.getAbsolutePath()))) {
		result = lines.skip(line - 1).findFirst().get();
	}
	return StringUtils.strip(result);
}
 
Example 19
Source Project: warnings-ng-plugin   File: SummaryBox.java    License: MIT License 2 votes vote down vote up
/**
 * Returns the title of the summary as plain text.
 * 
 * @return the title
 */
public String getTitle() {
    return StringUtils.strip(Objects.requireNonNull(title).getTextContent());
}
 
Example 20
Source Project: baleen   File: SharedFileResource.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Read an entire file into a string, ignoring any leading or trailing whitespace.
 *
 * @param file to load
 * @return the content of the file as a string.
 * @throws IOException on error reading or accessing the file.
 */
public static String readFile(File file) throws IOException {
  String contents = FileUtils.file2String(file);
  contents = contents.replaceAll("\r\n", "\n");
  return StringUtils.strip(contents);
}