code
stringlengths
73
34.1k
label
stringclasses
1 value
private void processScript() { ScriptReaderBase scr = null; try { if (database.isFilesInJar() || fa.isStreamElement(scriptFileName)) { scr = ScriptReaderBase.newScriptReader(database, scriptFileName,...
java
private void processDataFile() { // OOo related code if (database.isStoredFileAccess()) { return; } // OOo end if (cache == null || filesReadOnly || !fa.isStreamElement(logFileName)) { return; } File file = new File...
java
private void processLog() { if (!database.isFilesInJar() && fa.isStreamElement(logFileName)) { ScriptRunner.runScript(database, logFileName, ScriptWriterBase.SCRIPT_TEXT_170); } }
java
private void restoreBackup() { if (incBackup) { restoreBackupIncremental(); return; } // in case data file cannot be deleted, reset it DataFileCache.deleteOrResetFreePos(database, fileName + ".data"); try { FileArchiver.unarchive(fileName +...
java
private void restoreBackupIncremental() { try { if (fa.isStreamElement(fileName + ".backup")) { RAShadowFile.restoreFile(fileName + ".backup", fileName + ".data"); } else { /* // this is to ensure file has been wri...
java
public void updateCatalog(String diffCmds, CatalogContext context, boolean isReplay, boolean requireCatalogDiffCmdsApplyToEE, boolean requiresNewExportGeneration) { // note this will never require snapshot isolation because the MPI has no snapshot funtionality m_executionSite.updateCatal...
java
public static Pair<AbstractTopology, ImmutableList<Integer>> mutateAddNewHosts(AbstractTopology currentTopology, Map<Integer, HostInfo> newHostInfos) { int startingPartitionId = getNextFreePartitionId(currentTopology); TopologyBuilder topologyBuilder = addPartitionsToHosts(newHostInfos, Col...
java
public static Pair<AbstractTopology, Set<Integer>> mutateRemoveHosts(AbstractTopology currentTopology, Set<Integer> removalHosts) { Set<Integer> removalPartitionIds = getPartitionIdsForHosts(currentTopology, removalHosts); return ...
java
public Set<Integer> getPartitionGroupPeers(int hostId) { Set<Integer> peers = Sets.newHashSet(); for (Partition p : hostsById.get(hostId).partitions) { peers.addAll(p.hostIds); } return peers; }
java
public static List<Collection<Integer>> sortHostIdByHGDistance(int hostId, Map<Integer, String> hostGroups) { String localHostGroup = hostGroups.get(hostId); Preconditions.checkArgument(localHostGroup != null); HAGroup localHaGroup = new HAGroup(localHostGroup); // Memorize the distanc...
java
public void reportQueued(String importerName, String procName) { StatsInfo statsInfo = getStatsInfo(importerName, procName); statsInfo.m_pendingCount.incrementAndGet(); }
java
public void reportFailure(String importerName, String procName, boolean decrementPending) { StatsInfo statsInfo = getStatsInfo(importerName, procName); if (decrementPending) { statsInfo.m_pendingCount.decrementAndGet(); } statsInfo.m_failureCount.incrementAndGet(); }
java
private void reportSuccess(String importerName, String procName) { StatsInfo statsInfo = getStatsInfo(importerName, procName); statsInfo.m_pendingCount.decrementAndGet(); statsInfo.m_successCount.incrementAndGet(); }
java
private void reportRetry(String importerName, String procName) { StatsInfo statsInfo = getStatsInfo(importerName, procName); statsInfo.m_retryCount.incrementAndGet(); }
java
public void writeBlock(byte[] block) throws IOException { if (block.length != 512) { throw new IllegalArgumentException( RB.singleton.getString(RB.BAD_BLOCK_WRITE_LEN, block.length)); } write(block, block.length); }
java
public void writePadBlocks(int blockCount) throws IOException { for (int i = 0; i < blockCount; i++) { write(ZERO_BLOCK, ZERO_BLOCK.length); } }
java
private Vector getAllTables() { Vector result = new Vector(20); try { if (cConn == null) { return null; } dbmeta = cConn.getMetaData(); String[] tableTypes = { "TABLE" }; ResultSet allTables = dbmeta.getTables(null, null, nu...
java
private int getChoosenTableIndex() { String tableName = cTables.getSelectedItem(); // System.out.println("in getChoosenTableIndex, selected Item is "+tableName); int index = getTableIndex(tableName); if (index >= 0) { // System.out.println("table found, index: " + index);...
java
private int getTableIndex(String tableName) { int index; // System.out.println("begin searching for "+tableName); for (index = 0; index < vHoldTableNames.size(); index++) { // System.out.println("in getTableIndex searching for "+tableName+", index: "+index); if (tableN...
java
private String[] getWords() { StringTokenizer tokenizer = new StringTokenizer(fSearchWords.getText()); String[] result = new String[tokenizer.countTokens()]; int i = 0; while (tokenizer.hasMoreTokens()) { result[i++] = tokenizer.nextToken(); } ...
java
private void initButtons() { // the buttons for the search form bSearchRow = new Button("Search Rows"); bNewRow = new Button("Insert New Row"); bSearchRow.addActionListener(this); bNewRow.addActionListener(this); pSearchButs = new Panel(); pSearchButs.setLa...
java
private void resetTableForms() { lForm.show(pForm, "search"); lButton.show(pButton, "search"); Vector vAllTables = getAllTables(); // fill the drop down list again // get all table names and show a drop down list of them in cTables cTables.removeAll(); for (En...
java
private ParsedSelectStmt getLeftmostSelectStmt() { assert (!m_children.isEmpty()); AbstractParsedStmt firstChild = m_children.get(0); if (firstChild instanceof ParsedSelectStmt) { return (ParsedSelectStmt) firstChild; } else { assert(firstChild instanceof ParsedUn...
java
@Override public String calculateContentDeterminismMessage() { String ans = null; for (AbstractParsedStmt child : m_children) { ans = child.getContentDeterminismMessage(); if (ans != null) { return ans; } } return null; }
java
public synchronized void rollLog() throws IOException { if (logStream != null) { this.logStream.flush(); this.logStream = null; oa = null; } }
java
public synchronized void close() throws IOException { if (logStream != null) { logStream.close(); } for (FileOutputStream log : streamsToFlush) { log.close(); } }
java
public synchronized boolean append(TxnHeader hdr, Record txn) throws IOException { if (hdr != null) { if (hdr.getZxid() <= lastZxidSeen) { LOG.warn("Current zxid " + hdr.getZxid() + " is <= " + lastZxidSeen + " for " + hdr.g...
java
private void padFile(FileOutputStream out) throws IOException { currentSize = Util.padLogFile(out, currentSize, preAllocSize); }
java
public static File[] getLogFiles(File[] logDirList,long snapshotZxid) { List<File> files = Util.sortDataDir(logDirList, "log", true); long logZxid = 0; // Find the log file that starts before or at the same time as the // zxid of the snapshot for (File f : files) { lo...
java
public long getLastLoggedZxid() { File[] files = getLogFiles(logDir.listFiles(), 0); long maxLog=files.length>0? Util.getZxidFromName(files[files.length-1].getName(),"log"):-1; // if a log file is more recent we must scan it to find // the highest zxid long zxid ...
java
public synchronized void commit() throws IOException { if (logStream != null) { logStream.flush(); } for (FileOutputStream log : streamsToFlush) { log.flush(); if (forceSync) { log.getChannel().force(false); } } whil...
java
public boolean truncate(long zxid) throws IOException { FileTxnIterator itr = new FileTxnIterator(this.logDir, zxid); PositionInputStream input = itr.inputStream; long pos = input.getPosition(); // now, truncate at the current position RandomAccessFile raf=new RandomAccessFile(it...
java
private static FileHeader readHeader(File file) throws IOException { InputStream is =null; try { is = new BufferedInputStream(new FileInputStream(file)); InputArchive ia=BinaryInputArchive.getArchive(is); FileHeader hdr = new FileHeader(); hdr.deserialize(...
java
public long getDbId() throws IOException { FileTxnIterator itr = new FileTxnIterator(logDir, 0); FileHeader fh=readHeader(itr.logFile); itr.close(); if(fh==null) throw new IOException("Unsupported Format."); return fh.getDbid(); }
java
public static void verifyForHdfsUse(String sb) throws IllegalArgumentException { Preconditions.checkArgument( sb != null && !sb.trim().isEmpty(), "null or empty hdfs endpoint" ); int mask = conversionMaskFor(sb); boolean hasDateConversion = (mask ...
java
public static void verifyForBatchUse(String sb) throws IllegalArgumentException { Preconditions.checkArgument( sb != null && !sb.trim().isEmpty(), "null or empty hdfs endpoint" ); int mask = conversionMaskFor(sb); Preconditions.checkArgument( ...
java
@Override protected void handleJSONMessage(JSONObject obj) throws Exception { hostLog.warn("SystemCatalogAgent received a JSON message, which should be impossible."); VoltTable[] results = null; sendOpsResponse(results, obj); }
java
public static <K, V> Map<K, V> constrainedMap( Map<K, V> map, MapConstraint<? super K, ? super V> constraint) { return new ConstrainedMap<K, V>(map, constraint); }
java
public static <K, V> ListMultimap<K, V> constrainedListMultimap( ListMultimap<K, V> multimap, MapConstraint<? super K, ? super V> constraint) { return new ConstrainedListMultimap<K, V>(multimap, constraint); }
java
private void validateWindowedSyntax() { // Check that the aggregate is one of the supported ones, and // that the number of aggregate parameters is right. switch (opType) { case OpTypes.WINDOWED_RANK: case OpTypes.WINDOWED_DENSE_RANK: case OpTypes.WINDOWED_ROW_NUMBER: ...
java
Result getResult(Session session) { Table table = baseTable; Result resultOut = null; RowSetNavigator generatedNavigator = null; PersistentStore store = session.sessionData.getRowStore(baseTable); if (generatedIndexes != null) { ...
java
@Override public void resolveForTable(Table table) { assert(table != null); // It MAY be that for the case in which this function is called (expression indexes), the column's // table name is not specified (and not missed?). // It is possible to "correct" that here by cribbing it fro...
java
public int setColumnIndexUsingSchema(NodeSchema inputSchema) { int index = inputSchema.getIndexOfTve(this); if (index < 0) { //* enable to debug*/ System.out.println("DEBUG: setColumnIndex miss: " + this); //* enable to debug*/ System.out.println("DEBUG: setColumnIndex candidates...
java
public String getColumnClassName(int column) throws SQLException { sourceResultSet.checkColumnBounds(column); VoltType type = sourceResultSet.table.getColumnType(column - 1); String result = type.getJdbcClass(); if (result == null) { throw SQLError.get(SQLError.TRANSLATIO...
java
public int getPrecision(int column) throws SQLException { sourceResultSet.checkColumnBounds(column); VoltType type = sourceResultSet.table.getColumnType(column - 1); Integer result = type.getTypePrecisionAndRadix()[0]; if (result == null) { result = 0; } ...
java
public int getScale(int column) throws SQLException { sourceResultSet.checkColumnBounds(column); VoltType type = sourceResultSet.table.getColumnType(column - 1); Integer result = type.getMaximumScale(); if (result == null) { result = 0; } return result; ...
java
public boolean isCaseSensitive(int column) throws SQLException { sourceResultSet.checkColumnBounds(column); VoltType type = sourceResultSet.table.getColumnType(column - 1); return type.isCaseSensitive(); }
java
public boolean isSigned(int column) throws SQLException { sourceResultSet.checkColumnBounds(column); VoltType type = sourceResultSet.table.getColumnType(column - 1); Boolean result = type.isUnsigned(); if (result == null) { // Null return value means 'not signed' as far a...
java
private AbstractPlanNode applyOptimization(WindowFunctionPlanNode plan) { assert(plan.getChildCount() == 1); assert(plan.getChild(0) != null); AbstractPlanNode child = plan.getChild(0); assert(child != null); // SP Plans which have an index which can provide // the window...
java
AbstractPlanNode convertToSerialAggregation(AbstractPlanNode aggregateNode, OrderByPlanNode orderbyNode) { assert(aggregateNode instanceof HashAggregatePlanNode); HashAggregatePlanNode hashAggr = (HashAggregatePlanNode) aggregateNode; List<AbstractExpression> groupbys = new ArrayList<>(hashAggr....
java
private final void startHeartbeat() { if (timerTask == null || HsqlTimer.isCancelled(timerTask)) { Runnable runner = new HeartbeatRunner(); timerTask = timer.schedulePeriodicallyAfter(0, HEARTBEAT_INTERVAL, runner, true); } }
java
private final void stopHeartbeat() { if (timerTask != null && !HsqlTimer.isCancelled(timerTask)) { HsqlTimer.cancel(timerTask); timerTask = null; } }
java
public final static boolean isLocked(final String path) { boolean locked = true; try { LockFile lockFile = LockFile.newLockFile(path); lockFile.checkHeartbeat(false); locked = false; } catch (Exception e) {} return locked; }
java
public static ImmutableSortedSet<String> hosts(String option) { checkArgument(option != null, "option is null"); if (option.trim().isEmpty()) { return ImmutableSortedSet.of( HostAndPort.fromParts("", Constants.DEFAULT_INTERNAL_PORT).toString()); } Splitter...
java
public static ImmutableSortedSet<String> hosts(int...ports) { if (ports.length == 0) { return ImmutableSortedSet.of( HostAndPort.fromParts("", Constants.DEFAULT_INTERNAL_PORT).toString()); } ImmutableSortedSet.Builder<String> sbld = ImmutableSortedSet.naturalOrder...
java
public ClientResponseImpl call(Object... paramListIn) { m_perCallStats = m_statsCollector.beginProcedure(); // if we're keeping track, calculate parameter size if (m_perCallStats != null) { StoredProcedureInvocation invoc = (m_txnState != null ? m_txnState.getInvocation() : null); ...
java
public boolean checkPartition(TransactionState txnState, TheHashinator hashinator) { if (m_isSinglePartition) { // can happen when a proc changes from multi-to-single after it's routed if (hashinator == null) { return false; // this will kick it back to CI for re-routing ...
java
public static boolean isProcedureStackTraceElement(String procedureName, StackTraceElement stel) { int lastPeriodPos = stel.getClassName().lastIndexOf('.'); if (lastPeriodPos == -1) { lastPeriodPos = 0; } else { ++lastPeriodPos; } // Account for inner cl...
java
public void handleUpdateDeployment(String jsonp, HttpServletRequest request, HttpServletResponse response, AuthenticationResult ar) throws IOException, ServletException { String deployment = request.getParameter("deployment"); if (deployment == null || deployment.leng...
java
public void handleRemoveUser(String jsonp, String target, HttpServletRequest request, HttpServletResponse response, AuthenticationResult ar) throws IOException, ServletException { try { DeploymentType newDeployment = CatalogUtil.getDeployment(new ByteArrayInputStr...
java
public void handleGetUsers(String jsonp, String target, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ObjectMapper mapper = new ObjectMapper(); User user = null; String[] splitTarget = target.split("/"); ...
java
public void handleGetExportTypes(String jsonp, HttpServletResponse response) throws IOException, ServletException { if (jsonp != null) { response.getWriter().write(jsonp + "("); } JSONObject exportTypes = new JSONObject(); HashSet<String> exportList = new HashSet<...
java
void createZKDirectory(String path) { try { try { m_zk.create(path, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (KeeperException e) { if (e.code() != Code.NODEEXISTS) { throw e; ...
java
public Pair<Integer, String> findRestoreCatalog() { enterRestore(); try { m_snapshotToRestore = generatePlans(); } catch (Exception e) { VoltDB.crashGlobalVoltDB(e.getMessage(), true, e); } if (m_snapshotToRestore != null) { int hostId = m_sn...
java
void enterRestore() { createZKDirectory(VoltZK.restore); createZKDirectory(VoltZK.restore_barrier); createZKDirectory(VoltZK.restore_barrier2); try { m_generatedRestoreBarrier2 = m_zk.create(VoltZK.restore_barrier2 + "/counter", null, Ids.OPEN_ACL_UNS...
java
void exitRestore() { try { m_zk.delete(m_generatedRestoreBarrier2, -1); } catch (Exception e) { VoltDB.crashLocalVoltDB("Unable to delete zk node " + m_generatedRestoreBarrier2, false, e); } if (m_callback != null) { m_callback.onSnapshotRestoreComple...
java
static SnapshotInfo consolidateSnapshotInfos(Collection<SnapshotInfo> lastSnapshot) { SnapshotInfo chosen = null; if (lastSnapshot != null) { Iterator<SnapshotInfo> i = lastSnapshot.iterator(); while (i.hasNext()) { SnapshotInfo next = i.next(); ...
java
private void sendSnapshotTxnId(SnapshotInfo toRestore) { long txnId = toRestore != null ? toRestore.txnId : 0; String jsonData = toRestore != null ? toRestore.toJSONObject().toString() : "{}"; LOG.debug("Sending snapshot ID " + txnId + " for restore to other nodes"); try { m_...
java
private void sendLocalRestoreInformation(Long max, Set<SnapshotInfo> snapshots) { String jsonData = serializeRestoreInformation(max, snapshots); String zkNode = VoltZK.restore + "/" + m_hostId; try { m_zk.create(zkNode, jsonData.getBytes(StandardCharsets.UTF_8), ...
java
private Long deserializeRestoreInformation(List<String> children, Map<String, Set<SnapshotInfo>> snapshotFragments) throws Exception { try { int recover = m_action.ordinal(); Long clStartTxnId = null; for (String node : children) { //This might...
java
private void changeState() { if (m_state == State.RESTORE) { fetchSnapshotTxnId(); exitRestore(); m_state = State.REPLAY; /* * Add the interest here so that we can use the barriers in replay * agent to synchronize. */ ...
java
private Map<String, Snapshot> getSnapshots() { /* * Use the individual snapshot directories instead of voltroot, because * they can be set individually */ Map<String, SnapshotPathType> paths = new HashMap<String, SnapshotPathType>(); if (VoltDB.instance().getConfig().m...
java
@Override public CountDownLatch snapshotCompleted(SnapshotCompletionEvent event) { if (!event.truncationSnapshot || !event.didSucceed) { VoltDB.crashGlobalVoltDB("Failed to truncate command logs by snapshot", false, null); } else { m_trunc...
java
void shutdown() throws InterruptedException { m_shouldStop = true; if (m_thread != null) { m_selector.wakeup(); m_thread.join(); } }
java
Connection registerChannel( final SocketChannel channel, final InputHandler handler, final int interestOps, final ReverseDNSPolicy dns, final CipherExecutor cipherService, final SSLEngine sslEngine) throws IOException { synchronized(channe...
java
Future<?> unregisterChannel (Connection c) { FutureTask<Object> ft = new FutureTask<Object>(getUnregisterRunnable(c), null); m_tasks.offer(ft); m_selector.wakeup(); return ft; }
java
void addToChangeList(final VoltPort port, final boolean runFirst) { if (runFirst) { m_tasks.offer(new Runnable() { @Override public void run() { callPort(port); } }); } else { m_tasks.offer(new Runnab...
java
protected void invokeCallbacks(ThreadLocalRandom r) { final Set<SelectionKey> selectedKeys = m_selector.selectedKeys(); final int keyCount = selectedKeys.size(); int startInx = r.nextInt(keyCount); int itInx = 0; Iterator<SelectionKey> it = selectedKeys.iterator(); while(...
java
public static String path(String... components) { String path = components[0]; for (int i=1; i < components.length; i++) { path = ZKUtil.joinZKPath(path, components[i]); } return path; }
java
private String getSegmentFileName(long currentId, long previousId) { return PbdSegmentName.createName(m_nonce, currentId, previousId, false); }
java
private long getPreviousSegmentId(File file) { PbdSegmentName segmentName = PbdSegmentName.parseFile(m_usageSpecificLog, file); if (segmentName.m_result != PbdSegmentName.Result.OK) { throw new IllegalStateException("Invalid file name: " + file.getName()); } return segmentNam...
java
private void deleteStalePbdFile(File file) throws IOException { try { PBDSegment.setFinal(file, false); if (m_usageSpecificLog.isDebugEnabled()) { m_usageSpecificLog.debug("Segment " + file.getName() + " (final: " + PBDSegment.isFinal(file) + "), will be c...
java
private void recoverSegment(long segmentIndex, long segmentId, PbdSegmentName segmentName) throws IOException { PBDSegment segment; if (segmentName.m_quarantined) { segment = new PbdQuarantinedSegment(segmentName.m_file, segmentIndex, segmentId); } else { segment = newSeg...
java
int numOpenSegments() { int numOpen = 0; for (PBDSegment segment : m_segments.values()) { if (!segment.isClosed()) { numOpen++; } } return numOpen; }
java
public CacheBuilder<K, V> expireAfterWrite(long duration, TimeUnit unit) { checkState( expireAfterWriteNanos == UNSET_INT, "expireAfterWrite was already set to %s ns", expireAfterWriteNanos); checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit); this.exp...
java
public void revoke(Grantee role) { if (!hasRoleDirect(role)) { throw Error.error(ErrorCode.X_0P503, role.getNameString()); } roles.remove(role); }
java
private OrderedHashSet addGranteeAndRoles(OrderedHashSet set) { Grantee candidateRole; set.add(this); for (int i = 0; i < roles.size(); i++) { candidateRole = (Grantee) roles.get(i); if (!set.contains(candidateRole)) { candidateRole.addGranteeAndRoles(...
java
public void addAllRoles(HashMap map) { for (int i = 0; i < roles.size(); i++) { Grantee role = (Grantee) roles.get(i); map.put(role.granteeName.name, role.roles); } }
java
void clearPrivileges() { roles.clear(); directRightsMap.clear(); grantedRightsMap.clear(); fullRightsMap.clear(); isAdmin = false; }
java
boolean updateNestedRoles(Grantee role) { boolean hasNested = false; if (role != this) { for (int i = 0; i < roles.size(); i++) { Grantee currentRole = (Grantee) roles.get(i); hasNested |= currentRole.updateNestedRoles(role); } } ...
java
void addToFullRights(HashMap map) { Iterator it = map.keySet().iterator(); while (it.hasNext()) { Object key = it.next(); Right add = (Right) map.get(key); Right existing = (Right) fullRightsMap.get(key); if (existing == null) { ...
java
public void toLeftJoin() { assert((m_leftNode != null && m_rightNode != null) || (m_leftNode == null && m_rightNode == null)); if (m_leftNode == null && m_rightNode == null) { // End of recursion return; } // recursive calls if (m_leftNode instanceof Branc...
java
@Override protected void extractSubTree(List<JoinNode> leafNodes) { JoinNode[] children = {m_leftNode, m_rightNode}; for (JoinNode child : children) { // Leaf nodes don't have a significant join type, // test for them first and never attempt to start a new tree at a leaf. ...
java
@Override public boolean hasOuterJoin() { assert(m_leftNode != null && m_rightNode != null); return m_joinType != JoinType.INNER || m_leftNode.hasOuterJoin() || m_rightNode.hasOuterJoin(); }
java
@Override public void extractEphemeralTableQueries(List<StmtEphemeralTableScan> scans) { if (m_leftNode != null) { m_leftNode.extractEphemeralTableQueries(scans); } if (m_rightNode != null) { m_rightNode.extractEphemeralTableQueries(scans); } }
java
@Override public boolean allInnerJoins() { return m_joinType == JoinType.INNER && (m_leftNode == null || m_leftNode.allInnerJoins()) && (m_rightNode == null || m_rightNode.allInnerJoins()); }
java
public static void apply(CompiledPlan plan, DeterminismMode detMode) { if (detMode == DeterminismMode.FASTER) { return; } if (plan.hasDeterministicStatement()) { return; } AbstractPlanNode planGraph = plan.rootPlanGraph; if (planGraph.isOrderDe...
java
public void updateLastSeenUniqueIds(VoltMessage message) { long sequenceWithUniqueId = Long.MIN_VALUE; boolean commandLog = (message instanceof TransactionInfoBaseMessage && (((TransactionInfoBaseMessage)message).isForReplay())); boolean sentinel = message instanceof MultiP...
java
public void parseRestoreResultRow(VoltTable vt) { RestoreResultKey key = new RestoreResultKey( (int)vt.getLong("HOST_ID"), (int)vt.getLong("PARTITION_ID"), vt.getString("TABLE")); if (containsKey(key)) { get(key).mergeData(vt.getString("RES...
java
public static <E extends Comparable> int binarySearch( List<? extends E> list, E e, KeyPresentBehavior presentBehavior, KeyAbsentBehavior absentBehavior) { checkNotNull(e); return binarySearch(list, e, Ordering.natural(), presentBehavior, absentBehavior); }
java