List of usage examples for org.apache.commons.lang3 StringUtils startsWith
public static boolean startsWith(final CharSequence str, final CharSequence prefix)
Check if a CharSequence starts with a specified prefix.
null s are handled without exceptions.
From source file:com.erudika.para.utils.Utils.java
/** * Checks if a response is of type JSON. * @param contentType the value of "Content-Type" header * @return true if JSON/*from ww w .j a va 2s . c om*/ */ public static boolean isJsonType(String contentType) { return StringUtils.startsWith(contentType, "application/json") || StringUtils.startsWith(contentType, "application/javascript") || StringUtils.startsWith(contentType, "text/javascript"); // F U facebook! }
From source file:info.financialecology.finance.utilities.datastruct.VersatileDataTable.java
/** * Multiplies the values of a given subset of the variables in the * table with a factor./*from w w w. ja v a 2 s . co m*/ * <p> * String labels passed as arguments are used * to match the column keys that identify which variables are to be * multiplied. E.g. the label <code>price</code> matches the column * keys <code>price_1</code> and <code>price_2</code>. * @param multipler factor with which to multiple the selected columns * @param labels a set of filters to match column keys against */ public void columnMultiply(double multipler, String... labels) { List<String> columnKeys = getColumnKeys(); List<String> rowKeys = getRowKeys(); for (String label : labels) { for (String columnKey : columnKeys) { if (isSubsetOf(columnKey, label)) { for (String rowKey : rowKeys) { if (!StringUtils.startsWith(rowKey, "#")) { // exclude calculated elements of the table, e.g. column average double value = getValue(rowKey, columnKey).doubleValue(); setValue(value * multipler, rowKey, columnKey); } } } } } }
From source file:info.financialecology.finance.utilities.datastruct.VersatileDataTable.java
/** * Computes the column-wise average of values whose column key matches * any of the labels passed as arguments. The result is appended * to the bottom of the table and prefixed with a '#' symbol * to prevent methods such as {@link #columnMultiply(double, String...)} * to operate on them./*ww w . j a v a 2 s. c om*/ * @param rowLabel the name of the result as it should appear in the * leftmost row * @param labels a set of filters to match column keys against */ public void insertColumnAverage(String rowLabel, String... labels) { List<String> columnKeys = getColumnKeys(); List<String> rowKeys = getRowKeys(); rowLabel = "# " + rowLabel; for (String label : labels) { for (String columnKey : columnKeys) { double avg = 0, count = 0; if (isSubsetOf(columnKey, label)) { for (String rowKey : rowKeys) { if (!StringUtils.startsWith(rowKey, "#")) { avg += getValue(rowKey, columnKey).doubleValue(); count++; } } } if (count > 0) { avg = avg / count; setValue(avg, rowLabel, columnKey); } } } }
From source file:info.financialecology.finance.utilities.datastruct.VersatileDataTable.java
/** * Computes the column-wise standard deviation of values whose column * key matches any of the labels passed as arguments. The result is * appended to the bottom of the table and prefixed with a '#' symbol * to prevent methods such as {@link #columnMultiply(double, String...)} * to operate on them./*from ww w. j a va 2s . com*/ * @param rowLabel the name of the result as it should appear in the * leftmost row * @param labels a set of filters to match column keys against */ public void insertColumnStdev(String rowLabel, String... labels) { DescriptiveStatistics stats = new DescriptiveStatistics(); List<String> columnKeys = getColumnKeys(); List<String> rowKeys = getRowKeys(); rowLabel = "# " + rowLabel; for (String label : labels) { for (String columnKey : columnKeys) { if (isSubsetOf(columnKey, label)) { for (String rowKey : rowKeys) { if (!StringUtils.startsWith(rowKey, "#")) { stats.addValue(getValue(rowKey, columnKey).doubleValue()); } } } setValue(stats.getStandardDeviation(), rowLabel, columnKey); stats.clear(); } } }
From source file:br.com.autonomiccs.cloudTraces.main.CloudTracesSimulator.java
private static Collection<VirtualMachine> getAllVirtualMachinesFromCloudTraces( String cloudTraceFullQualifiedFilePath) { Map<String, VirtualMachine> poolOfVirtualMachines = new HashMap<>(); try (BufferedReader bf = new BufferedReader(new FileReader(cloudTraceFullQualifiedFilePath))) { String line = bf.readLine(); while (line != null) { if (StringUtils.trim(line).isEmpty() || StringUtils.startsWith(line, "#")) { line = bf.readLine();/*from w w w.java2 s. c o m*/ continue; } Matcher matcher = patternMatchVmsData.matcher(line); if (!matcher.matches()) { throw new GoogleTracesToCloudTracesException( String.format("String [%s] does not meet the expected pattern.", line)); } int time = Integer.parseInt(matcher.group(1)); String vmId = matcher.group(2); VirtualMachine virtualMachine = poolOfVirtualMachines.get(vmId); if (virtualMachine == null) { virtualMachine = createVirtualMachine(matcher); poolOfVirtualMachines.put(vmId, virtualMachine); } loadTaskForTime(matcher, time, virtualMachine); line = bf.readLine(); } } catch (IOException e) { throw new GoogleTracesToCloudTracesException(e); } return poolOfVirtualMachines.values(); }
From source file:com.ottogroup.bi.spqr.pipeline.MicroPipelineFactory.java
/** * Instantiates, initializes and returns the {@link DelayedResponseOperatorWaitStrategy} configured for the {@link DelayedResponseOperator} * whose {@link MicroPipelineComponentConfiguration configuration} is provided when calling this method. * @param delayedResponseOperatorCfg/*from w w w.j a v a 2 s . com*/ * @return */ protected DelayedResponseOperatorWaitStrategy getResponseWaitStrategy( final MicroPipelineComponentConfiguration delayedResponseOperatorCfg) throws RequiredInputMissingException, UnknownWaitStrategyException { ///////////////////////////////////////////////////////////////////////////////////// // validate input if (delayedResponseOperatorCfg == null) throw new RequiredInputMissingException("Missing required delayed response operator configuration"); if (delayedResponseOperatorCfg.getSettings() == null) throw new RequiredInputMissingException("Missing required delayed response operator settings"); String strategyName = StringUtils.lowerCase(StringUtils.trim(delayedResponseOperatorCfg.getSettings() .getProperty(DelayedResponseOperator.CFG_WAIT_STRATEGY_NAME))); if (StringUtils.isBlank(strategyName)) throw new RequiredInputMissingException( "Missing required strategy name expected as part of operator settings ('" + DelayedResponseOperator.CFG_WAIT_STRATEGY_NAME + "')"); // ///////////////////////////////////////////////////////////////////////////////////// if (logger.isDebugEnabled()) logger.debug("Settings provided for strategy '" + strategyName + "'"); Properties strategyProperties = new Properties(); for (Enumeration<Object> keyEnumerator = delayedResponseOperatorCfg.getSettings().keys(); keyEnumerator .hasMoreElements();) { String key = (String) keyEnumerator.nextElement(); if (StringUtils.startsWith(key, DelayedResponseOperator.CFG_WAIT_STRATEGY_SETTINGS_PREFIX)) { String waitStrategyCfgKey = StringUtils.substring(key, StringUtils.lastIndexOf(key, ".") + 1); if (StringUtils.isNoneBlank(waitStrategyCfgKey)) { String waitStrategyCfgValue = delayedResponseOperatorCfg.getSettings().getProperty(key); strategyProperties.put(waitStrategyCfgKey, waitStrategyCfgValue); if (logger.isDebugEnabled()) logger.debug("\t" + waitStrategyCfgKey + ": " + waitStrategyCfgValue); } } } if (StringUtils.equalsIgnoreCase(strategyName, MessageCountResponseWaitStrategy.WAIT_STRATEGY_NAME)) { MessageCountResponseWaitStrategy strategy = new MessageCountResponseWaitStrategy(); strategy.initialize(strategyProperties); return strategy; } else if (StringUtils.equalsIgnoreCase(strategyName, TimerBasedResponseWaitStrategy.WAIT_STRATEGY_NAME)) { TimerBasedResponseWaitStrategy strategy = new TimerBasedResponseWaitStrategy(); strategy.initialize(strategyProperties); return strategy; } else if (StringUtils.equalsIgnoreCase(strategyName, OperatorTriggeredWaitStrategy.WAIT_STRATEGY_NAME)) { OperatorTriggeredWaitStrategy strategy = new OperatorTriggeredWaitStrategy(); strategy.initialize(strategyProperties); return strategy; } throw new UnknownWaitStrategyException("Unknown wait strategy '" + strategyName + "'"); }
From source file:cgeo.geocaching.connector.gc.GCParser.java
static SearchResult parseCacheFromText(final String pageIn, final CancellableHandler handler) { CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_details); if (StringUtils.isBlank(pageIn)) { Log.e("GCParser.parseCache: No page given"); return null; }/*from www .j a v a 2s . com*/ final SearchResult searchResult = new SearchResult(); if (pageIn.contains(GCConstants.STRING_UNPUBLISHED_OTHER) || pageIn.contains(GCConstants.STRING_UNPUBLISHED_FROM_SEARCH)) { searchResult.setError(StatusCode.UNPUBLISHED_CACHE); return searchResult; } if (pageIn.contains(GCConstants.STRING_PREMIUMONLY_1) || pageIn.contains(GCConstants.STRING_PREMIUMONLY_2)) { searchResult.setError(StatusCode.PREMIUM_ONLY); return searchResult; } final String cacheName = Html.fromHtml(TextUtils.getMatch(pageIn, GCConstants.PATTERN_NAME, true, "")) .toString(); if (GCConstants.STRING_UNKNOWN_ERROR.equalsIgnoreCase(cacheName)) { searchResult.setError(StatusCode.UNKNOWN_ERROR); return searchResult; } // first handle the content with line breaks, then trim everything for easier matching and reduced memory consumption in parsed fields String personalNoteWithLineBreaks = ""; MatcherWrapper matcher = new MatcherWrapper(GCConstants.PATTERN_PERSONALNOTE, pageIn); if (matcher.find()) { personalNoteWithLineBreaks = matcher.group(1).trim(); } final String page = TextUtils.replaceWhitespace(pageIn); final Geocache cache = new Geocache(); cache.setDisabled(page.contains(GCConstants.STRING_DISABLED)); cache.setArchived(page.contains(GCConstants.STRING_ARCHIVED)); cache.setPremiumMembersOnly(TextUtils.matches(page, GCConstants.PATTERN_PREMIUMMEMBERS)); cache.setFavorite(TextUtils.matches(page, GCConstants.PATTERN_FAVORITE)); // cache geocode cache.setGeocode(TextUtils.getMatch(page, GCConstants.PATTERN_GEOCODE, true, cache.getGeocode())); // cache id cache.setCacheId(TextUtils.getMatch(page, GCConstants.PATTERN_CACHEID, true, cache.getCacheId())); // cache guid cache.setGuid(TextUtils.getMatch(page, GCConstants.PATTERN_GUID, true, cache.getGuid())); // name cache.setName(cacheName); // owner real name cache.setOwnerUserId(Network .decode(TextUtils.getMatch(page, GCConstants.PATTERN_OWNER_USERID, true, cache.getOwnerUserId()))); cache.setUserModifiedCoords(false); String tableInside = page; final int pos = tableInside.indexOf(GCConstants.STRING_CACHEDETAILS); if (pos == -1) { Log.e("GCParser.parseCache: ID \"cacheDetails\" not found on page"); return null; } tableInside = tableInside.substring(pos); if (StringUtils.isNotBlank(tableInside)) { // cache terrain String result = TextUtils.getMatch(tableInside, GCConstants.PATTERN_TERRAIN, true, null); if (result != null) { try { cache.setTerrain(Float.parseFloat(StringUtils.replaceChars(result, '_', '.'))); } catch (final NumberFormatException e) { Log.e("Error parsing terrain value", e); } } // cache difficulty result = TextUtils.getMatch(tableInside, GCConstants.PATTERN_DIFFICULTY, true, null); if (result != null) { try { cache.setDifficulty(Float.parseFloat(StringUtils.replaceChars(result, '_', '.'))); } catch (final NumberFormatException e) { Log.e("Error parsing difficulty value", e); } } // owner cache.setOwnerDisplayName(StringEscapeUtils.unescapeHtml4(TextUtils.getMatch(tableInside, GCConstants.PATTERN_OWNER_DISPLAYNAME, true, cache.getOwnerDisplayName()))); // hidden try { String hiddenString = TextUtils.getMatch(tableInside, GCConstants.PATTERN_HIDDEN, true, null); if (StringUtils.isNotBlank(hiddenString)) { cache.setHidden(GCLogin.parseGcCustomDate(hiddenString)); } if (cache.getHiddenDate() == null) { // event date hiddenString = TextUtils.getMatch(tableInside, GCConstants.PATTERN_HIDDENEVENT, true, null); if (StringUtils.isNotBlank(hiddenString)) { cache.setHidden(GCLogin.parseGcCustomDate(hiddenString)); } } } catch (final ParseException e) { // failed to parse cache hidden date Log.w("GCParser.parseCache: Failed to parse cache hidden (event) date"); } // favorite try { cache.setFavoritePoints(Integer .parseInt(TextUtils.getMatch(tableInside, GCConstants.PATTERN_FAVORITECOUNT, true, "0"))); } catch (final NumberFormatException e) { Log.e("Error parsing favorite count", e); } // cache size cache.setSize(CacheSize.getById( TextUtils.getMatch(tableInside, GCConstants.PATTERN_SIZE, true, CacheSize.NOT_CHOSEN.id))); } // cache found cache.setFound(TextUtils.matches(page, GCConstants.PATTERN_FOUND) || TextUtils.matches(page, GCConstants.PATTERN_FOUND_ALTERNATIVE)); // cache found date try { final String foundDateString = TextUtils.getMatch(page, GCConstants.PATTERN_FOUND_DATE, true, null); if (StringUtils.isNotBlank(foundDateString)) { cache.setVisitedDate(GCLogin.parseGcCustomDate(foundDateString).getTime()); } } catch (final ParseException e) { // failed to parse cache found date Log.w("GCParser.parseCache: Failed to parse cache found date"); } // cache type cache.setType(CacheType .getByPattern(TextUtils.getMatch(page, GCConstants.PATTERN_TYPE, true, cache.getType().id))); // on watchlist cache.setOnWatchlist(TextUtils.matches(page, GCConstants.PATTERN_WATCHLIST)); // latitude and longitude. Can only be retrieved if user is logged in String latlon = TextUtils.getMatch(page, GCConstants.PATTERN_LATLON, true, ""); if (StringUtils.isNotEmpty(latlon)) { try { cache.setCoords(new Geopoint(latlon)); cache.setReliableLatLon(true); } catch (final Geopoint.GeopointException e) { Log.w("GCParser.parseCache: Failed to parse cache coordinates", e); } } // cache location cache.setLocation(TextUtils.getMatch(page, GCConstants.PATTERN_LOCATION, true, "")); // cache hint final String result = TextUtils.getMatch(page, GCConstants.PATTERN_HINT, false, null); if (result != null) { // replace linebreak and paragraph tags final String hint = GCConstants.PATTERN_LINEBREAK.matcher(result).replaceAll("\n"); cache.setHint(StringUtils.replace(hint, "</p>", "").trim()); } cache.checkFields(); // cache personal note cache.setPersonalNote(personalNoteWithLineBreaks); // cache short description cache.setShortDescription(TextUtils.getMatch(page, GCConstants.PATTERN_SHORTDESC, true, "")); // cache description cache.setDescription(TextUtils.getMatch(page, GCConstants.PATTERN_DESC, true, "")); // cache attributes try { final String attributesPre = TextUtils.getMatch(page, GCConstants.PATTERN_ATTRIBUTES, true, null); if (null != attributesPre) { final MatcherWrapper matcherAttributesInside = new MatcherWrapper( GCConstants.PATTERN_ATTRIBUTESINSIDE, attributesPre); final ArrayList<String> attributes = new ArrayList<String>(); while (matcherAttributesInside.find()) { if (matcherAttributesInside.groupCount() > 1 && !matcherAttributesInside.group(2).equalsIgnoreCase("blank")) { // by default, use the tooltip of the attribute String attribute = matcherAttributesInside.group(2).toLowerCase(Locale.US); // if the image name can be recognized, use the image name as attribute final String imageName = matcherAttributesInside.group(1).trim(); if (StringUtils.isNotEmpty(imageName)) { final int start = imageName.lastIndexOf('/'); final int end = imageName.lastIndexOf('.'); if (start >= 0 && end >= 0) { attribute = imageName.substring(start + 1, end).replace('-', '_') .toLowerCase(Locale.US); } } attributes.add(attribute); } } cache.setAttributes(attributes); } } catch (final RuntimeException e) { // failed to parse cache attributes Log.w("GCParser.parseCache: Failed to parse cache attributes"); } // cache spoilers try { if (CancellableHandler.isCancelled(handler)) { return null; } CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_spoilers); final MatcherWrapper matcherSpoilersInside = new MatcherWrapper(GCConstants.PATTERN_SPOILER_IMAGE, page); while (matcherSpoilersInside.find()) { // the original spoiler URL (include .../display/... contains a low-resolution image // if we shorten the URL we get the original-resolution image final String url = matcherSpoilersInside.group(1).replace("/display", ""); String title = null; if (matcherSpoilersInside.group(3) != null) { title = matcherSpoilersInside.group(3); } String description = null; if (matcherSpoilersInside.group(4) != null) { description = matcherSpoilersInside.group(4); } cache.addSpoiler(new Image(url, title, description)); } } catch (final RuntimeException e) { // failed to parse cache spoilers Log.w("GCParser.parseCache: Failed to parse cache spoilers"); } // cache inventory try { cache.setInventoryItems(0); final MatcherWrapper matcherInventory = new MatcherWrapper(GCConstants.PATTERN_INVENTORY, page); if (matcherInventory.find()) { if (cache.getInventory() == null) { cache.setInventory(new ArrayList<Trackable>()); } if (matcherInventory.groupCount() > 1) { final String inventoryPre = matcherInventory.group(2); if (StringUtils.isNotBlank(inventoryPre)) { final MatcherWrapper matcherInventoryInside = new MatcherWrapper( GCConstants.PATTERN_INVENTORYINSIDE, inventoryPre); while (matcherInventoryInside.find()) { if (matcherInventoryInside.groupCount() > 0) { final Trackable inventoryItem = new Trackable(); inventoryItem.setGuid(matcherInventoryInside.group(1)); inventoryItem.setName(matcherInventoryInside.group(2)); cache.getInventory().add(inventoryItem); cache.setInventoryItems(cache.getInventoryItems() + 1); } } } } } } catch (final RuntimeException e) { // failed to parse cache inventory Log.w("GCParser.parseCache: Failed to parse cache inventory (2)"); } // cache logs counts try { final String countlogs = TextUtils.getMatch(page, GCConstants.PATTERN_COUNTLOGS, true, null); if (null != countlogs) { final MatcherWrapper matcherLog = new MatcherWrapper(GCConstants.PATTERN_COUNTLOG, countlogs); while (matcherLog.find()) { final String typeStr = matcherLog.group(1); final String countStr = getNumberString(matcherLog.group(2)); if (StringUtils.isNotBlank(typeStr) && LogType.UNKNOWN != LogType.getByIconName(typeStr) && StringUtils.isNotBlank(countStr)) { cache.getLogCounts().put(LogType.getByIconName(typeStr), Integer.parseInt(countStr)); } } } } catch (final NumberFormatException e) { // failed to parse logs Log.w("GCParser.parseCache: Failed to parse cache log count"); } // waypoints - reset collection cache.setWaypoints(Collections.<Waypoint>emptyList(), false); // add waypoint for original coordinates in case of user-modified listing-coordinates try { final String originalCoords = TextUtils.getMatch(page, GCConstants.PATTERN_LATLON_ORIG, false, null); if (null != originalCoords) { final Waypoint waypoint = new Waypoint( CgeoApplication.getInstance().getString(R.string.cache_coordinates_original), WaypointType.ORIGINAL, false); waypoint.setCoords(new Geopoint(originalCoords)); cache.addOrChangeWaypoint(waypoint, false); cache.setUserModifiedCoords(true); } } catch (final Geopoint.GeopointException e) { } int wpBegin = page.indexOf("<table class=\"Table\" id=\"ctl00_ContentBody_Waypoints\">"); if (wpBegin != -1) { // parse waypoints if (CancellableHandler.isCancelled(handler)) { return null; } CancellableHandler.sendLoadProgressDetail(handler, R.string.cache_dialog_loading_details_status_waypoints); String wpList = page.substring(wpBegin); int wpEnd = wpList.indexOf("</p>"); if (wpEnd > -1 && wpEnd <= wpList.length()) { wpList = wpList.substring(0, wpEnd); } if (!wpList.contains("No additional waypoints to display.")) { wpEnd = wpList.indexOf("</table>"); wpList = wpList.substring(0, wpEnd); wpBegin = wpList.indexOf("<tbody>"); wpEnd = wpList.indexOf("</tbody>"); if (wpBegin >= 0 && wpEnd >= 0 && wpEnd <= wpList.length()) { wpList = wpList.substring(wpBegin + 7, wpEnd); } final String[] wpItems = wpList.split("<tr"); for (int j = 1; j < wpItems.length; j++) { String[] wp = wpItems[j].split("<td"); // waypoint name // res is null during the unit tests final String name = TextUtils.getMatch(wp[6], GCConstants.PATTERN_WPNAME, true, 1, CgeoApplication.getInstance().getString(R.string.waypoint), true); // waypoint type final String resulttype = TextUtils.getMatch(wp[3], GCConstants.PATTERN_WPTYPE, null); final Waypoint waypoint = new Waypoint(name, WaypointType.findById(resulttype), false); // waypoint prefix waypoint.setPrefix(TextUtils.getMatch(wp[4], GCConstants.PATTERN_WPPREFIXORLOOKUPORLATLON, true, 2, waypoint.getPrefix(), false)); // waypoint lookup waypoint.setLookup(TextUtils.getMatch(wp[5], GCConstants.PATTERN_WPPREFIXORLOOKUPORLATLON, true, 2, waypoint.getLookup(), false)); // waypoint latitude and longitude latlon = Html.fromHtml(TextUtils.getMatch(wp[7], GCConstants.PATTERN_WPPREFIXORLOOKUPORLATLON, false, 2, "", false)).toString().trim(); if (!StringUtils.startsWith(latlon, "???")) { waypoint.setLatlon(latlon); waypoint.setCoords(new Geopoint(latlon)); } j++; if (wpItems.length > j) { wp = wpItems[j].split("<td"); } // waypoint note waypoint.setNote(TextUtils.getMatch(wp[3], GCConstants.PATTERN_WPNOTE, waypoint.getNote())); cache.addOrChangeWaypoint(waypoint, false); } } } cache.parseWaypointsFromNote(); // logs cache.setLogs(getLogsFromDetails(page, false)); // last check for necessary cache conditions if (StringUtils.isBlank(cache.getGeocode())) { searchResult.setError(StatusCode.UNKNOWN_ERROR); return searchResult; } cache.setDetailedUpdatedNow(); searchResult.addAndPutInCache(Collections.singletonList(cache)); return searchResult; }
From source file:com.opensymphony.xwork2.util.finder.ResourceFinder.java
private static void readJarDirectoryEntries(URL location, String basePath, Set<String> resources) throws IOException { JarURLConnection conn = (JarURLConnection) location.openConnection(); JarFile jarfile = null;//from w w w. j av a 2s . c o m jarfile = conn.getJarFile(); Enumeration<JarEntry> entries = jarfile.entries(); while (entries != null && entries.hasMoreElements()) { JarEntry entry = entries.nextElement(); String name = entry.getName(); if (entry.isDirectory() && StringUtils.startsWith(name, basePath)) { resources.add(name); } } }
From source file:com.joyent.manta.http.MantaHttpHeaders.java
/** * Translates the range request header into two values. The first value * is the starting bytes of the binary file to read and the second value * is the ending bytes of the file to read. If the range indicates the * end of a file (unlimited), then the end value will be set to null. * Likewise, if the start position is unknown, it will be set to null. * * This method may eventually be deprecated in favor of {@link HttpRange#parseRequestRange(String)} but * that refactoring is being deferred./*from www .j av a2 s . co m*/ * * @return two value array containing the start and the end of a byte range as Long * * @see HttpRange#parseRequestRange(String) */ public Long[] getByteRange() { final String rangeString = getRange(); Validate.notNull(rangeString, "Range value must not be null"); String[] rangeValuesStrings = StringUtils.split(rangeString, "bytes="); Validate.isTrue(rangeValuesStrings.length == 1, "Range header value doesn't begin with string: bytes="); final String byteRange = rangeValuesStrings[0]; Validate.isTrue(StringUtils.split(byteRange, ",").length == 1, "Multi-range requests are not supported"); String[] rangeParts = StringUtils.split(byteRange, "-"); Validate.isTrue(StringUtils.countMatches(byteRange, "-") < 2, "Cannot end or start with a negative number"); Long startPos = null; Long endPos = null; if (StringUtils.startsWith(byteRange, "-")) { endPos = Long.parseLong(byteRange); } else if (StringUtils.endsWith(byteRange, "-")) { startPos = Long.parseLong(byteRange.split("-")[0]); } else if (rangeParts.length == 2) { startPos = Long.parseUnsignedLong(rangeParts[0]); endPos = Long.parseUnsignedLong(rangeParts[1]); } else { throw new IllegalArgumentException("range must exist with - separator"); } return new Long[] { startPos, endPos }; }
From source file:io.wcm.handler.url.impl.UrlHandlerImplTest.java
/** * Simulate mapping:/*from w ww .ja v a 2s . c om*/ * - /content/unittest/de_test/brand/de -> /de * - /content/* -> /* */ private static MockSlingHttpServletRequest applySimpleMapping(SlingHttpServletRequest request) { ResourceResolver spyResolver = spy(request.getResourceResolver()); Answer<String> mappingAnswer = new Answer<String>() { @Override public String answer(InvocationOnMock invocation) { SlingHttpServletRequest mapRequest; String path; if (invocation.getArguments()[0] instanceof SlingHttpServletRequest) { mapRequest = (SlingHttpServletRequest) invocation.getArguments()[0]; path = (String) invocation.getArguments()[1]; } else { mapRequest = null; path = (String) invocation.getArguments()[0]; } if (StringUtils.startsWith(path, "/content/unittest/de_test/brand/")) { path = "/" + StringUtils.substringAfter(path, "/content/unittest/de_test/brand/"); } if (StringUtils.startsWith(path, "/content/")) { path = "/" + StringUtils.substringAfter(path, "/content/"); } if (mapRequest != null) { path = StringUtils.defaultString(mapRequest.getContextPath()) + path; } path = Externalizer.mangleNamespaces(path); try { return URLEncoder.encode(path, CharEncoding.UTF_8); } catch (UnsupportedEncodingException ex) { throw new RuntimeException(ex); } } }; when(spyResolver.map(anyString())).thenAnswer(mappingAnswer); when(spyResolver.map(any(SlingHttpServletRequest.class), anyString())).thenAnswer(mappingAnswer); MockSlingHttpServletRequest newRequest = new MockSlingHttpServletRequest(spyResolver); newRequest.setResource(request.getResource()); newRequest.setContextPath(request.getContextPath()); return newRequest; }