code
stringlengths
73
34.1k
label
stringclasses
1 value
private boolean startsWithCustomRoot(String path) { for (Enumeration<String> it = customRoots.elements(); it != null && it.hasMoreElements();) { if (path.startsWith(it.nextElement())) { return true; } } return false; }
java
public boolean isDirectoryOrLinkedDirectory(SftpFile file) throws SftpStatusException, SshException { return file.isDirectory() || (file.isLink() && stat(file.getAbsolutePath()).isDirectory()); }
java
public SftpFileAttributes get(String remote, String local, boolean resume) throws FileNotFoundException, SftpStatusException, SshException, TransferCancelledException { return get(remote, local, null, resume); }
java
public InputStream getInputStream(String remotefile, long position) throws SftpStatusException, SshException { String remotePath = resolveRemotePath(remotefile); sftp.getAttributes(remotePath); return new SftpFileInputStream(sftp.openFile(remotePath, SftpSubsystemChannel.OPEN_READ), position); }
java
public SftpFileAttributes get(String remote, OutputStream local, long position) throws SftpStatusException, SshException, TransferCancelledException { return get(remote, local, null, position); }
java
public OutputStream getOutputStream(String remotefile) throws SftpStatusException, SshException { String remotePath = resolveRemotePath(remotefile); return new SftpFileOutputStream(sftp.openFile(remotePath, SftpSubsystemChannel.OPEN_CREATE | SftpSubsystemChannel.OPEN_TRUNCATE | SftpSubsystemChan...
java
public void put(InputStream in, String remote, long position) throws SftpStatusException, SshException, TransferCancelledException { put(in, remote, null, position); }
java
public void rm(String path, boolean force, boolean recurse) throws SftpStatusException, SshException { String actual = resolveRemotePath(path); SftpFileAttributes attrs = null; attrs = sftp.getAttributes(actual); SftpFile file; if (attrs.isDirectory()) { SftpFile[] list = ls(path); if (!force &&...
java
public String getAbsolutePath(String path) throws SftpStatusException, SshException { String actual = resolveRemotePath(path); return sftp.getAbsolutePath(actual); }
java
public void putFiles(String local, String remote, FileTransferProgress progress, boolean resume) throws FileNotFoundException, SftpStatusException, SshException, TransferCancelledException { putFileMatches(local, remote, progress, resume); }
java
public int authenticate(AuthenticationClient auth, String servicename) throws SshException { try { auth.authenticate(this, servicename); readMessage(); transport .disconnect(TransportProtocol.PROTOCOL_ERROR, "Unexpected response received from Authentication Protocol"); throw new SshExceptio...
java
public void sendRequest(String username, String servicename, String methodname, byte[] requestdata) throws SshException { ByteArrayWriter msg = new ByteArrayWriter(); try { msg.write(SSH_MSG_USERAUTH_REQUEST); msg.writeString(username); msg.writeString(servicename); msg.writeString(methodname); ...
java
public static UnsignedInteger32 add(UnsignedInteger32 x, UnsignedInteger32 y) { return new UnsignedInteger32(x.longValue() + y.longValue()); }
java
public boolean setAuthenticationMethod(int methodId, Authentication method) { if (methodId < 0 || methodId > 255) return false; if (method == null) { // Want to remove a particular method return (authMethods.remove(new Integer(methodId)) != null); } else {// Add the method, or rewrite old one authMeth...
java
public Authentication getAuthenticationMethod(int methodId) { Object method = authMethods.get(new Integer(methodId)); if (method == null) return null; return (Authentication) method; }
java
public void installCBCCiphers(ComponentFactory ciphers) { if (testJCECipher("3des-cbc", TripleDesCbc.class)) { ciphers.add("3des-cbc", TripleDesCbc.class); } if (testJCECipher("blowfish-cbc", BlowfishCbc.class)) { ciphers.add("blowfish-cbc", BlowfishCbc.class); } if (testJCECipher("aes128-cbc", AES128...
java
public void installArcFourCiphers(ComponentFactory ciphers) { if (testJCECipher("arcfour", ArcFour.class)) { ciphers.add("arcfour", ArcFour.class); } if (testJCECipher("arcfour128", ArcFour128.class)) { ciphers.add("arcfour128", ArcFour128.class); } if (testJCECipher("arcfour256", ArcFour256.class)...
java
public Event addAttribute(String key, Object value) { eventAttributes.put(key, (value == null ? "null" : value)); return this; }
java
public InetAddress getInetAddress(){ if(remoteIP == null){ try{ remoteIP = InetAddress.getByName(remoteHost); }catch(UnknownHostException e){ return null; } } return remoteIP; }
java
public void run(Iterable<Item> items, Context cx) { Function prepareFunc = (Function) indexResults.getPrototype().get("prepare", indexResults); prepareFunc.call(cx, scope, indexResults, NO_ARGS); Object args[] = new Object[] { null, mapFunction }; for (Item item : items) { a...
java
public static Indexer create(String mapTxt) { Context cx = Context.enter(); try { return new Indexer(mapTxt, cx); } finally { Context.exit(); } }
java
public boolean isAuthorizedForBucket(AuthContext ctx, Bucket bucket) { if (ctx.getUsername().equals(adminName)) { return ctx.getPassword().equals(adminPass); } if (bucket.getName().equals(ctx.getUsername())) { return bucket.getPassword().equals(ctx.getPassword()); ...
java
public boolean isAdministrator(AuthContext ctx) { return ctx.getUsername() != null && ctx.getUsername().equals(adminName) && ctx.getPassword() != null && ctx.getPassword().equals(adminPass); }
java
public static BinaryResponse create(BinaryCommand command, MemcachedServer server, ErrorCode errOk, ErrorCode errNotSupp) { if (!server.isCccpEnabled()) { return new BinaryResponse(command, errNotSupp); } String config = server.getBucket().getJSON(); config = config.replaceA...
java
public void loadDocuments(String docsFile) throws IOException { ZipFile zipFile = new ZipFile(docsFile); Enumeration<? extends ZipEntry> entries = zipFile.entries(); int numDocs = 0; int numDesigns = 0; while (entries.hasMoreElements()) { ZipEntry ent = entries.next...
java
public static void main(String[] args) throws Exception { String input = args[0]; File outputFile = new File(input.replace(".zip", "") + ".serialized.xz"); // Get the base name FileOutputStream fos = new FileOutputStream(outputFile); LZMA2Options options = new LZMA2Options(9); ...
java
public String processInput(String input) { JsonObject object; try { object = gs.fromJson(input, JsonObject.class); } catch (Throwable t) { return "{ \"status\" : \"fail\", \"error\" : \"Failed to parse input\" }"; } String command = object.get("command")...
java
public static void main(String[] args) { try { VBucketInfo vbi[] = new VBucketInfo[1024]; for (int ii = 0; ii < vbi.length; ++ii) { vbi[ii] = new VBucketInfo(); } MemcachedServer server = new MemcachedServer(null, null, 11211, vbi, false); ...
java
public static DesignDocument create(String body, String name) throws DesignParseException { DesignDocument doc = new DesignDocument(body); doc.id = "_design/" + name; doc.load(); return doc; }
java
public List<Entry> parse(String[] argv) { optind = -1; List<Entry> ret = new ArrayList<Entry>(); int idx = 0; while (idx < argv.length) { if (argv[idx].equals("--")) { // End of options! ++idx; break; } ...
java
public static Bucket create(CouchbaseMock mock, BucketConfiguration config) throws IOException { switch (config.type) { case MEMCACHED: return new MemcachedBucket(mock, config); case COUCHBASE: return new CouchbaseBucket(mock, config); ...
java
protected Map<String,Object> getCommonConfig() { Map<String,Object> mm = new HashMap<String, Object>(); mm.put("replicaNumber", numReplicas); Map<String,Object> ramQuota = new HashMap<String, Object>(); ramQuota.put("rawRAM", 1024 * 1024 * 100); ramQuota.put("ram", 1024 * 1024 * ...
java
public void respawn(int index) { configurationRwLock.writeLock().lock(); try { if (index >= 0 && index < servers.length) { servers[index].startup(); } rebalance(); } finally { Info.incrementConfigRevision(); configuratio...
java
final void rebalance() { // Let's start distribute the vbuckets across the servers configurationRwLock.writeLock().lock(); try { Info.incrementConfigRevision(); List<MemcachedServer> nodes = activeServers(); for (int ii = 0; ii < numVBuckets; ++ii) { ...
java
public static JsonObject getJsonQuery(URL url) throws MalformedURLException { String query = url.getQuery(); JsonObject payload = new JsonObject(); JsonParser parser = new JsonParser(); if (query == null) { return null; } for (String kv : query.split("&")) {...
java
public static Map<String,String> getQueryParams(String s) throws MalformedURLException { Map<String,String> params = new HashMap<String, String>(); for (String kv : s.split("&")) { String[] parts = kv.split("="); if (parts.length != 2) { throw new MalformedURLExc...
java
public static void makeStringResponse(HttpResponse response, String s) { StringEntity entity = new StringEntity(s, ContentType.TEXT_PLAIN); entity.setContentEncoding("utf-8"); response.setEntity(entity); }
java
public static void makeResponse(HttpResponse response, String msg, int status) { response.setStatusCode(status); makeStringResponse(response, msg); }
java
public static void make400Response(HttpResponse response, String msg) { makeResponse(response, msg, HttpStatus.SC_BAD_REQUEST); }
java
public static void bailResponse(HttpContext cx, HttpResponse response) throws IOException, HttpException { HttpServerConnection conn = getConnection(cx); conn.sendResponseHeader(response); conn.sendResponseEntity(response); conn.flush(); }
java
public static AuthContext getAuth(HttpContext cx, HttpRequest req) throws IOException { AuthContext auth = (AuthContext) cx.getAttribute(HttpServer.CX_AUTH); if (auth == null) { Header authHdr = req.getLastHeader(HttpHeaders.AUTHORIZATION); if (authHdr == null) { ...
java
public static Reducer create(String txt) { Context cx = Context.enter(); try { return new Reducer(txt, cx); } finally { Context.exit(); } }
java
public void stopServer() { shouldRun = false; try { listener.close(); } catch (IOException ex) { // Don't care } while (true) { synchronized (allWorkers) { if (allWorkers.isEmpty()) { break; }...
java
public static void defineDesignDocument(CouchbaseMock mock, String designName, String contents, String bucketName) throws IOException { URL url = getDesignURL(mock, designName, bucketName); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); setAuthHeaders(mock, bucketName, conn);...
java
private static void sendHelpText(HttpResponse response, int code) throws IOException { HandlerUtil.makeStringResponse(response, MockHelpCommandHandler.getIndentedHelp()); response.setStatusCode(code); }
java
public void write(ByteBuffer bb, VBucketCoordinates coords) { if (!enabled) { return; } bb.putLong(24, coords.getUuid()); bb.putLong(32, coords.getSeqno()); }
java
public void startHarakiriMonitor(InetSocketAddress address, boolean terminate) throws IOException { if (terminate) { harakiriMonitor.setTemrinateAction(new Callable() { @Override public Object call() throws Exception { System.exit(1); ...
java
private static BucketConfiguration createDefaultConfig(String hostname, int numNodes, int bucketStartPort, int numVBuckets, int numReplicas) { BucketConfiguration defaultConfig = new BucketConfiguration(); defaultConfig.type = BucketType.COUCHBASE; defaultConfig.hostname = hostname; defa...
java
public int getCarrierPort(String bucketName) { Bucket bucket = buckets.get(bucketName); if (null == bucket) { // Buckets are created when the mock is started. Calling getCarrierPort() // before the mock has been started makes no sense. throw new RuntimeException("Buck...
java
public void createBucket(BucketConfiguration config) throws BucketAlreadyExistsException, IOException { if (!config.validate()) { throw new IllegalArgumentException("Invalid bucket configuration"); } synchronized (buckets) { if (buckets.containsKey(config.name)) { ...
java
public void removeBucket(String name) throws FileNotFoundException { Bucket bucket; synchronized (buckets) { if (!buckets.containsKey(name)) { throw new FileNotFoundException("No such bucket: "+ name); } bucket = buckets.remove(name); } ...
java
private void start(String docsFile, String monitorAddress, boolean useBeerSample) throws IOException { try { if (port == 0) { ServerSocketChannel ch = ServerSocketChannel.open(); ch.socket().bind(new InetSocketAddress(0)); port = ch.socket().getLocalPo...
java
public void run() throws Exception { // Send the initial command: client.sendRequest(cmd); long endTime = System.currentTimeMillis() + spec.getMaxDuration(); // Wait until the 'after' time Thread.sleep(spec.getAfter()); int numAttempts = 0; long now = System.cu...
java
public void step() throws IOException { if (closed) { throw new ClosedChannelException(); } if (input.position() == header.length) { if (command == null) { command = CommandFactory.create(input); } if (command.complete()) { ...
java
boolean hasOutput() { if (pending == null) { return false; } if (pending.isEmpty()) { return false; } if (!pending.get(0).hasRemaining()) { return false; } return true; }
java
public void returnOutputContext(OutputContext ctx) { List<ByteBuffer> remaining = ctx.releaseRemaining(); if (pending == null) { pending = remaining; } else { List<ByteBuffer> tmp = pending; pending = remaining; pending.addAll(tmp); } }
java
void setSupportedFeatures(boolean[] input) { if (input.length != supportedFeatures.length) { throw new IllegalArgumentException("Bad features length!"); } // Scan through all other features and disable them unless they are supported for (int i = 0; i < input.length; i++) { ...
java
public ByteBuffer[] getIov() { if (buffers.size() == 1) { singleArray[0] = buffers.get(0); return singleArray; } return buffers.toArray(new ByteBuffer[buffers.size()]); }
java
public OutputContext getSlice(int limit) { List<ByteBuffer> newBufs = new LinkedList<ByteBuffer>(); ByteBuffer buf = ByteBuffer.allocate(limit); Iterator<ByteBuffer> iter = buffers.iterator(); while (iter.hasNext() && buf.position() < buf.limit()) { ByteBuffer cur = iter.nex...
java
public void updateBytesSent(long num) { Iterator<ByteBuffer> iter = buffers.iterator(); while (iter.hasNext()) { ByteBuffer cur = iter.next(); if (cur.hasRemaining()) { break; } iter.remove(); } }
java
public List<ByteBuffer> releaseRemaining() { List<ByteBuffer> ret = buffers; buffers = null; return ret; }
java
private MutationStatus incrCoords(KeySpec ks) { final StorageVBucketCoordinates curCoord; synchronized (vbCoords) { curCoord = vbCoords[ks.vbId]; } long seq = curCoord.incrSeqno(); long uuid = curCoord.getUuid(); VBucketCoordinates coord = new BasicVBucketCoo...
java
void forceStorageMutation(Item itm, VBucketCoordinates coords) { forceMutation(itm.getKeySpec().vbId, itm, coords, false); }
java
void forceDeleteMutation(Item itm, VBucketCoordinates coords) { forceMutation(itm.getKeySpec().vbId, itm, coords, true); }
java
public static int convertExpiryTime(int original) { if (original == 0) { return original; } else if (original > THIRTY_DAYS) { return original + (int)Info.getClockOffset(); } return (int)((new Date().getTime() / 1000) + original + Info.getClockOffset()); }
java
public static <T> T decode(String json, Class<T> cls) { return GSON.fromJson(json, cls); }
java
@SuppressWarnings("unchecked") public static Map<String,Object> decodeAsMap(String json) { return decode(json, HashMap.class); }
java
public Map<String,Object> rowAt(int ix) { return (Map<String,Object>) rows.get(ix); }
java
public String executeRaw(Iterable<Item> items, Configuration config) throws QueryExecutionException { if (config == null) { config = new Configuration(); } Context cx = Context.enter(); Scriptable scope = cx.initStandardObjects(); NativeObject configObject = config.t...
java
public synchronized ThriftClient getThriftClient() { if (mode.api != ConnectionAPI.THRIFT_SMART) return getSimpleThriftClient(); if (tclient == null) tclient = getSmartThriftClient(); return tclient; }
java
public String[] getEndpointInfo(InetAddress endpoint) { String[] rawEndpointInfo = getRawEndpointInfo(endpoint); if (rawEndpointInfo == null) throw new RuntimeException("Unknown host " + endpoint + " with no default configured"); return rawEndpointInfo; }
java
public String getDatacenter(InetAddress endpoint) { String[] info = getEndpointInfo(endpoint); assert info != null : "No location defined for endpoint " + endpoint; return info[0]; }
java
public String getRack(InetAddress endpoint) { String[] info = getEndpointInfo(endpoint); assert info != null : "No location defined for endpoint " + endpoint; return info[1]; }
java
public void setPartitionFilter(Expression partitionFilter) throws IOException { UDFContext context = UDFContext.getUDFContext(); Properties property = context.getUDFProperties(AbstractCassandraStorage.class); property.setProperty(PARTITION_FILTER_SIGNATURE, indexExpressionsToString(filterToI...
java
public void putNext(Tuple t) throws IOException { /* We support two cases for output: First, the original output: (key, (name, value), (name,value), {(name,value)}) (tuples or bag is optional) For supers, we only accept the original output. */ if (t.size(...
java
private void writeColumnsFromTuple(ByteBuffer key, Tuple t, int offset) throws IOException { ArrayList<Mutation> mutationList = new ArrayList<Mutation>(); for (int i = offset; i < t.size(); i++) { if (t.getType(i) == DataType.BAG) writeColumnsFromBag(key, (DataBag...
java
private Mutation mutationFromTuple(Tuple t) throws IOException { Mutation mutation = new Mutation(); if (t.get(1) == null) { if (allow_deletes) { mutation.deletion = new Deletion(); mutation.deletion.predicate = new org.apache.cassandra...
java
private void writeColumnsFromBag(ByteBuffer key, DataBag bag) throws IOException { List<Mutation> mutationList = new ArrayList<Mutation>(); for (Tuple pair : bag) { Mutation mutation = new Mutation(); if (DataType.findType(pair.get(1)) == DataType.BAG) // supercolumn ...
java
private void writeMutations(ByteBuffer key, List<Mutation> mutations) throws IOException { try { writer.write(key, mutations); } catch (InterruptedException e) { throw new IOException(e); } }
java
private List<IndexExpression> filterToIndexExpressions(Expression expression) throws IOException { List<IndexExpression> indexExpressions = new ArrayList<IndexExpression>(); Expression.BinaryExpression be = (Expression.BinaryExpression)expression; ByteBuffer name = ByteBuffer.wrap(be.getLhs(...
java
private static String indexExpressionsToString(List<IndexExpression> indexExpressions) throws IOException { assert indexExpressions != null; // oh, you thought cfdefToString was awful? IndexClause indexClause = new IndexClause(); indexClause.setExpressions(indexExpressions); ...
java
private static List<IndexExpression> indexExpressionsFromString(String ie) throws IOException { assert ie != null; TDeserializer deserializer = new TDeserializer(new TBinaryProtocol.Factory()); IndexClause indexClause = new IndexClause(); try { deserializer.deseri...
java
private List<IndexExpression> getIndexExpressions() throws IOException { UDFContext context = UDFContext.getUDFContext(); Properties property = context.getUDFProperties(AbstractCassandraStorage.class); if (property.getProperty(PARTITION_FILTER_SIGNATURE) != null) return indexExpr...
java
protected List<ColumnDef> getColumnMetadata(Cassandra.Client client) throws TException, CharacterCodingException, InvalidRequestException, ConfigurationException { return getColumnMeta(client, true, true); }
java
private Tuple keyToTuple(ByteBuffer key, CfDef cfDef, AbstractType comparator) throws IOException { Tuple tuple = TupleFactory.getInstance().newTuple(1); addKeyToTuple(tuple, key, cfDef, comparator); return tuple; }
java
private void addKeyToTuple(Tuple tuple, ByteBuffer key, CfDef cfDef, AbstractType comparator) throws IOException { if( comparator instanceof AbstractCompositeType ) { setTupleValue(tuple, 0, composeComposite((AbstractCompositeType)comparator,key)); } else { ...
java
public Iterator<RangeTombstone> rangeIterator() { return ranges == null ? Iterators.<RangeTombstone>emptyIterator() : ranges.iterator(); }
java
public BooleanConditionBuilder must(ConditionBuilder... conditionBuilders) { if (must == null) { must = new ArrayList<>(conditionBuilders.length); } for (ConditionBuilder conditionBuilder : conditionBuilders) { must.add(conditionBuilder.build()); } return ...
java
public BooleanConditionBuilder should(ConditionBuilder... conditionBuilders) { if (should == null) { should = new ArrayList<>(conditionBuilders.length); } for (ConditionBuilder conditionBuilder : conditionBuilders) { should.add(conditionBuilder.build()); } ...
java
public BooleanConditionBuilder not(ConditionBuilder... conditionBuilders) { if (not == null) { not = new ArrayList<>(conditionBuilders.length); } for (ConditionBuilder conditionBuilder : conditionBuilders) { not.add(conditionBuilder.build()); } return this...
java
public Schema load(KSMetaData keyspaceDef) { for (CFMetaData cfm : keyspaceDef.cfMetaData().values()) load(cfm); setKeyspaceDefinition(keyspaceDef); return this; }
java
public void storeKeyspaceInstance(Keyspace keyspace) { if (keyspaceInstances.containsKey(keyspace.getName())) throw new IllegalArgumentException(String.format("Keyspace %s was already initialized.", keyspace.getName())); keyspaceInstances.put(keyspace.getName(), keyspace); }
java
public CFMetaData getCFMetaData(String keyspaceName, String cfName) { assert keyspaceName != null; KSMetaData ksm = keyspaces.get(keyspaceName); return (ksm == null) ? null : ksm.cfMetaData().get(cfName); }
java
public CFMetaData getCFMetaData(UUID cfId) { Pair<String,String> cf = getCF(cfId); return (cf == null) ? null : getCFMetaData(cf.left, cf.right); }
java
public Map<String, CFMetaData> getKeyspaceMetaData(String keyspaceName) { assert keyspaceName != null; KSMetaData ksm = keyspaces.get(keyspaceName); assert ksm != null; return ksm.cfMetaData(); }
java
public void purge(CFMetaData cfm) { cfIdMap.remove(Pair.create(cfm.ksName, cfm.cfName)); cfm.markPurged(); }
java
public void updateVersion() { try { MessageDigest versionDigest = MessageDigest.getInstance("MD5"); for (Row row : SystemKeyspace.serializedSchema()) { if (invalidSchemaRow(row) || ignoredSchemaRow(row)) continue; ...
java
public boolean signal() { if (!hasWaiters()) return false; while (true) { RegisteredSignal s = queue.poll(); if (s == null || s.signal() != null) return s != null; } }
java
public void signalAll() { if (!hasWaiters()) return; // to avoid a race where the condition is not met and the woken thread managed to wait on the queue before // we finish signalling it all, we pick a random thread we have woken-up and hold onto it, so that if we encounter ...
java
public int getWaiting() { if (!hasWaiters()) return 0; Iterator<RegisteredSignal> iter = queue.iterator(); int count = 0; while (iter.hasNext()) { Signal next = iter.next(); if (!next.isCancelled()) count++; } ...
java