List of usage examples for com.google.common.collect Range upperEndpoint
public C upperEndpoint()
From source file:com.nimbits.io.http.NimbitsClientImpl.java
@Override public List<Value> getSeries(final String entity, final Range<Date> range) { final Gson gson = new GsonBuilder().registerTypeAdapter(Value.class, new ValueDeserializer()).create(); RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(instanceUrl.getUrl()) .setRequestInterceptor(requestInterceptor).setConverter(new GsonConverter(gson)).build(); SeriesApi seriesApi = restAdapter.create(SeriesApi.class); List<Value> sample = seriesApi.getSeries(entity, range.lowerEndpoint().getTime(), range.upperEndpoint().getTime()); List<Value> fixed = new ArrayList<>(sample.size()); Set<Long> test = new HashSet<>(sample.size()); for (Value value : sample) { if (!test.contains(value.getTimestamp().getTime())) { fixed.add(value);/*from w w w .j a va2s . c o m*/ test.add(value.getTimestamp().getTime()); } } return sample; }
From source file:net.sf.mzmine.modules.visualization.twod.TwoDDataSet.java
double upperEndpointIntensity(Range<Double> rtRange, Range<Double> mzRange, PlotMode plotMode) { double maxIntensity = 0; double searchRetentionTimes[] = retentionTimes; if (processedScans < totalScans) { searchRetentionTimes = new double[processedScans]; System.arraycopy(retentionTimes, 0, searchRetentionTimes, 0, searchRetentionTimes.length); }//from www.j a va 2s. c om int startScanIndex = Arrays.binarySearch(searchRetentionTimes, rtRange.lowerEndpoint()); if (startScanIndex < 0) startScanIndex = (startScanIndex * -1) - 1; if (startScanIndex >= searchRetentionTimes.length) { return 0; } if (searchRetentionTimes[startScanIndex] > rtRange.upperEndpoint()) { if (startScanIndex == 0) return 0; if (startScanIndex == searchRetentionTimes.length - 1) return upperEndpointIntensity(startScanIndex - 1, mzRange, plotMode); // find which scan point is closer double diffNext = searchRetentionTimes[startScanIndex] - rtRange.upperEndpoint(); double diffPrev = rtRange.lowerEndpoint() - searchRetentionTimes[startScanIndex - 1]; if (diffPrev < diffNext) return upperEndpointIntensity(startScanIndex - 1, mzRange, plotMode); else return upperEndpointIntensity(startScanIndex, mzRange, plotMode); } for (int scanIndex = startScanIndex; ((scanIndex < searchRetentionTimes.length) && (searchRetentionTimes[scanIndex] <= rtRange.upperEndpoint())); scanIndex++) { // ignore scans where all peaks are smaller than current max if (basePeaks[scanIndex] < maxIntensity) continue; double scanMax = upperEndpointIntensity(scanIndex, mzRange, plotMode); if (scanMax > maxIntensity) maxIntensity = scanMax; } return maxIntensity; }
From source file:com.google.googlejavaformat.java.JavaOutput.java
/** * Emit a list of {@link Replacement}s to convert from input to output. * * @return a list of {@link Replacement}s, sorted by start index, without overlaps *///from ww w . ja va2s .com public ImmutableList<Replacement> getFormatReplacements(RangeSet<Integer> iRangeSet0) { ImmutableList.Builder<Replacement> result = ImmutableList.builder(); Map<Integer, Range<Integer>> kToJ = JavaOutput.makeKToIJ(this); // Expand the token ranges to align with re-formattable boundaries. RangeSet<Integer> breakableRanges = TreeRangeSet.create(); RangeSet<Integer> iRangeSet = iRangeSet0.subRangeSet(Range.closed(0, javaInput.getkN())); for (Range<Integer> iRange : iRangeSet.asRanges()) { Range<Integer> range = expandToBreakableRegions(iRange.canonical(DiscreteDomain.integers())); if (range.equals(EMPTY_RANGE)) { // the range contains only whitespace continue; } breakableRanges.add(range); } // Construct replacements for each reformatted region. for (Range<Integer> range : breakableRanges.asRanges()) { Input.Tok startTok = startTok(javaInput.getToken(range.lowerEndpoint())); Input.Tok endTok = endTok(javaInput.getToken(range.upperEndpoint() - 1)); // Add all output lines in the given token range to the replacement. StringBuilder replacement = new StringBuilder(); int replaceFrom = startTok.getPosition(); // Replace leading whitespace in the input with the whitespace from the formatted file while (replaceFrom > 0) { char previous = javaInput.getText().charAt(replaceFrom - 1); if (!CharMatcher.whitespace().matches(previous)) { break; } replaceFrom--; } int i = kToJ.get(startTok.getIndex()).lowerEndpoint(); // Include leading blank lines from the formatted output, unless the formatted range // starts at the beginning of the file. while (i > 0 && getLine(i - 1).isEmpty()) { i--; } // Write out the formatted range. for (; i < kToJ.get(endTok.getIndex()).upperEndpoint(); i++) { // It's possible to run out of output lines (e.g. if the input ended with // multiple trailing newlines). if (i < getLineCount()) { if (i > 0) { replacement.append(lineSeparator); } replacement.append(getLine(i)); } } int replaceTo = Math.min(endTok.getPosition() + endTok.length(), javaInput.getText().length()); // If the formatted ranged ended in the trailing trivia of the last token before EOF, // format all the way up to EOF to deal with trailing whitespace correctly. if (endTok.getIndex() == javaInput.getkN() - 1) { replaceTo = javaInput.getText().length(); } // Replace trailing whitespace in the input with the whitespace from the formatted file. // If the trailing whitespace in the input includes one or more line breaks, preserve the // whitespace after the last newline to avoid re-indenting the line following the formatted // line. int newline = -1; while (replaceTo < javaInput.getText().length()) { char next = javaInput.getText().charAt(replaceTo); if (!CharMatcher.whitespace().matches(next)) { break; } int newlineLength = Newlines.hasNewlineAt(javaInput.getText(), replaceTo); if (newlineLength != -1) { newline = replaceTo; // Skip over the entire newline; don't count the second character of \r\n as a newline. replaceTo += newlineLength; } else { replaceTo++; } } if (newline != -1) { replaceTo = newline; } if (newline == -1) { // There wasn't an existing trailing newline; add one. replacement.append(lineSeparator); } for (; i < getLineCount(); i++) { String after = getLine(i); int idx = CharMatcher.whitespace().negate().indexIn(after); if (idx == -1) { // Write out trailing empty lines from the formatted output. replacement.append(lineSeparator); } else { if (newline == -1) { // If there wasn't a trailing newline in the input, indent the next line. replacement.append(after.substring(0, idx)); } break; } } result.add(Replacement.create(replaceFrom, replaceTo, replacement.toString())); } return result.build(); }
From source file:org.pshdl.model.extensions.RangeExtension.java
protected Optional<Range<BigInteger>> _determineRange(final HDLManip obj, final HDLEvaluationContext context) { HDLExpression _target = obj.getTarget(); final Optional<Range<BigInteger>> right = this.determineRange(_target, context); boolean _isPresent = right.isPresent(); boolean _not = (!_isPresent); if (_not) {//w w w . j a v a 2s.c o m return Optional.<Range<BigInteger>>absent(); } HDLManip.HDLManipType _type = obj.getType(); if (_type != null) { switch (_type) { case CAST: final HDLType type = obj.getCastTo(); if ((type instanceof HDLPrimitive)) { HDLPrimitives _instance = HDLPrimitives.getInstance(); final Optional<Range<BigInteger>> castRange = _instance.getValueRange(((HDLPrimitive) type), context); boolean _isPresent_1 = right.isPresent(); boolean _not_1 = (!_isPresent_1); if (_not_1) { return Optional.<Range<BigInteger>>absent(); } HDLPrimitive.HDLPrimitiveType _type_1 = ((HDLPrimitive) type).getType(); boolean _equals = Objects.equal(_type_1, HDLPrimitive.HDLPrimitiveType.INTEGER); if (_equals) { Range<BigInteger> _intRange = HDLPrimitives.intRange(BigInteger.valueOf(32L)); Range<BigInteger> _get = right.get(); Range<BigInteger> _intersection = _intRange.intersection(_get); return Optional.<Range<BigInteger>>of(_intersection); } HDLPrimitive.HDLPrimitiveType _type_2 = ((HDLPrimitive) type).getType(); boolean _equals_1 = Objects.equal(_type_2, HDLPrimitive.HDLPrimitiveType.NATURAL); if (_equals_1) { Range<BigInteger> _uintRange = HDLPrimitives.uintRange(BigInteger.valueOf(32L)); Range<BigInteger> _get_1 = right.get(); Range<BigInteger> _intersection_1 = _uintRange.intersection(_get_1); return Optional.<Range<BigInteger>>of(_intersection_1); } HDLPrimitive.HDLPrimitiveType _type_3 = ((HDLPrimitive) type).getType(); boolean _equals_2 = Objects.equal(_type_3, HDLPrimitive.HDLPrimitiveType.BIT); if (_equals_2) { Range<BigInteger> _createRange = RangeTool.<BigInteger>createRange(BigInteger.ZERO, BigInteger.ONE); Range<BigInteger> _get_2 = right.get(); Range<BigInteger> _intersection_2 = _createRange.intersection(_get_2); return Optional.<Range<BigInteger>>of(_intersection_2); } boolean _isPresent_2 = castRange.isPresent(); boolean _not_2 = (!_isPresent_2); if (_not_2) { return Optional.<Range<BigInteger>>absent(); } Range<BigInteger> _get_3 = castRange.get(); Range<BigInteger> _get_4 = right.get(); Range<BigInteger> _intersection_3 = _get_3.intersection(_get_4); return Optional.<Range<BigInteger>>of(_intersection_3); } obj.<IHDLObject>addMeta(ProblemDescription.SOURCE, obj); obj.<ProblemDescription>addMeta(ProblemDescription.DESCRIPTION, ProblemDescription.TYPE_NOT_SUPPORTED_FOR_CONSTANTS); return Optional.<Range<BigInteger>>absent(); case ARITH_NEG: Range<BigInteger> _get_5 = right.get(); BigInteger _upperEndpoint = _get_5.upperEndpoint(); BigInteger _negate = _upperEndpoint.negate(); Range<BigInteger> _get_6 = right.get(); BigInteger _lowerEndpoint = _get_6.lowerEndpoint(); BigInteger _negate_1 = _lowerEndpoint.negate(); Range<BigInteger> _createRange_1 = RangeTool.<BigInteger>createRange(_negate, _negate_1); return Optional.<Range<BigInteger>>of(_createRange_1); case BIT_NEG: Range<BigInteger> _get_7 = right.get(); BigInteger _upperEndpoint_1 = _get_7.upperEndpoint(); int _bitLength = _upperEndpoint_1.bitLength(); BigInteger _shiftLeft = BigInteger.ONE.shiftLeft(_bitLength); BigInteger _subtract = _shiftLeft.subtract(BigInteger.ONE); Range<BigInteger> _createRange_2 = RangeTool.<BigInteger>createRange(BigInteger.ZERO, _subtract); return Optional.<Range<BigInteger>>of(_createRange_2); case LOGIC_NEG: obj.<IHDLObject>addMeta(ProblemDescription.SOURCE, obj); obj.<ProblemDescription>addMeta(ProblemDescription.DESCRIPTION, ProblemDescription.BOOLEAN_NOT_SUPPORTED_FOR_RANGES); Range<BigInteger> _createRange_3 = RangeTool.<BigInteger>createRange(BigInteger.ZERO, BigInteger.ONE); return Optional.<Range<BigInteger>>of(_createRange_3); default: break; } } throw new RuntimeException("Incorrectly implemented obj op"); }
From source file:jetbrains.jetpad.hybrid.HybridSynchronizer.java
private CellTrait createTargetTrait() { return new CellTrait() { @Override//w ww . j a v a 2 s. c o m public Object get(Cell cell, CellTraitPropertySpec<?> spec) { if (spec == HYBRID_SYNCHRONIZER) { return HybridSynchronizer.this; } if (spec == CellStateHandler.PROPERTY) { return getCellStateHandler(); } return super.get(cell, spec); } @Override public void onKeyPressed(Cell cell, KeyEvent event) { Cell focusedCell = cell.cellContainer().get().focusedCell.get(); if (myTargetList.contains(focusedCell)) { Cell currentCell = cell.cellContainer().get().focusedCell.get(); if (!hasSelection()) { if (event.is(KeyStrokeSpecs.SELECT_UP) && currentCell != null) { mySelectionSupport.select(currentCell, currentCell); event.consume(); } } else { Range<Integer> currentRange = selection(); if (event.is(KeyStrokeSpecs.SELECT_UP)) { ParseNode parseNode = myTokenListEditor.parseNode(); if (parseNode != null) { if (!currentRange.equals(parseNode.range())) { ParseNode node = ParseNodes.findForRange(parseNode, currentRange); ParseNode parentNode = ParseNodes.nonSameRangeParent(node); if (parentNode != null) { select(parentNode.range()); event.consume(); } } } else { if (!currentRange.equals(Range.closed(0, tokens().size()))) { select(Range.closed(0, tokens().size())); event.consume(); } } } if (event.is(KeyStrokeSpecs.SELECT_DOWN)) { ParseNode parseNode = myTokenListEditor.parseNode(); if (parseNode != null) { ParseNode node = ParseNodes.findForRange(parseNode, currentRange); ParseNode childNode = ParseNodes.nonSameRangeChild(node, myTargetList.indexOf(mySelectionSupport.currentCell())); if (childNode != null) { select(childNode.range()); event.consume(); return; } } if (!mySelectionSupport.isCurrentCompletelySelected()) { mySelectionSupport.clearSelection(); event.consume(); } } } } super.onKeyPressed(cell, event); } @Override public void onCopy(Cell cell, CopyCutEvent event) { if (canCopy()) { event.consume(copy()); return; } super.onCopy(cell, event); } @Override public void onCut(Cell cell, CopyCutEvent event) { if (canCut()) { event.consume(cut()); return; } super.onCut(cell, event); } @Override public void onPaste(Cell cell, PasteEvent event) { if (canPaste(event.getContent())) { paste(event.getContent()); event.consume(); return; } super.onPaste(cell, event); } private boolean canPaste(ClipboardContent content) { return content.isSupported(TOKENS_CONTENT); } private void paste(ClipboardContent content) { List<Token> tokens = content.get(TOKENS_CONTENT); Cell currentCell = mySelectionSupport.currentCell(); int targetIndex; if (currentCell != null) { int currentCellIndex = myTargetList.indexOf(currentCell); targetIndex = Positions.isHomePosition(currentCell) ? currentCellIndex : currentCellIndex + 1; } else { targetIndex = 0; } myTokenListEditor.tokens.addAll(targetIndex, tokens); myTokenListEditor.updateToPrintedTokens(); tokenOperations().select(targetIndex + tokens.size() - 1, LAST).run(); } private boolean canCopy() { return hasSelection(); } private ClipboardContent copy() { final Range<Integer> selection = selection(); final List<Token> tokens = new ArrayList<>( tokens().subList(selection.lowerEndpoint(), selection.upperEndpoint())); return new ClipboardContent() { @Override public boolean isSupported(ContentKind<?> kind) { return kind == TOKENS_CONTENT; } @Override public <T> T get(ContentKind<T> kind) { if (kind == TOKENS_CONTENT) { return (T) Collections.unmodifiableList(tokens); } return null; } }; } private boolean canCut() { return hasSelection(); } private ClipboardContent cut() { ClipboardContent result = copy(); clearSelection(); return result; } }; }
From source file:edu.mit.streamjit.impl.compiler2.ActorGroup.java
/** * Returns a void->void MethodHandle that will run this ActorGroup for the * given iterations using the given ConcreteStorage instances. * @param iterations the range of iterations to run for * @param storage the storage being used * @return a void->void method handle */// w ww . j a v a 2 s . c o m public MethodHandle specialize(Range<Integer> iterations, Map<Storage, ConcreteStorage> storage, BiFunction<MethodHandle[], WorkerActor, MethodHandle> switchFactory, int unrollFactor, ImmutableTable<Actor, Integer, IndexFunctionTransformer> inputTransformers, ImmutableTable<Actor, Integer, IndexFunctionTransformer> outputTransformers) { //TokenActors are special. assert !isTokenGroup() : actors(); Map<Actor, MethodHandle> withRWHandlesBound = bindActorsToStorage(iterations, storage, switchFactory, inputTransformers, outputTransformers); int totalIterations = iterations.upperEndpoint() - iterations.lowerEndpoint(); unrollFactor = Math.min(unrollFactor, totalIterations); int unrolls = (totalIterations / unrollFactor); int unrollEndpoint = iterations.lowerEndpoint() + unrolls * unrollFactor; MethodHandle overall = Combinators.semicolon( makeGroupLoop(Range.closedOpen(iterations.lowerEndpoint(), unrollEndpoint), unrollFactor, withRWHandlesBound), makeGroupLoop(Range.closedOpen(unrollEndpoint, iterations.upperEndpoint()), 1, withRWHandlesBound)); return overall; }
From source file:org.pshdl.model.validation.builtin.BuiltInValidator.java
private static void checkType(HDLPackage unit, Set<Problem> problems, Map<HDLQualifiedName, HDLEvaluationContext> hContext) { final HDLVariableDeclaration[] hvds = unit.getAllObjectsOf(HDLVariableDeclaration.class, true); for (final HDLVariableDeclaration hvd : hvds) { final Optional<? extends HDLType> type = hvd.resolveType(); if (type.isPresent()) { final HDLType hdlType = type.get(); if (hdlType instanceof HDLPrimitive) { final HDLPrimitive primType = (HDLPrimitive) hdlType; switch (primType.getType()) { case BIT: case INTEGER: case NATURAL: break; case STRING: if (primType.getWidth() != null) { problems.add(new Problem(TYPE_INVALID_PRIMITIVE, hvd, "Strings can not have a width")); }//w ww. j a v a 2 s . c o m break; case BOOL: if (primType.getWidth() != null) { problems.add(new Problem(TYPE_INVALID_PRIMITIVE, hvd, "Booleans can not have a width")); } break; case BITVECTOR: case INT: case UINT: final Optional<Range<BigInteger>> rangeOpt = RangeExtension.rangeOf(primType.getWidth()); if (rangeOpt.isPresent()) { final Range<BigInteger> range = rangeOpt.get(); if (!range.hasLowerBound()) { problems.add(new Problem(ErrorCode.TYPE_NEGATIVE_WIDTH, hvd)); } else { final BigInteger le = range.lowerEndpoint(); if (le.compareTo(BigInteger.ZERO) < 0) { if (range.hasUpperBound() && (range.upperEndpoint().compareTo(BigInteger.ZERO) < 0)) { problems.add(new Problem(ErrorCode.TYPE_NEGATIVE_WIDTH, hvd)); } else { problems.add(new Problem(ErrorCode.TYPE_POSSIBLY_NEGATIVE_WIDTH, hvd)); } } else if (le.equals(BigInteger.ZERO) && range.hasUpperBound() && range.upperEndpoint().equals(BigInteger.ZERO)) { problems.add(new Problem(ErrorCode.TYPE_ZERO_WIDTH, hvd)); } else if (le.equals(BigInteger.ZERO)) { problems.add(new Problem(ErrorCode.TYPE_POSSIBLY_ZERO_WIDTH, hvd)); } } } break; } } } } final HDLOpExpression[] ops = unit.getAllObjectsOf(HDLOpExpression.class, true); for (final HDLOpExpression ope : ops) { if (skipExp(ope)) { continue; } checkOpExpression(problems, ope, ope); } final HDLManip[] manips = unit.getAllObjectsOf(HDLManip.class, true); for (final HDLManip manip : manips) { final Optional<? extends HDLType> targetType = TypeExtension.typeOf(manip.getTarget()); if (targetType.isPresent()) { final HDLType tt = targetType.get(); switch (manip.getType()) { case ARITH_NEG: if (tt instanceof HDLPrimitive) { final HDLPrimitive primitive = (HDLPrimitive) tt; if (!primitive.isNumber()) { problems.add(new Problem(UNSUPPORTED_TYPE_FOR_OP, manip, "Can not use arithmetic negate on a non-number")); } } else { problems.add(new Problem(UNSUPPORTED_TYPE_FOR_OP, manip, "Can not use arithmetic negate on a non-number")); } break; case BIT_NEG: if (manip.getTarget().getClassType() == HDLClass.HDLLiteral) { problems.add(new Problem(UNSUPPORTED_TYPE_FOR_OP, manip, "Can not use binary negate on literals as they have no width")); } if (tt instanceof HDLPrimitive) { final HDLPrimitive primitive = (HDLPrimitive) tt; if (!primitive.isBits()) { problems.add(new Problem(UNSUPPORTED_TYPE_FOR_OP, manip, "Can not use binary negate on a non-bits")); } } else { problems.add(new Problem(UNSUPPORTED_TYPE_FOR_OP, manip, "Can not use binary negate on a non-bits")); } break; case LOGIC_NEG: if (tt instanceof HDLPrimitive) { final HDLPrimitive primitive = (HDLPrimitive) tt; if ((primitive.getType() != HDLPrimitiveType.BOOL) && (primitive.getType() != HDLPrimitiveType.BIT)) { problems.add(new Problem(BOOL_NEGATE_NUMERIC_NOT_SUPPORTED, manip, "Can not use logic negate on a non boolean/bit")); } } else { problems.add(new Problem(UNSUPPORTED_TYPE_FOR_OP, manip, "Can not use logic negate on a non boolean")); } break; case CAST: final HDLType castTo = manip.getCastTo(); if (castTo instanceof HDLInterface) { if (!(tt instanceof HDLInterface)) { problems.add(new Problem(UNSUPPORTED_TYPE_FOR_OP, manip, "Can not cast from interface to non interface type:" + castTo)); } } if (castTo instanceof HDLEnum) { problems.add( new Problem(UNSUPPORTED_TYPE_FOR_OP, manip, "Enums can not be casted to anything")); } if (castTo instanceof HDLPrimitive) { if (!(tt instanceof HDLPrimitive)) { problems.add(new Problem(UNSUPPORTED_TYPE_FOR_OP, manip, "Can not cast from primitve to non primitive type:" + castTo)); } } break; } } } }
From source file:org.sonatype.nexus.content.internal.ContentServlet.java
/** * Handles a file response, all the conditional request cases, and eventually the content serving of the file item. *//*from www.jav a2s . co m*/ protected void doGetFile(final HttpServletRequest request, final HttpServletResponse response, final StorageFileItem file) throws ServletException, IOException { // ETag, in "shaved" form of {SHA1{e5c244520e897865709c730433f8b0c44ef271f1}} (without quotes) // or null if file does not have SHA1 (like Virtual) or generated items (as their SHA1 would correspond to template, // not to actual generated content). final String etag; if (!file.isContentGenerated() && !file.isVirtual() && file.getRepositoryItemAttributes().containsKey(StorageFileItem.DIGEST_SHA1_KEY)) { etag = "{SHA1{" + file.getRepositoryItemAttributes().get(StorageFileItem.DIGEST_SHA1_KEY) + "}}"; // tag header ETag: "{SHA1{e5c244520e897865709c730433f8b0c44ef271f1}}", quotes are must by RFC response.setHeader("ETag", "\"" + etag + "\""); } else { etag = null; } response.setHeader("Content-Type", file.getMimeType()); response.setDateHeader("Last-Modified", file.getModified()); // content-length, if known if (file.getLength() != ContentLocator.UNKNOWN_LENGTH) { // Note: response.setContentLength Servlet API method uses ints (max 2GB file)! // TODO: apparently, some Servlet containers follow serlvet API and assume // contents can have 2GB max, so even this workaround below in inherently unsafe. // Jetty is checked, and supports this (uses long internally), but unsure for other containers response.setHeader("Content-Length", String.valueOf(file.getLength())); } // handle conditional GETs only for "static" content, actual content stored, not generated if (!file.isContentGenerated() && file.getResourceStoreRequest().getIfModifiedSince() != 0 && file.getModified() <= file.getResourceStoreRequest().getIfModifiedSince()) { // this is a conditional GET using time-stamp response.setStatus(SC_NOT_MODIFIED); } else if (!file.isContentGenerated() && file.getResourceStoreRequest().getIfNoneMatch() != null && etag != null && file.getResourceStoreRequest().getIfNoneMatch().equals(etag)) { // this is a conditional GET using ETag response.setStatus(SC_NOT_MODIFIED); } else { final List<Range<Long>> ranges = getRequestedRanges(request, file.getLength()); // pour the content, but only if needed (this method will be called even for HEAD reqs, but with content tossed // away), so be conservative as getting input stream involves locking etc, is expensive final boolean contentNeeded = "GET".equalsIgnoreCase(request.getMethod()); if (ranges.isEmpty()) { if (contentNeeded) { webUtils.sendContent(file.getInputStream(), response); } } else if (ranges.size() > 1) { throw new ErrorStatusException(SC_NOT_IMPLEMENTED, "Not Implemented", "Multiple ranges not yet supported."); } else { final Range<Long> range = ranges.get(0); if (!isRequestedRangeSatisfiable(file, range)) { response.setStatus(SC_REQUESTED_RANGE_NOT_SATISFIABLE); response.setHeader("Content-Length", "0"); response.setHeader("Content-Range", "bytes */" + file.getLength()); return; } final long bodySize = 1 + range.upperEndpoint() - range.lowerEndpoint(); response.setStatus(SC_PARTIAL_CONTENT); response.setHeader("Content-Length", String.valueOf(bodySize)); response.setHeader("Content-Range", range.lowerEndpoint() + "-" + range.upperEndpoint() + "/" + file.getLength()); if (contentNeeded) { try (final InputStream in = file.getInputStream()) { in.skip(range.lowerEndpoint()); webUtils.sendContent(limit(in, bodySize), response); } } } } }
From source file:io.github.mzmine.parameters.parametertypes.selectors.ScanSelectionParameter.java
@Override public void saveValueToXML(Element xmlElement) { ScanSelection value = getValue();//from ww w .j av a2 s . c om if (value == null) return; Document parentDocument = xmlElement.getOwnerDocument(); final Range<Integer> scanNumberRange = value.getScanNumberRange(); final Range<Double> scanRetentionTimeRange = value.getScanRTRange(); final PolarityType polarity = value.getPolarity(); final MsSpectrumType spectrumType = value.getSpectrumType(); final Integer msLevel = value.getMsLevel(); final String scanDefinition = value.getScanDefinition(); if (scanNumberRange != null) { Element scanNumElement = parentDocument.createElement("scan_numbers"); xmlElement.appendChild(scanNumElement); Element newElement = parentDocument.createElement("min"); newElement.setTextContent(String.valueOf(scanNumberRange.lowerEndpoint())); scanNumElement.appendChild(newElement); newElement = parentDocument.createElement("max"); newElement.setTextContent(String.valueOf(scanNumberRange.upperEndpoint())); scanNumElement.appendChild(newElement); } if (scanRetentionTimeRange != null) { Element scanRtElement = parentDocument.createElement("retention_time"); xmlElement.appendChild(scanRtElement); Element newElement = parentDocument.createElement("min"); newElement.setTextContent(String.valueOf(scanRetentionTimeRange.lowerEndpoint())); scanRtElement.appendChild(newElement); newElement = parentDocument.createElement("max"); newElement.setTextContent(String.valueOf(scanRetentionTimeRange.upperEndpoint())); scanRtElement.appendChild(newElement); } if (polarity != null) { Element newElement = parentDocument.createElement("polarity"); newElement.setTextContent(polarity.toString()); xmlElement.appendChild(newElement); } if (spectrumType != null) { Element newElement = parentDocument.createElement("spectrum_type"); newElement.setTextContent(spectrumType.toString()); xmlElement.appendChild(newElement); } if (msLevel != null) { Element newElement = parentDocument.createElement("ms_level"); newElement.setTextContent(String.valueOf(msLevel)); xmlElement.appendChild(newElement); } if (scanDefinition != null) { Element newElement = parentDocument.createElement("scan_definition"); newElement.setTextContent(scanDefinition); xmlElement.appendChild(newElement); } }
From source file:com.nimbits.server.io.BlobStoreImpl.java
@Override public List<Value> getDataSegment(final Entity entity, final Range<Date> timespan) { PersistenceManager pm = persistenceManagerFactory.getPersistenceManager(); try {//from w w w. j av a 2 s.c om final List<Value> retObj = new ArrayList<Value>(); final Query q = pm.newQuery(ValueBlobStoreEntity.class); q.setFilter("entity == k && minTimestamp <= et && maxTimestamp >= st "); q.declareParameters("String k, Long et, Long st"); q.setOrdering("minTimestamp desc"); final Iterable<ValueBlobStore> result = (Iterable<ValueBlobStore>) q.execute(entity.getKey(), timespan.upperEndpoint().getTime(), timespan.lowerEndpoint().getTime()); for (final ValueBlobStore e : result) { //todo break out of loop when range is met if (validateOwnership(entity, e)) { List<Value> values = readValuesFromFile(e.getBlobKey()); for (final Value vx : values) { if (timespan.contains(vx.getTimestamp())) { retObj.add(vx); } } } } return retObj; } finally { pm.close(); } }