List of usage examples for java.lang Long MIN_VALUE
long MIN_VALUE
To view the source code for java.lang Long MIN_VALUE.
Click Source Link
From source file:io.warp10.standalone.StandaloneDeleteHandler.java
@Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { if (target.equals(Constants.API_ENDPOINT_DELETE)) { baseRequest.setHandled(true);/* w ww.j a v a 2 s .c o m*/ } else { return; } // // CORS header // response.setHeader("Access-Control-Allow-Origin", "*"); long nano = System.nanoTime(); // // Extract DatalogRequest if specified // String datalogHeader = request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_DATALOG)); DatalogRequest dr = null; boolean forwarded = false; if (null != datalogHeader) { byte[] bytes = OrderPreservingBase64.decode(datalogHeader.getBytes(Charsets.US_ASCII)); if (null != datalogPSK) { bytes = CryptoUtils.unwrap(datalogPSK, bytes); } if (null == bytes) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid Datalog header."); return; } TDeserializer deser = new TDeserializer(new TCompactProtocol.Factory()); try { dr = new DatalogRequest(); deser.deserialize(dr, bytes); } catch (TException te) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.getMessage()); return; } Map<String, String> labels = new HashMap<String, String>(); labels.put(SensisionConstants.SENSISION_LABEL_ID, new String( OrderPreservingBase64.decode(dr.getId().getBytes(Charsets.US_ASCII)), Charsets.UTF_8)); labels.put(SensisionConstants.SENSISION_LABEL_TYPE, dr.getType()); Sensision.update(SensisionConstants.CLASS_WARP_DATALOG_REQUESTS_RECEIVED, labels, 1); // // Check that the request query string matches the QS in the datalog request // if (!request.getQueryString().equals(dr.getDeleteQueryString())) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid DatalogRequest."); return; } forwarded = true; } // // TODO(hbs): Extract producer/owner from token // String token = null != dr ? dr.getToken() : request.getHeader(Constants.getHeader(Configuration.HTTP_HEADER_TOKENX)); if (null == token) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Missing token."); return; } WriteToken writeToken; try { writeToken = Tokens.extractWriteToken(token); } catch (WarpScriptException ee) { ee.printStackTrace(); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ee.getMessage()); return; } String application = writeToken.getAppName(); String producer = Tokens.getUUID(writeToken.getProducerId()); String owner = Tokens.getUUID(writeToken.getOwnerId()); // // For delete operations, producer and owner MUST be equal // if (!producer.equals(owner)) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid write token for deletion."); return; } Map<String, String> sensisionLabels = new HashMap<String, String>(); sensisionLabels.put(SensisionConstants.SENSISION_LABEL_PRODUCER, producer); long count = 0; long gts = 0; Throwable t = null; StringBuilder metas = new StringBuilder(); // // Extract start/end // String startstr = request.getParameter(Constants.HTTP_PARAM_START); String endstr = request.getParameter(Constants.HTTP_PARAM_END); // // Extract selector // String selector = request.getParameter(Constants.HTTP_PARAM_SELECTOR); String minage = request.getParameter(Constants.HTTP_PARAM_MINAGE); if (null != minage) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Standalone version does not support the '" + Constants.HTTP_PARAM_MINAGE + "' parameter in delete requests."); return; } boolean dryrun = null != request.getParameter(Constants.HTTP_PARAM_DRYRUN); File loggingFile = null; PrintWriter loggingWriter = null; // // Open the logging file if logging is enabled // if (null != loggingDir) { long nanos = null != dr ? dr.getTimestamp() : TimeSource.getNanoTime(); StringBuilder sb = new StringBuilder(); sb.append(Long.toHexString(nanos)); sb.insert(0, "0000000000000000", 0, 16 - sb.length()); sb.append("-"); if (null != dr) { sb.append(dr.getId()); } else { sb.append(datalogId); } sb.append("-"); sb.append(dtf.print(nanos / 1000000L)); sb.append(Long.toString(1000000L + (nanos % 1000000L)).substring(1)); sb.append("Z"); if (null == dr) { dr = new DatalogRequest(); dr.setTimestamp(nanos); dr.setType(Constants.DATALOG_DELETE); dr.setId(datalogId); dr.setToken(token); dr.setDeleteQueryString(request.getQueryString()); } if (null != dr && (!forwarded || (forwarded && this.logforwarded))) { // // Serialize the request // TSerializer ser = new TSerializer(new TCompactProtocol.Factory()); byte[] encoded; try { encoded = ser.serialize(dr); } catch (TException te) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, te.getMessage()); return; } if (null != this.datalogPSK) { encoded = CryptoUtils.wrap(this.datalogPSK, encoded); } encoded = OrderPreservingBase64.encode(encoded); loggingFile = new File(loggingDir, sb.toString()); loggingWriter = new PrintWriter(new FileWriterWithEncoding(loggingFile, Charsets.UTF_8)); // // Write request // loggingWriter.println(new String(encoded, Charsets.US_ASCII)); } } boolean validated = false; try { if (null == producer || null == owner) { response.sendError(HttpServletResponse.SC_FORBIDDEN, "Invalid token."); return; } // // Build extra labels // Map<String, String> extraLabels = new HashMap<String, String>(); // // Only set owner and potentially app, producer may vary // extraLabels.put(Constants.OWNER_LABEL, owner); // FIXME(hbs): remove me if (null != application) { extraLabels.put(Constants.APPLICATION_LABEL, application); sensisionLabels.put(SensisionConstants.SENSISION_LABEL_APPLICATION, application); } boolean hasRange = false; long start = Long.MIN_VALUE; long end = Long.MAX_VALUE; if (null != startstr) { if (null == endstr) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Both " + Constants.HTTP_PARAM_START + " and " + Constants.HTTP_PARAM_END + " should be defined."); return; } if (startstr.contains("T")) { start = fmt.parseDateTime(startstr).getMillis() * Constants.TIME_UNITS_PER_MS; } else { start = Long.valueOf(startstr); } } if (null != endstr) { if (null == startstr) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Both " + Constants.HTTP_PARAM_START + " and " + Constants.HTTP_PARAM_END + " should be defined."); return; } if (endstr.contains("T")) { end = fmt.parseDateTime(endstr).getMillis() * Constants.TIME_UNITS_PER_MS; } else { end = Long.valueOf(endstr); } } if (Long.MIN_VALUE == start && Long.MAX_VALUE == end && null == request.getParameter(Constants.HTTP_PARAM_DELETEALL)) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Parameter " + Constants.HTTP_PARAM_DELETEALL + " should be set when deleting a full range."); return; } if (Long.MIN_VALUE != start || Long.MAX_VALUE != end) { hasRange = true; } if (start > end) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Invalid time range specification."); return; } // // Extract the class and labels selectors // The class selector and label selectors are supposed to have // values which use percent encoding, i.e. explicit percent encoding which // might have been re-encoded using percent encoding when passed as parameter // // Matcher m = EgressFetchHandler.SELECTOR_RE.matcher(selector); if (!m.matches()) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } String classSelector = URLDecoder.decode(m.group(1), "UTF-8"); String labelsSelection = m.group(2); Map<String, String> labelsSelectors; try { labelsSelectors = GTSHelper.parseLabelsSelectors(labelsSelection); } catch (ParseException pe) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, pe.getMessage()); return; } validated = true; // // Force 'producer'/'owner'/'app' from token // labelsSelectors.putAll(extraLabels); List<Metadata> metadatas = null; List<String> clsSels = new ArrayList<String>(); List<Map<String, String>> lblsSels = new ArrayList<Map<String, String>>(); clsSels.add(classSelector); lblsSels.add(labelsSelectors); metadatas = directoryClient.find(clsSels, lblsSels); response.setStatus(HttpServletResponse.SC_OK); response.setContentType("text/plain"); PrintWriter pw = response.getWriter(); StringBuilder sb = new StringBuilder(); for (Metadata metadata : metadatas) { // // Remove from DB // if (!hasRange) { if (!dryrun) { this.directoryClient.unregister(metadata); } } // // Remove data // long localCount = 0; if (!dryrun) { localCount = this.storeClient.delete(writeToken, metadata, start, end); } count += localCount; sb.setLength(0); GTSHelper.metadataToString(sb, metadata.getName(), metadata.getLabels()); if (metadata.getAttributesSize() > 0) { GTSHelper.labelsToString(sb, metadata.getAttributes()); } else { sb.append("{}"); } pw.write(sb.toString()); pw.write("\r\n"); metas.append(sb); metas.append("\n"); gts++; // Log detailed metrics for this GTS owner and app Map<String, String> labels = new HashMap<>(); labels.put(SensisionConstants.SENSISION_LABEL_OWNER, metadata.getLabels().get(Constants.OWNER_LABEL)); labels.put(SensisionConstants.SENSISION_LABEL_APPLICATION, metadata.getLabels().get(Constants.APPLICATION_LABEL)); Sensision.update( SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_DELETE_DATAPOINTS_PEROWNERAPP, labels, localCount); } } catch (Exception e) { t = e; throw e; } finally { if (null != loggingWriter) { Map<String, String> labels = new HashMap<String, String>(); labels.put(SensisionConstants.SENSISION_LABEL_ID, new String( OrderPreservingBase64.decode(dr.getId().getBytes(Charsets.US_ASCII)), Charsets.UTF_8)); labels.put(SensisionConstants.SENSISION_LABEL_TYPE, dr.getType()); Sensision.update(SensisionConstants.CLASS_WARP_DATALOG_REQUESTS_LOGGED, labels, 1); loggingWriter.close(); if (validated) { loggingFile.renameTo(new File(loggingFile.getAbsolutePath() + DatalogForwarder.DATALOG_SUFFIX)); } else { loggingFile.delete(); } } Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_DELETE_REQUESTS, sensisionLabels, 1); Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_DELETE_GTS, sensisionLabels, gts); Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_DELETE_DATAPOINTS, sensisionLabels, count); Sensision.update(SensisionConstants.SENSISION_CLASS_CONTINUUM_STANDALONE_DELETE_TIME_US, sensisionLabels, (System.nanoTime() - nano) / 1000); LoggingEvent event = LogUtil.setLoggingEventAttribute(null, LogUtil.DELETION_TOKEN, token); event = LogUtil.setLoggingEventAttribute(event, LogUtil.DELETION_SELECTOR, selector); event = LogUtil.setLoggingEventAttribute(event, LogUtil.DELETION_START, startstr); event = LogUtil.setLoggingEventAttribute(event, LogUtil.DELETION_END, endstr); event = LogUtil.setLoggingEventAttribute(event, LogUtil.DELETION_METADATA, metas.toString()); event = LogUtil.setLoggingEventAttribute(event, LogUtil.DELETION_COUNT, Long.toString(count)); event = LogUtil.setLoggingEventAttribute(event, LogUtil.DELETION_GTS, Long.toString(gts)); LogUtil.addHttpHeaders(event, request); if (null != t) { LogUtil.setLoggingEventStackTrace(null, LogUtil.STACK_TRACE, t); } LOG.info(LogUtil.serializeLoggingEvent(this.keyStore, event)); } response.setStatus(HttpServletResponse.SC_OK); }
From source file:com.palantir.atlasdb.ptobject.EncodingUtils.java
public static Long decodeNullableFixedLong(byte[] value, int offset) { if (value[offset] == 0) { return null; } else {/*from w ww . j a v a 2s . c o m*/ return Long.MIN_VALUE ^ PtBytes.toLong(value, offset + 1); } }
From source file:org.apache.hadoop.hbase.regionserver.compactions.CompactionPolicy.java
public boolean isMajorCompaction(final List<StoreFile> filesToCompact) throws IOException { boolean result = false; long mcTime = getNextMajorCompactTime(filesToCompact); if (filesToCompact == null || filesToCompact.isEmpty() || mcTime == 0) { return result; }//from w ww . j a va 2s. co m // TODO: Use better method for determining stamp of last major (HBASE-2990) long lowTimestamp = StoreUtils.getLowestTimestamp(filesToCompact); long now = System.currentTimeMillis(); if (lowTimestamp > 0l && lowTimestamp < (now - mcTime)) { // Major compaction time has elapsed. long cfTtl = this.storeConfig.getStoreFileTtl(); if (filesToCompact.size() == 1) { // Single file StoreFile sf = filesToCompact.get(0); Long minTimestamp = sf.getMinimumTimestamp(); long oldest = (minTimestamp == null) ? Long.MIN_VALUE : now - minTimestamp.longValue(); if (sf.isMajorCompaction() && (cfTtl == HConstants.FOREVER || oldest < cfTtl)) { if (LOG.isDebugEnabled()) { LOG.debug("Skipping major compaction of " + this + " because one (major) compacted file only and oldestTime " + oldest + "ms is < ttl=" + cfTtl); } } else if (cfTtl != HConstants.FOREVER && oldest > cfTtl) { LOG.debug("Major compaction triggered on store " + this + ", because keyvalues outdated; time since last major compaction " + (now - lowTimestamp) + "ms"); result = true; } } else { if (LOG.isDebugEnabled()) { LOG.debug("Major compaction triggered on store " + this + "; time since last major compaction " + (now - lowTimestamp) + "ms"); } result = true; } } return result; }
From source file:gedi.util.ArrayUtils.java
public static long[] minmax(long[] a) { long[] re = { Long.MAX_VALUE, Long.MIN_VALUE }; for (long i : a) { if (i > re[1]) re[1] = i;//from w w w . j a v a 2 s .co m else if (i < re[0]) re[0] = i; } return re; }
From source file:org.apache.cassandra.db.SystemKeyspace.java
private static Pair<ReplayPosition, Long> truncationRecordFromBlob(ByteBuffer bytes) { try {/*from w w w .java 2s . c o m*/ DataInputStream in = new DataInputStream(ByteBufferUtil.inputStream(bytes)); return Pair.create(ReplayPosition.serializer.deserialize(in), in.available() > 0 ? in.readLong() : Long.MIN_VALUE); } catch (IOException e) { throw new RuntimeException(e); } }
From source file:io.pravega.controller.task.Stream.StreamMetadataTasks.java
/** * Generate a new stream cut./*from ww w . ja v a 2 s. c o m*/ * * @param scope scope. * @param stream stream name. * @param contextOpt optional context * @return streamCut. */ public CompletableFuture<StreamCutRecord> generateStreamCut(final String scope, final String stream, final OperationContext contextOpt) { final OperationContext context = contextOpt == null ? streamMetadataStore.createContext(scope, stream) : contextOpt; final long generationTime = System.currentTimeMillis(); return streamMetadataStore.getActiveSegments(scope, stream, context, executor) .thenCompose(activeSegments -> Futures.allOfWithResults(activeSegments.stream().parallel().collect( Collectors.toMap(Segment::getNumber, x -> getSegmentOffset(scope, stream, x.getNumber()))))) .thenApply(map -> new StreamCutRecord(generationTime, Long.MIN_VALUE, ImmutableMap.copyOf(map))); }
From source file:annis.AnnisRunner.java
public void doBenchmark(String benchmarkCount) { int count = Integer.parseInt(benchmarkCount); out.println("---> executing " + benchmarks.size() + " queries " + count + " times"); AnnisRunner.OS currentOS = AnnisRunner.OS.other; try {/*from www . j ava 2 s . c o m*/ currentOS = AnnisRunner.OS.valueOf(System.getProperty("os.name").toLowerCase()); } catch (IllegalArgumentException ex) { } List<AnnisRunner.Benchmark> session = new ArrayList<AnnisRunner.Benchmark>(); // create sql + plan for each query and create count copies for each benchmark for (AnnisRunner.Benchmark benchmark : benchmarks) { if (clearCaches) { resetCaches(currentOS); } SqlGenerator<QueryData, ?> generator = getGeneratorForQueryFunction(benchmark.functionCall); benchmark.sql = getGeneratorForQueryFunction(benchmark.functionCall).toSql(benchmark.queryData); out.println("---> SQL query for: " + benchmark.functionCall); out.println(benchmark.sql); try { benchmark.plan = annisDao.explain(generator, benchmark.queryData, false); out.println("---> query plan for: " + benchmark.functionCall); out.println(benchmark.plan); } catch (RuntimeException e) { // nested DataAccessException would be better out.println("---> query plan failed for " + benchmark.functionCall); } benchmark.bestTimeInMilliseconds = Long.MAX_VALUE; benchmark.worstTimeInMilliseconds = Long.MIN_VALUE; out.println("---> running query sequentially " + SEQUENTIAL_RUNS + " times"); String options = benchmarkOptions(benchmark.queryData); for (int i = 0; i < SEQUENTIAL_RUNS; ++i) { if (i > 0) { out.print(", "); } boolean error = false; long start = new Date().getTime(); try { annisDao.executeQueryFunction(benchmark.queryData, generator); } catch (RuntimeException e) { error = true; } long end = new Date().getTime(); long runtime = end - start; benchmark.values.add(runtime); benchmark.bestTimeInMilliseconds = Math.min(benchmark.bestTimeInMilliseconds, runtime); benchmark.worstTimeInMilliseconds = Math.max(benchmark.worstTimeInMilliseconds, runtime); ++benchmark.runs; if (error) { ++benchmark.errors; } out.print(runtime + " ms"); } out.println(); out.println(benchmark.bestTimeInMilliseconds + " ms best time for '" + benchmark.functionCall + ("".equals(options) ? "'" : "' with " + options)); session.addAll(Collections.nCopies(count, benchmark)); } // clear cache again in order to treat the last query in the list equal to // the others if (clearCaches) { resetCaches(currentOS); } // shuffle the benchmark queries Collections.shuffle(session); out.println(); out.println("---> running queries in random order"); // execute the queries, record test times for (AnnisRunner.Benchmark benchmark : session) { if (benchmark.errors >= 3) { continue; } boolean error = false; SqlGenerator<QueryData, ?> generator = getGeneratorForQueryFunction(benchmark.functionCall); long start = new Date().getTime(); try { annisDao.executeQueryFunction(benchmark.queryData, generator); } catch (RuntimeException e) { error = true; } long end = new Date().getTime(); long runtime = end - start; benchmark.avgTimeInMilliseconds += runtime; benchmark.values.add(runtime); benchmark.bestTimeInMilliseconds = Math.min(benchmark.bestTimeInMilliseconds, runtime); benchmark.worstTimeInMilliseconds = Math.max(benchmark.worstTimeInMilliseconds, runtime); ++benchmark.runs; if (error) { ++benchmark.errors; } String options = benchmarkOptions(benchmark.queryData); out.println(runtime + " ms for '" + benchmark.functionCall + ("".equals(options) ? "'" : "' with " + options) + (error ? " ERROR" : "")); } // compute average runtime for each query out.println(); out.println("---> benchmark complete"); for (AnnisRunner.Benchmark benchmark : benchmarks) { benchmark.avgTimeInMilliseconds = Math .round((double) benchmark.avgTimeInMilliseconds / (double) benchmark.runs); String options = benchmarkOptions(benchmark.queryData); out.println(benchmark.getMedian() + " ms (median for " + benchmark.runs + " runs" + (benchmark.errors > 0 ? ", " + benchmark.errors + " errors)" : ")") + " for '" + benchmark.functionCall + ("".equals(options) ? "'" : "' with " + options)); } // show best runtime for each query out.println(); out.println("---> worst times"); for (AnnisRunner.Benchmark benchmark : benchmarks) { String options = benchmarkOptions(benchmark.queryData); out.println(benchmark.worstTimeInMilliseconds + " ms " + (benchmark.errors > 0 ? "(" + benchmark.errors + " errors)" : "") + " for '" + benchmark.functionCall + ("".equals(options) ? "'" : "' with " + options)); } // show best runtime for each query out.println(); out.println("---> best times"); for (AnnisRunner.Benchmark benchmark : benchmarks) { String options = benchmarkOptions(benchmark.queryData); out.println(benchmark.bestTimeInMilliseconds + " ms " + (benchmark.errors > 0 ? "(" + benchmark.errors + " errors)" : "") + " for '" + benchmark.functionCall + ("".equals(options) ? "'" : "' with " + options)); } out.println(); // CSV output try { CSVWriter csv = new CSVWriter( new FileWriterWithEncoding(new File("annis_benchmark_result.csv"), "UTF-8")); String[] header = new String[] { "corpora", "query", "median", "diff-best", "diff-worst" }; csv.writeNext(header); for (AnnisRunner.Benchmark benchmark : benchmarks) { long median = benchmark.getMedian(); String[] line = new String[5]; line[0] = StringUtils.join(benchmark.queryData.getCorpusList(), ","); line[1] = benchmark.functionCall; line[2] = "" + median; line[3] = "" + Math.abs(benchmark.bestTimeInMilliseconds - median); line[4] = "" + Math.abs(median - benchmark.worstTimeInMilliseconds); csv.writeNext(line); } csv.close(); } catch (IOException ex) { log.error(null, ex); } }
From source file:com.palantir.atlasdb.keyvalue.impl.InMemoryKeyValueService.java
private void putInternal(String tableName, Collection<Map.Entry<Cell, Value>> values, boolean doNotOverwriteWithSameValue) { Table table = getTableMap(tableName); for (Map.Entry<Cell, Value> e : values) { Cell cell = e.getKey();/*from w w w .jav a 2 s .c o m*/ byte[] row = cell.getRowName(); byte[] col = cell.getColumnName(); byte[] contents = e.getValue().getContents(); long timestamp = e.getValue().getTimestamp(); Key nextKey = table.entries.ceilingKey(new Key(row, ArrayUtils.EMPTY_BYTE_ARRAY, Long.MIN_VALUE)); if (nextKey != null && nextKey.matchesRow(row)) { // Save memory by sharing rows. row = nextKey.row; } byte[] oldContents = table.entries.putIfAbsent(new Key(row, col, timestamp), contents); if (oldContents != null && (doNotOverwriteWithSameValue || !Arrays.equals(oldContents, contents))) { throw new KeyAlreadyExistsException("We already have a value for this timestamp"); } } }
From source file:com.palantir.atlasdb.ptobject.EncodingUtils.java
public static byte[] encodeNullableFixedLong(Long value) { if (value == null) { return new byte[9]; } else {/* w w w . jav a 2 s . co m*/ return ArrayUtils.addAll(new byte[] { 1 }, PtBytes.toBytes(Long.MIN_VALUE ^ value)); } }
From source file:cz.filmtit.userspace.Session.java
/** * Terminates the session. Used in all session terminating situations (i.e. * logout, time-out, re-login). Saves the log about the session to the * database./*from w w w. j a v a 2s. c o m*/ */ private synchronized void terminate() { // the session was already terminated and is in database => skip this method if (databaseId != Long.MIN_VALUE) { return; } org.hibernate.Session session = usHibernateUtil.getSessionWithActiveTransaction(); Query query = session.createQuery("FROM USTranslationResult t WHERE t.lockedByUser = :user"); query.setParameter("user", this.getUserDatabaseId()); List list = query.list(); // Unlock all Translation Results locked by this user for (Object o : list) { USTranslationResult translationResult = (USTranslationResult) o; translationResult.setLockedByUser(null); session.save(translationResult); } session.save(this); usHibernateUtil.closeAndCommitSession(session); }