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

The following examples show how to use org.apache.commons.lang3.StringUtils#strip() . 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
Source File: SalesforceSourceOrSinkTestIT.java    From components with Apache License 2.0 6 votes vote down vote up
@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 File: PdfTextExtractorByArea.java    From sejda with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 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 3
Source File: VocabularyNeo4jImpl.java    From SciGraph with 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 4
Source File: TextFeatsCfg.java    From TranskribusCore with GNU General Public License v3.0 6 votes vote down vote up
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 5
Source File: VcfUtils.java    From molgenis with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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 6
Source File: AbstractComponentApiServlet.java    From baleen with Apache License 2.0 5 votes vote down vote up
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 7
Source File: IOUtils.java    From swagger2markup with 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 8
Source File: AliasLoader.java    From livingdoc-core with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 9
Source File: SiteItemScriptResolverImpl.java    From engine with GNU General Public License v3.0 5 votes vote down vote up
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 10
Source File: SystemInputDocReader.java    From tcases with 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 11
Source File: BeelineHiveClient.java    From kylin with 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 12
Source File: StlParser.java    From subtitle with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 13
Source File: DisplayUtils.java    From bisq with GNU Affero General Public License v3.0 5 votes vote down vote up
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 14
Source File: DefaultProfileLoader.java    From app-engine with 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 15
Source File: AbstractMessageConverter.java    From elucidate-server with MIT License 4 votes vote down vote up
private String prepareContext(String profile) {
    profile = StringUtils.substringBeforeLast(profile, "#");
    return StringUtils.strip(profile, "\"");
}
 
Example 16
Source File: TextFeatsCfg.java    From TranskribusCore with GNU General Public License v3.0 4 votes vote down vote up
public void setFormat(String format) {
//		this.format = format;
		this.format = StringUtils.strip(format, "\"'");
	}
 
Example 17
Source File: TextFeatsCfg.java    From TranskribusCore with GNU General Public License v3.0 4 votes vote down vote up
public void setType(String type) {
//		this.type = type;
		this.type = StringUtils.strip(type, "\"'");
	}
 
Example 18
Source File: AbstractRefactoringTests.java    From Refactoring-Bot with MIT License 3 votes vote down vote up
/**
 * 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 File: SummaryBox.java    From warnings-ng-plugin with 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 File: SharedFileResource.java    From baleen with 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);
}