_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q20300
TmdbAccount.getAccount
train
public Account getAccount(String sessionId) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.SESSION_ID, sessionId); URL url = new ApiUrl(apiKey, MethodBase.ACCOUNT).buildUrl(parameters); String webpage = httpTools.getRequest(url); try { return MAPPER.readValue(webpage, Account.class); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get Account", url, ex); } }
java
{ "resource": "" }
q20301
TmdbAccount.modifyWatchList
train
public StatusCode modifyWatchList(String sessionId, int accountId, MediaType mediaType, Integer movieId, boolean addToWatchlist) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.SESSION_ID, sessionId); parameters.add(Param.ID, accountId); String jsonBody = new PostTools() .add(PostBody.MEDIA_TYPE, mediaType.toString().toLowerCase()) .add(PostBody.MEDIA_ID, movieId) .add(PostBody.WATCHLIST, addToWatchlist) .build(); URL url = new ApiUrl(apiKey, MethodBase.ACCOUNT).subMethod(MethodSub.WATCHLIST).buildUrl(parameters); String webpage = httpTools.postRequest(url, jsonBody); try { return MAPPER.readValue(webpage, StatusCode.class); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to modify watch list", url, ex); } }
java
{ "resource": "" }
q20302
TmdbCompanies.getCompanyInfo
train
public Company getCompanyInfo(int companyId) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, companyId); URL url = new ApiUrl(apiKey, MethodBase.COMPANY).buildUrl(parameters); String webpage = httpTools.getRequest(url); try { return MAPPER.readValue(webpage, Company.class); } catch (IOException ex) { throw new MovieDbException(ApiExceptionType.MAPPING_FAILED, "Failed to get company information", url, ex); } }
java
{ "resource": "" }
q20303
TmdbTV.getTVAlternativeTitles
train
public ResultList<AlternativeTitle> getTVAlternativeTitles(int tvID) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, tvID); URL url = new ApiUrl(apiKey, MethodBase.TV).subMethod(MethodSub.ALT_TITLES).buildUrl(parameters); WrapperGenericList<AlternativeTitle> wrapper = processWrapper(getTypeReference(AlternativeTitle.class), url, "alternative titles"); return wrapper.getResultsList(); }
java
{ "resource": "" }
q20304
TmdbTV.getTVChanges
train
public ResultList<ChangeKeyItem> getTVChanges(int tvID, String startDate, String endDate) throws MovieDbException { return getMediaChanges(tvID, startDate, endDate); }
java
{ "resource": "" }
q20305
TmdbTV.getTVContentRatings
train
public ResultList<ContentRating> getTVContentRatings(int tvID) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, tvID); URL url = new ApiUrl(apiKey, MethodBase.TV).subMethod(MethodSub.CONTENT_RATINGS).buildUrl(parameters); WrapperGenericList<ContentRating> wrapper = processWrapper(getTypeReference(ContentRating.class), url, "content rating"); return wrapper.getResultsList(); }
java
{ "resource": "" }
q20306
TmdbTV.getTVKeywords
train
public ResultList<Keyword> getTVKeywords(int tvID) throws MovieDbException { TmdbParameters parameters = new TmdbParameters(); parameters.add(Param.ID, tvID); URL url = new ApiUrl(apiKey, MethodBase.TV).subMethod(MethodSub.KEYWORDS).buildUrl(parameters); WrapperGenericList<Keyword> wrapper = processWrapper(getTypeReference(Keyword.class), url, "keywords"); return wrapper.getResultsList(); }
java
{ "resource": "" }
q20307
FullscreenVideoView.init
train
protected void init() { Log.d(TAG, "init"); if (isInEditMode()) return; this.mediaPlayer = null; this.shouldAutoplay = false; this.fullscreen = false; this.initialConfigOrientation = -1; this.videoIsReady = false; this.surfaceIsReady = false; this.initialMovieHeight = -1; this.initialMovieWidth = -1; this.setBackgroundColor(Color.BLACK); initObjects(); }
java
{ "resource": "" }
q20308
FullscreenVideoView.release
train
protected void release() { Log.d(TAG, "release"); releaseObjects(); if (this.mediaPlayer != null) { this.mediaPlayer.setOnBufferingUpdateListener(null); this.mediaPlayer.setOnPreparedListener(null); this.mediaPlayer.setOnErrorListener(null); this.mediaPlayer.setOnSeekCompleteListener(null); this.mediaPlayer.setOnCompletionListener(null); this.mediaPlayer.setOnInfoListener(null); this.mediaPlayer.setOnVideoSizeChangedListener(null); this.mediaPlayer.release(); this.mediaPlayer = null; } this.currentState = State.END; }
java
{ "resource": "" }
q20309
FullscreenVideoView.initObjects
train
protected void initObjects() { Log.d(TAG, "initObjects"); if (this.mediaPlayer == null) { this.mediaPlayer = new MediaPlayer(); this.mediaPlayer.setOnInfoListener(this); this.mediaPlayer.setOnErrorListener(this); this.mediaPlayer.setOnPreparedListener(this); this.mediaPlayer.setOnCompletionListener(this); this.mediaPlayer.setOnSeekCompleteListener(this); this.mediaPlayer.setOnBufferingUpdateListener(this); this.mediaPlayer.setOnVideoSizeChangedListener(this); this.mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); } RelativeLayout.LayoutParams layoutParams; View view; if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { if (this.textureView == null) { this.textureView = new TextureView(this.context); this.textureView.setSurfaceTextureListener(this); } view = this.textureView; } else { if (this.surfaceView == null) { this.surfaceView = new SurfaceView(context); } view = this.surfaceView; if (this.surfaceHolder == null) { this.surfaceHolder = this.surfaceView.getHolder(); //noinspection deprecation this.surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); this.surfaceHolder.addCallback(this); } } layoutParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); layoutParams.addRule(CENTER_IN_PARENT); view.setLayoutParams(layoutParams); addView(view); // Try not reset onProgressView if (this.onProgressView == null) this.onProgressView = new ProgressBar(context); layoutParams = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); layoutParams.addRule(CENTER_IN_PARENT); this.onProgressView.setLayoutParams(layoutParams); addView(this.onProgressView); stopLoading(); this.currentState = State.IDLE; }
java
{ "resource": "" }
q20310
FullscreenVideoView.releaseObjects
train
protected void releaseObjects() { Log.d(TAG, "releaseObjects"); if (this.mediaPlayer != null) { this.mediaPlayer.setSurface(null); this.mediaPlayer.reset(); } this.videoIsReady = false; this.surfaceIsReady = false; this.initialMovieHeight = -1; this.initialMovieWidth = -1; if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) { if (this.textureView != null) { this.textureView.setSurfaceTextureListener(null); removeView(this.textureView); this.textureView = null; } } else { if (this.surfaceHolder != null) { this.surfaceHolder.removeCallback(this); this.surfaceHolder = null; } if (this.surfaceView != null) { removeView(this.surfaceView); this.surfaceView = null; } } if (this.onProgressView != null) { removeView(this.onProgressView); } }
java
{ "resource": "" }
q20311
FullscreenVideoView.tryToPrepare
train
protected void tryToPrepare() { Log.d(TAG, "tryToPrepare"); if (this.surfaceIsReady && this.videoIsReady) { if (this.mediaPlayer != null && this.mediaPlayer.getVideoWidth() != 0 && this.mediaPlayer.getVideoHeight() != 0) { this.initialMovieWidth = this.mediaPlayer.getVideoWidth(); this.initialMovieHeight = this.mediaPlayer.getVideoHeight(); } resize(); stopLoading(); currentState = State.PREPARED; if (shouldAutoplay) start(); if (this.preparedListener != null) this.preparedListener.onPrepared(mediaPlayer); } }
java
{ "resource": "" }
q20312
FullscreenVideoView.setFullscreen
train
public void setFullscreen(final boolean fullscreen) throws RuntimeException { if (mediaPlayer == null) throw new RuntimeException("Media Player is not initialized"); if (this.currentState != State.ERROR) { if (FullscreenVideoView.this.fullscreen == fullscreen) return; FullscreenVideoView.this.fullscreen = fullscreen; final boolean wasPlaying = mediaPlayer.isPlaying(); if (wasPlaying) pause(); if (FullscreenVideoView.this.fullscreen) { if (activity != null) activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); View rootView = getRootView(); View v = rootView.findViewById(android.R.id.content); ViewParent viewParent = getParent(); if (viewParent instanceof ViewGroup) { if (parentView == null) parentView = (ViewGroup) viewParent; // Prevents MediaPlayer to became invalidated and released detachedByFullscreen = true; // Saves the last state (LayoutParams) of view to restore after currentLayoutParams = FullscreenVideoView.this.getLayoutParams(); parentView.removeView(FullscreenVideoView.this); } else Log.e(TAG, "Parent View is not a ViewGroup"); if (v instanceof ViewGroup) { ((ViewGroup) v).addView(FullscreenVideoView.this); } else Log.e(TAG, "RootView is not a ViewGroup"); } else { if (activity != null) activity.setRequestedOrientation(initialConfigOrientation); ViewParent viewParent = getParent(); if (viewParent instanceof ViewGroup) { // Check if parent view is still available boolean parentHasParent = false; if (parentView != null && parentView.getParent() != null) { parentHasParent = true; detachedByFullscreen = true; } ((ViewGroup) viewParent).removeView(FullscreenVideoView.this); if (parentHasParent) { parentView.addView(FullscreenVideoView.this); FullscreenVideoView.this.setLayoutParams(currentLayoutParams); } } } resize(); Handler handler = new Handler(Looper.getMainLooper()); handler.post(new Runnable() { @Override public void run() { if (wasPlaying && mediaPlayer != null) start(); } }); } }
java
{ "resource": "" }
q20313
FullscreenVideoLayout.onClick
train
@Override public void onClick(View v) { if (v.getId() == R.id.vcv_img_play) { if (isPlaying()) { pause(); } else { start(); } } else { setFullscreen(!isFullscreen()); } }
java
{ "resource": "" }
q20314
AbstractDataBuilder.populate
train
public void populate(final AnnotationData data, final Annotation annotation, final Class<? extends Annotation> expectedAnnotationClass, final Method targetMethod) throws Exception { if (support(expectedAnnotationClass)) { build(data, annotation, expectedAnnotationClass, targetMethod); } }
java
{ "resource": "" }
q20315
CacheFactory.createCache
train
protected Cache createCache() throws IOException { // this factory creates only one single cache and return it if someone invoked this method twice or // more if (cache != null) { throw new IllegalStateException(String.format("This factory has already created memcached client for cache %s", cacheName)); } if (isCacheDisabled()) { LOGGER.warn("Cache {} is disabled", cacheName); cache = (Cache) Proxy.newProxyInstance(Cache.class.getClassLoader(), new Class[] { Cache.class }, new DisabledCacheInvocationHandler(cacheName, cacheAliases)); return cache; } if (configuration == null) { throw new RuntimeException(String.format("The MemcachedConnectionBean for cache %s must be defined!", cacheName)); } List<InetSocketAddress> addrs = addressProvider.getAddresses(); cache = new CacheImpl(cacheName, cacheAliases, createClient(addrs), defaultSerializationType, jsonTranscoder, javaTranscoder, customTranscoder, new CacheProperties(configuration.isUseNameAsKeyPrefix(), configuration.getKeyPrefixSeparator())); return cache; }
java
{ "resource": "" }
q20316
CacheKeyBuilderImpl.getCacheKey
train
@Override public String getCacheKey(final Object keyObject, final String namespace) { return namespace + SEPARATOR + defaultKeyProvider.generateKey(keyObject); }
java
{ "resource": "" }
q20317
CacheKeyBuilderImpl.buildCacheKey
train
private String buildCacheKey(final String[] objectIds, final String namespace) { if (objectIds.length == 1) { checkKeyPart(objectIds[0]); return namespace + SEPARATOR + objectIds[0]; } StringBuilder cacheKey = new StringBuilder(namespace); cacheKey.append(SEPARATOR); for (String id : objectIds) { checkKeyPart(id); cacheKey.append(id); cacheKey.append(ID_SEPARATOR); } cacheKey.deleteCharAt(cacheKey.length() - 1); return cacheKey.toString(); }
java
{ "resource": "" }
q20318
SSMCacheManager.removeCache
train
public void removeCache(final String nameOrAlias) { final Cache cache = cacheMap.get(nameOrAlias); if (cache == null) { return; } final SSMCache ssmCache = (SSMCache) cache; if (ssmCache.isRegisterAliases()) { ssmCache.getCache().getAliases().forEach(this::unregisterCache); } unregisterCache(nameOrAlias); unregisterCache(cache.getName()); caches.removeIf(c -> c.getName().equals(cache.getName())); }
java
{ "resource": "" }
q20319
JavaTranscoder.deserialize
train
protected Object deserialize(final byte[] in) { Object o = null; ByteArrayInputStream bis = null; ConfigurableObjectInputStream is = null; try { if (in != null) { bis = new ByteArrayInputStream(in); is = new ConfigurableObjectInputStream(bis, Thread.currentThread().getContextClassLoader()); o = is.readObject(); is.close(); bis.close(); } } catch (IOException e) { LOGGER.warn(String.format("Caught IOException decoding %d bytes of data", in.length), e); } catch (ClassNotFoundException e) { LOGGER.warn(String.format("Caught CNFE decoding %d bytes of data", in.length), e); } finally { close(is); close(bis); } return o; }
java
{ "resource": "" }
q20320
SSMCache.get
train
@Override @SuppressWarnings("unchecked") public <T> T get(final Object key, final Class<T> type) { if (!cache.isEnabled()) { LOGGER.warn("Cache {} is disabled. Cannot get {} from cache", cache.getName(), key); return null; } Object value = getValue(key); if (value == null) { LOGGER.info("Cache miss. Get by key {} and type {} from cache {}", new Object[] { key, type, cache.getName() }); return null; } if (value instanceof PertinentNegativeNull) { return null; } if (type != null && !type.isInstance(value)) { // in such case default Spring back end for EhCache throws IllegalStateException which interrupts // intercepted method invocation String msg = "Cached value is not of required type [" + type.getName() + "]: " + value; LOGGER.error(msg, new IllegalStateException(msg)); return null; } LOGGER.info("Cache hit. Get by key {} and type {} from cache {} value '{}'", new Object[] { key, type, cache.getName(), value }); return (T) value; }
java
{ "resource": "" }
q20321
SSMCache.get
train
@Override @SuppressWarnings("unchecked") public <T> T get(final Object key, final Callable<T> valueLoader) { if (!cache.isEnabled()) { LOGGER.warn("Cache {} is disabled. Cannot get {} from cache", cache.getName(), key); return loadValue(key, valueLoader); } final ValueWrapper valueWrapper = get(key); if (valueWrapper != null) { return (T) valueWrapper.get(); } synchronized (key.toString().intern()) { final T value = loadValue(key, valueLoader); put(key, value); return value; } }
java
{ "resource": "" }
q20322
SSMCache.putIfAbsent
train
@Override public ValueWrapper putIfAbsent(final Object key, final Object value) { if (!cache.isEnabled()) { LOGGER.warn("Cache {} is disabled. Cannot put value under key {}", cache.getName(), key); return null; } if (key != null) { final String cacheKey = getKey(key); try { LOGGER.info("Put '{}' under key {} to cache {}", new Object[] { value, key, cache.getName() }); final Object store = toStoreValue(value); final boolean added = cache.add(cacheKey, expiration, store, null); return added ? null : get(key); } catch (TimeoutException | CacheException | RuntimeException e) { logOrThrow(e, "An error has ocurred for cache {} and key {}", getName(), cacheKey, e); } } else { LOGGER.info("Cannot put to cache {} because key is null", cache.getName()); } return null; }
java
{ "resource": "" }
q20323
Utils.toScalaSeq
train
@SuppressWarnings({ "rawtypes", "unchecked" }) public static Seq toScalaSeq(Object[] o) { ArrayList list = new ArrayList(); for (int i = 0; i < o.length; i++) { list.add(o[i]); } return scala.collection.JavaConversions.asScalaBuffer(list).toList(); }
java
{ "resource": "" }
q20324
UnsignedInteger64.add
train
public static UnsignedInteger64 add(UnsignedInteger64 x, UnsignedInteger64 y) { return new UnsignedInteger64(x.bigInt.add(y.bigInt)); }
java
{ "resource": "" }
q20325
UnsignedInteger64.add
train
public static UnsignedInteger64 add(UnsignedInteger64 x, int y) { return new UnsignedInteger64(x.bigInt.add(BigInteger.valueOf(y))); }
java
{ "resource": "" }
q20326
UnsignedInteger64.toByteArray
train
public byte[] toByteArray() { byte[] raw = new byte[8]; byte[] bi = bigIntValue().toByteArray(); System.arraycopy(bi, 0, raw, raw.length - bi.length, bi.length); return raw; }
java
{ "resource": "" }
q20327
PublicKeySubsystem.remove
train
public void remove(SshPublicKey key) throws SshException, PublicKeySubsystemException { try { Packet msg = createPacket(); msg.writeString("remove"); msg.writeString(key.getAlgorithm()); msg.writeBinaryString(key.getEncoded()); sendMessage(msg); readStatusResponse(); } catch (IOException ex) { throw new SshException(ex); } }
java
{ "resource": "" }
q20328
PublicKeySubsystem.list
train
public SshPublicKey[] list() throws SshException, PublicKeySubsystemException { try { Packet msg = createPacket(); msg.writeString("list"); sendMessage(msg); Vector<SshPublicKey> keys = new Vector<SshPublicKey>(); while (true) { ByteArrayReader response = new ByteArrayReader(nextMessage()); try { String type = response.readString(); if (type.equals("publickey")) { @SuppressWarnings("unused") String comment = response.readString(); String algorithm = response.readString(); keys.addElement(SshPublicKeyFileFactory .decodeSSH2PublicKey(algorithm, response.readBinaryString())); } else if (type.equals("status")) { int status = (int) response.readInt(); String desc = response.readString(); if (status != PublicKeySubsystemException.SUCCESS) { throw new PublicKeySubsystemException(status, desc); } SshPublicKey[] array = new SshPublicKey[keys.size()]; keys.copyInto(array); return array; } else { throw new SshException( "The server sent an invalid response to a list command", SshException.PROTOCOL_VIOLATION); } } finally { try { response.close(); } catch (IOException e) { } } } } catch (IOException ex) { throw new SshException(ex); } }
java
{ "resource": "" }
q20329
PublicKeySubsystem.associateCommand
train
public void associateCommand(SshPublicKey key, String command) throws SshException, PublicKeySubsystemException { try { Packet msg = createPacket(); msg.writeString("command"); msg.writeString(key.getAlgorithm()); msg.writeBinaryString(key.getEncoded()); msg.writeString(command); sendMessage(msg); readStatusResponse(); } catch (IOException ex) { throw new SshException(ex); } }
java
{ "resource": "" }
q20330
PublicKeySubsystem.readStatusResponse
train
void readStatusResponse() throws SshException, PublicKeySubsystemException { ByteArrayReader msg = new ByteArrayReader(nextMessage()); try { msg.readString(); int status = (int) msg.readInt(); String desc = msg.readString(); if (status != PublicKeySubsystemException.SUCCESS) { throw new PublicKeySubsystemException(status, desc); } } catch (IOException ex) { throw new SshException(ex); } finally { try { msg.close(); } catch (IOException e) { } } }
java
{ "resource": "" }
q20331
PseudoTerminalModes.setTerminalMode
train
public void setTerminalMode(int mode, int value) throws SshException { try { encodedModes.write(mode); if (version == 1 && mode <= 127) { encodedModes.write(value); } else { encodedModes.writeInt(value); } } catch (IOException ex) { throw new SshException(SshException.INTERNAL_ERROR, ex); } }
java
{ "resource": "" }
q20332
Proxy.exchange
train
protected ProxyMessage exchange(ProxyMessage request) throws SocksException{ ProxyMessage reply; try{ request.write(out); reply = formMessage(in); }catch(SocksException s_ex){ throw s_ex; }catch(IOException ioe){ throw(new SocksException(SOCKS_PROXY_IO_ERROR,""+ioe)); } return reply; }
java
{ "resource": "" }
q20333
NoRegExpMatching.matchFileNamesWithPattern
train
public String[] matchFileNamesWithPattern(File[] files, String fileNameRegExp) throws SshException, SftpStatusException { String[] thefile = new String[1]; thefile[0] = files[0].getName(); return thefile; }
java
{ "resource": "" }
q20334
EventServiceImplementation.addListener
train
public synchronized void addListener(String threadPrefix, EventListener listener) { if (threadPrefix.trim().equals("")) { globalListeners.addElement(listener); } else { keyedListeners.put(threadPrefix.trim(), listener); } }
java
{ "resource": "" }
q20335
EventServiceImplementation.fireEvent
train
public synchronized void fireEvent(Event evt) { if (evt == null) { return; } // Process global listeners for (Enumeration<EventListener> keys = globalListeners.elements(); keys .hasMoreElements();) { EventListener mListener = keys.nextElement(); try { mListener.processEvent(evt); } catch (Throwable t) { } } String sourceThread = Thread.currentThread().getName(); for (Enumeration<String> keys = keyedListeners.keys(); keys .hasMoreElements();) { String key = (String) keys.nextElement(); // We don't want badly behaved listeners to throw uncaught // exceptions and upset other listeners try { String prefix = ""; if (sourceThread.indexOf('-') > -1) { prefix = sourceThread.substring(0, sourceThread.indexOf('-')); if (key.startsWith(prefix)) { EventListener mListener = keyedListeners.get(key); mListener.processEvent(evt); } } } catch (Throwable thr) { // log.error("Event failed.", thr); } } }
java
{ "resource": "" }
q20336
SftpFileOutputStream.close
train
public void close() throws IOException { try { while (processNextResponse(0)) ; file.close(); } catch (SshException ex) { throw new SshIOException(ex); } catch (SftpStatusException ex) { throw new IOException(ex.getMessage()); } }
java
{ "resource": "" }
q20337
ByteArrayReader.setCharsetEncoding
train
public static void setCharsetEncoding(String charset) { try { String test = "123456890"; test.getBytes(charset); CHARSET_ENCODING = charset; encode = true; } catch (UnsupportedEncodingException ex) { // Reset the encoding to default CHARSET_ENCODING = ""; encode = false; } }
java
{ "resource": "" }
q20338
ByteArrayReader.readBigInteger
train
public BigInteger readBigInteger() throws IOException { int len = (int) readInt(); byte[] raw = new byte[len]; readFully(raw); return new BigInteger(raw); }
java
{ "resource": "" }
q20339
ByteArrayReader.readString
train
public String readString(String charset) throws IOException { long len = readInt(); if (len > available()) throw new IOException("Cannot read string of length " + len + " bytes when only " + available() + " bytes are available"); byte[] raw = new byte[(int) len]; readFully(raw); if (encode) { return new String(raw, charset); } return new String(raw); }
java
{ "resource": "" }
q20340
ByteArrayReader.readMPINT32
train
public BigInteger readMPINT32() throws IOException { int bits = (int) readInt(); byte[] raw = new byte[(bits + 7) / 8 + 1]; raw[0] = 0; readFully(raw, 1, raw.length - 1); return new BigInteger(raw); }
java
{ "resource": "" }
q20341
ByteArrayReader.readMPINT
train
public BigInteger readMPINT() throws IOException { short bits = readShort(); byte[] raw = new byte[(bits + 7) / 8 + 1]; raw[0] = 0; readFully(raw, 1, raw.length - 1); return new BigInteger(raw); }
java
{ "resource": "" }
q20342
SocksProxyTransport.connectViaSocks4Proxy
train
public static SocksProxyTransport connectViaSocks4Proxy(String remoteHost, int remotePort, String proxyHost, int proxyPort, String userId) throws IOException, UnknownHostException { SocksProxyTransport proxySocket = new SocksProxyTransport(remoteHost, remotePort, proxyHost, proxyPort, SOCKS4); proxySocket.username = userId; try { InputStream proxyIn = proxySocket.getInputStream(); OutputStream proxyOut = proxySocket.getOutputStream(); InetAddress hostAddr = InetAddress.getByName(remoteHost); proxyOut.write(SOCKS4); proxyOut.write(CONNECT); proxyOut.write((remotePort >>> 8) & 0xff); proxyOut.write(remotePort & 0xff); proxyOut.write(hostAddr.getAddress()); proxyOut.write(userId.getBytes()); proxyOut.write(NULL_TERMINATION); proxyOut.flush(); int res = proxyIn.read(); if (res == -1) { throw new IOException("SOCKS4 server " + proxyHost + ":" + proxyPort + " disconnected"); } if (res != 0x00) { throw new IOException("Invalid response from SOCKS4 server (" + res + ") " + proxyHost + ":" + proxyPort); } int code = proxyIn.read(); if (code != 90) { if ((code > 90) && (code < 93)) { throw new IOException( "SOCKS4 server unable to connect, reason: " + SOCKSV4_ERROR[code - 91]); } throw new IOException( "SOCKS4 server unable to connect, reason: " + code); } byte[] data = new byte[6]; if (proxyIn.read(data, 0, 6) != 6) { throw new IOException( "SOCKS4 error reading destination address/port"); } proxySocket.setProviderDetail(data[2] + "." + data[3] + "." + data[4] + "." + data[5] + ":" + ((data[0] << 8) | data[1])); } catch (SocketException e) { throw new SocketException("Error communicating with SOCKS4 server " + proxyHost + ":" + proxyPort + ", " + e.getMessage()); } return proxySocket; }
java
{ "resource": "" }
q20343
SubsystemChannel.sendMessage
train
protected void sendMessage(byte[] msg) throws SshException { try { Packet pkt = createPacket(); pkt.write(msg); sendMessage(pkt); } catch (IOException ex) { throw new SshException(SshException.UNEXPECTED_TERMINATION, ex); } }
java
{ "resource": "" }
q20344
SubsystemChannel.createPacket
train
protected Packet createPacket() throws IOException { synchronized (packets) { if (packets.size() == 0) return new Packet(); Packet p = (Packet) packets.elementAt(0); packets.removeElementAt(0); return p; } }
java
{ "resource": "" }
q20345
SshKeyPairGenerator.generateKeyPair
train
public static SshKeyPair generateKeyPair(String algorithm, int bits) throws IOException, SshException { if (!SSH2_RSA.equalsIgnoreCase(algorithm) && !SSH2_DSA.equalsIgnoreCase(algorithm)) { throw new IOException(algorithm + " is not a supported key algorithm!"); } SshKeyPair pair = new SshKeyPair(); if (SSH2_RSA.equalsIgnoreCase(algorithm)) { pair = ComponentManager.getInstance().generateRsaKeyPair(bits); } else { pair = ComponentManager.getInstance().generateDsaKeyPair(bits); } return pair; }
java
{ "resource": "" }
q20346
SftpFileAttributes.setUID
train
public void setUID(String uid) { if (version > 3) { flags |= SSH_FILEXFER_ATTR_OWNERGROUP; } else flags |= SSH_FILEXFER_ATTR_UIDGID; this.uid = uid; }
java
{ "resource": "" }
q20347
SftpFileAttributes.setGID
train
public void setGID(String gid) { if (version > 3) { flags |= SSH_FILEXFER_ATTR_OWNERGROUP; } else flags |= SSH_FILEXFER_ATTR_UIDGID; this.gid = gid; }
java
{ "resource": "" }
q20348
SftpFileAttributes.setSize
train
public void setSize(UnsignedInteger64 size) { this.size = size; // Set the flag if (size != null) { flags |= SSH_FILEXFER_ATTR_SIZE; } else { flags ^= SSH_FILEXFER_ATTR_SIZE; } }
java
{ "resource": "" }
q20349
SftpFileAttributes.setPermissions
train
public void setPermissions(UnsignedInteger32 permissions) { this.permissions = permissions; // Set the flag if (permissions != null) { flags |= SSH_FILEXFER_ATTR_PERMISSIONS; } else { flags ^= SSH_FILEXFER_ATTR_PERMISSIONS; } }
java
{ "resource": "" }
q20350
SftpFileAttributes.setPermissionsFromMaskString
train
public void setPermissionsFromMaskString(String mask) { if (mask.length() != 4) { throw new IllegalArgumentException("Mask length must be 4"); } try { setPermissions(new UnsignedInteger32(String.valueOf(Integer .parseInt(mask, 8)))); } catch (NumberFormatException nfe) { throw new IllegalArgumentException( "Mask must be 4 digit octal number."); } }
java
{ "resource": "" }
q20351
SftpFileAttributes.setPermissionsFromUmaskString
train
public void setPermissionsFromUmaskString(String umask) { if (umask.length() != 4) { throw new IllegalArgumentException("umask length must be 4"); } try { setPermissions(new UnsignedInteger32(String.valueOf(Integer .parseInt(umask, 8) ^ 0777))); } catch (NumberFormatException ex) { throw new IllegalArgumentException( "umask must be 4 digit octal number"); } }
java
{ "resource": "" }
q20352
SftpFileAttributes.getMaskString
train
public String getMaskString() { StringBuffer buf = new StringBuffer(); if (permissions != null) { int i = (int) permissions.longValue(); buf.append('0'); buf.append(octal(i, 6)); buf.append(octal(i, 3)); buf.append(octal(i, 0)); } else { buf.append("----"); } return buf.toString(); }
java
{ "resource": "" }
q20353
SftpFileAttributes.isDirectory
train
public boolean isDirectory() { if (sftp.getVersion() > 3) { return type == SSH_FILEXFER_TYPE_DIRECTORY; } else if (permissions != null && (permissions.longValue() & SftpFileAttributes.S_IFDIR) == SftpFileAttributes.S_IFDIR) { return true; } else { return false; } }
java
{ "resource": "" }
q20354
SftpFileAttributes.isLink
train
public boolean isLink() { if (sftp.getVersion() > 3) { return type == SSH_FILEXFER_TYPE_SYMLINK; } else if (permissions != null && (permissions.longValue() & SftpFileAttributes.S_IFLNK) == SftpFileAttributes.S_IFLNK) { return true; } else { return false; } }
java
{ "resource": "" }
q20355
SftpFileAttributes.isFifo
train
public boolean isFifo() { if (permissions != null && (permissions.longValue() & SftpFileAttributes.S_IFIFO) == SftpFileAttributes.S_IFIFO) { return true; } return false; }
java
{ "resource": "" }
q20356
SftpFileAttributes.isBlock
train
public boolean isBlock() { if (permissions != null && (permissions.longValue() & SftpFileAttributes.S_IFBLK) == SftpFileAttributes.S_IFBLK) { return true; } return false; }
java
{ "resource": "" }
q20357
SftpFileAttributes.isCharacter
train
public boolean isCharacter() { if (permissions != null && (permissions.longValue() & SftpFileAttributes.S_IFCHR) == SftpFileAttributes.S_IFCHR) { return true; } return false; }
java
{ "resource": "" }
q20358
SftpFileAttributes.isSocket
train
public boolean isSocket() { if (permissions != null && (permissions.longValue() & SftpFileAttributes.S_IFSOCK) == SftpFileAttributes.S_IFSOCK) { return true; } return false; }
java
{ "resource": "" }
q20359
JCEProvider.getProviderForAlgorithm
train
public static Provider getProviderForAlgorithm(String jceAlgorithm) { if (specficProviders.containsKey(jceAlgorithm)) { return (Provider) specficProviders.get(jceAlgorithm); } return defaultProvider; }
java
{ "resource": "" }
q20360
JCEProvider.getSecureRandom
train
public static SecureRandom getSecureRandom() throws NoSuchAlgorithmException { if (secureRandom == null) { try { return secureRandom = JCEProvider .getProviderForAlgorithm(JCEProvider .getSecureRandomAlgorithm()) == null ? SecureRandom .getInstance(JCEProvider.getSecureRandomAlgorithm()) : SecureRandom.getInstance(JCEProvider .getSecureRandomAlgorithm(), JCEProvider .getProviderForAlgorithm(JCEProvider .getSecureRandomAlgorithm())); } catch (NoSuchAlgorithmException e) { return secureRandom = SecureRandom.getInstance(JCEProvider .getSecureRandomAlgorithm()); } } return secureRandom; }
java
{ "resource": "" }
q20361
DirectoryOperation.containsFile
train
public boolean containsFile(File f) { return unchangedFiles.contains(f) || newFiles.contains(f) || updatedFiles.contains(f) || deletedFiles.contains(f) || recursedDirectories.contains(f) || failedTransfers.containsKey(f); }
java
{ "resource": "" }
q20362
DirectoryOperation.containsFile
train
public boolean containsFile(SftpFile f) { return unchangedFiles.contains(f) || newFiles.contains(f) || updatedFiles.contains(f) || deletedFiles.contains(f) || recursedDirectories.contains(f.getAbsolutePath()) || failedTransfers.containsKey(f); }
java
{ "resource": "" }
q20363
DirectoryOperation.addDirectoryOperation
train
public void addDirectoryOperation(DirectoryOperation op, File f) { addAll(op.getUpdatedFiles(), updatedFiles); addAll(op.getNewFiles(), newFiles); addAll(op.getUnchangedFiles(), unchangedFiles); addAll(op.getDeletedFiles(), deletedFiles); Object obj; for (Enumeration e = op.failedTransfers.keys(); e.hasMoreElements();) { obj = e.nextElement(); failedTransfers.put(obj, op.failedTransfers.get(obj)); } recursedDirectories.addElement(f); }
java
{ "resource": "" }
q20364
DirectoryOperation.getTransferSize
train
public long getTransferSize() throws SftpStatusException, SshException { Object obj; long size = 0; SftpFile sftpfile; File file; for (Enumeration e = newFiles.elements(); e.hasMoreElements();) { obj = e.nextElement(); if (obj instanceof File) { file = (File) obj; if (file.isFile()) { size += file.length(); } } else if (obj instanceof SftpFile) { sftpfile = (SftpFile) obj; if (sftpfile.isFile()) { size += sftpfile.getAttributes().getSize().longValue(); } } } for (Enumeration e = updatedFiles.elements(); e.hasMoreElements();) { obj = e.nextElement(); if (obj instanceof File) { file = (File) obj; if (file.isFile()) { size += file.length(); } } else if (obj instanceof SftpFile) { sftpfile = (SftpFile) obj; if (sftpfile.isFile()) { size += sftpfile.getAttributes().getSize().longValue(); } } } // Add a value for deleted files?? return size; }
java
{ "resource": "" }
q20365
ByteArrayWriter.writeBigInteger
train
public void writeBigInteger(BigInteger bi) throws IOException { byte[] raw = bi.toByteArray(); writeInt(raw.length); write(raw); }
java
{ "resource": "" }
q20366
ByteArrayWriter.writeInt
train
public void writeInt(long i) throws IOException { byte[] raw = new byte[4]; raw[0] = (byte) (i >> 24); raw[1] = (byte) (i >> 16); raw[2] = (byte) (i >> 8); raw[3] = (byte) (i); write(raw); }
java
{ "resource": "" }
q20367
ByteArrayWriter.encodeInt
train
public static byte[] encodeInt(int i) { byte[] raw = new byte[4]; raw[0] = (byte) (i >> 24); raw[1] = (byte) (i >> 16); raw[2] = (byte) (i >> 8); raw[3] = (byte) (i); return raw; }
java
{ "resource": "" }
q20368
ByteArrayWriter.writeString
train
public void writeString(String str, String charset) throws IOException { if (str == null) { writeInt(0); } else { byte[] tmp; if (ByteArrayReader.encode) tmp = str.getBytes(charset); else tmp = str.getBytes(); writeInt(tmp.length); write(tmp); } }
java
{ "resource": "" }
q20369
SftpSubsystemChannel.initialize
train
public void initialize() throws SshException, UnsupportedEncodingException { // Initialize the SFTP subsystem try { Packet packet = createPacket(); packet.write(SSH_FXP_INIT); packet.writeInt(this_MAX_VERSION); sendMessage(packet); byte[] msg = nextMessage(); if (msg[0] != SSH_FXP_VERSION) { close(); throw new SshException( "Unexpected response from SFTP subsystem.", SshException.CHANNEL_FAILURE); } ByteArrayReader bar = new ByteArrayReader(msg); try { bar.skip(1); serverVersion = (int) bar.readInt(); version = Math.min(serverVersion, MAX_VERSION); try { while (bar.available() > 0) { String name = bar.readString(); byte[] data = bar.readBinaryString(); extensions.put(name, data); } } catch (Throwable t) { } } finally { bar.close(); } if (version <= 3) setCharsetEncoding("ISO-8859-1"); else setCharsetEncoding("UTF8"); } catch (SshIOException ex) { throw ex.getRealException(); } catch (IOException ex) { throw new SshException(SshException.CHANNEL_FAILURE, ex); } catch (Throwable t) { throw new SshException(SshException.CHANNEL_FAILURE, t); } }
java
{ "resource": "" }
q20370
SftpSubsystemChannel.setCharsetEncoding
train
public void setCharsetEncoding(String charset) throws SshException, UnsupportedEncodingException { if (version == -1) throw new SshException( "SFTP Channel must be initialized before setting character set encoding", SshException.BAD_API_USAGE); String test = "123456890"; test.getBytes(charset); CHARSET_ENCODING = charset; }
java
{ "resource": "" }
q20371
SftpSubsystemChannel.sendExtensionMessage
train
public SftpMessage sendExtensionMessage(String request, byte[] requestData) throws SshException, SftpStatusException { try { UnsignedInteger32 id = nextRequestId(); Packet packet = createPacket(); packet.write(SSH_FXP_EXTENDED); packet.writeUINT32(id); packet.writeString(request); sendMessage(packet); return getResponse(id); } catch (IOException ex) { throw new SshException(SshException.INTERNAL_ERROR, ex); } }
java
{ "resource": "" }
q20372
SftpSubsystemChannel.postWriteRequest
train
public UnsignedInteger32 postWriteRequest(byte[] handle, long position, byte[] data, int off, int len) throws SftpStatusException, SshException { if ((data.length - off) < len) { throw new IndexOutOfBoundsException("Incorrect data array size!"); } try { UnsignedInteger32 requestId = nextRequestId(); Packet msg = createPacket(); msg.write(SSH_FXP_WRITE); msg.writeInt(requestId.longValue()); msg.writeBinaryString(handle); msg.writeUINT64(position); msg.writeBinaryString(data, off, len); sendMessage(msg); return requestId; } catch (SshIOException ex) { throw ex.getRealException(); } catch (IOException ex) { throw new SshException(ex); } }
java
{ "resource": "" }
q20373
SftpSubsystemChannel.writeFile
train
public void writeFile(byte[] handle, UnsignedInteger64 offset, byte[] data, int off, int len) throws SftpStatusException, SshException { getOKRequestStatus(postWriteRequest(handle, offset.longValue(), data, off, len)); }
java
{ "resource": "" }
q20374
SftpSubsystemChannel.performSynchronousRead
train
public void performSynchronousRead(byte[] handle, int blocksize, OutputStream out, FileTransferProgress progress, long position) throws SftpStatusException, SshException, TransferCancelledException { if (Log.isDebugEnabled()) { Log.debug(this, "Performing synchronous read postion=" + position + " blocksize=" + blocksize); } if (blocksize < 1 || blocksize > 32768) { if (Log.isDebugEnabled()) { Log.debug(this, "Blocksize to large for some SFTP servers, reseting to 32K"); } blocksize = 32768; } if (position < 0) { throw new SshException("Position value must be greater than zero!", SshException.BAD_API_USAGE); } byte[] tmp = new byte[blocksize]; int read; UnsignedInteger64 offset = new UnsignedInteger64(position); if (position > 0) { if (progress != null) progress.progressed(position); } try { while ((read = readFile(handle, offset, tmp, 0, tmp.length)) > -1) { if (progress != null && progress.isCancelled()) { throw new TransferCancelledException(); } out.write(tmp, 0, read); offset = UnsignedInteger64.add(offset, read); if (progress != null) progress.progressed(offset.longValue()); } } catch (IOException e) { throw new SshException(e); } }
java
{ "resource": "" }
q20375
SftpSubsystemChannel.postReadRequest
train
public UnsignedInteger32 postReadRequest(byte[] handle, long offset, int len) throws SftpStatusException, SshException { try { UnsignedInteger32 requestId = nextRequestId(); Packet msg = createPacket(); msg.write(SSH_FXP_READ); msg.writeInt(requestId.longValue()); msg.writeBinaryString(handle); msg.writeUINT64(offset); msg.writeInt(len); sendMessage(msg); return requestId; } catch (SshIOException ex) { throw ex.getRealException(); } catch (IOException ex) { throw new SshException(ex); } }
java
{ "resource": "" }
q20376
SftpSubsystemChannel.readFile
train
public int readFile(byte[] handle, UnsignedInteger64 offset, byte[] output, int off, int len) throws SftpStatusException, SshException { try { if ((output.length - off) < len) { throw new IndexOutOfBoundsException( "Output array size is smaller than read length!"); } UnsignedInteger32 requestId = nextRequestId(); Packet msg = createPacket(); msg.write(SSH_FXP_READ); msg.writeInt(requestId.longValue()); msg.writeBinaryString(handle); msg.write(offset.toByteArray()); msg.writeInt(len); sendMessage(msg); SftpMessage bar = getResponse(requestId); if (bar.getType() == SSH_FXP_DATA) { byte[] msgdata = bar.readBinaryString(); System.arraycopy(msgdata, 0, output, off, msgdata.length); return msgdata.length; } else if (bar.getType() == SSH_FXP_STATUS) { int status = (int) bar.readInt(); if (status == SftpStatusException.SSH_FX_EOF) return -1; if (version >= 3) { String desc = bar.readString().trim(); throw new SftpStatusException(status, desc); } throw new SftpStatusException(status); } else { close(); throw new SshException( "The server responded with an unexpected message", SshException.CHANNEL_FAILURE); } } catch (SshIOException ex) { throw ex.getRealException(); } catch (IOException ex) { throw new SshException(ex); } }
java
{ "resource": "" }
q20377
SftpSubsystemChannel.createSymbolicLink
train
public void createSymbolicLink(String targetpath, String linkpath) throws SftpStatusException, SshException { if (version < 3) { throw new SftpStatusException( SftpStatusException.SSH_FX_OP_UNSUPPORTED, "Symbolic links are not supported by the server SFTP version " + String.valueOf(version)); } try { UnsignedInteger32 requestId = nextRequestId(); Packet msg = createPacket(); msg.write(SSH_FXP_SYMLINK); msg.writeInt(requestId.longValue()); msg.writeString(linkpath, CHARSET_ENCODING); msg.writeString(targetpath, CHARSET_ENCODING); sendMessage(msg); getOKRequestStatus(requestId); } catch (SshIOException ex) { throw ex.getRealException(); } catch (IOException ex) { throw new SshException(ex); } }
java
{ "resource": "" }
q20378
SftpSubsystemChannel.getSymbolicLinkTarget
train
public String getSymbolicLinkTarget(String linkpath) throws SftpStatusException, SshException { if (version < 3) { throw new SftpStatusException( SftpStatusException.SSH_FX_OP_UNSUPPORTED, "Symbolic links are not supported by the server SFTP version " + String.valueOf(version)); } try { UnsignedInteger32 requestId = nextRequestId(); Packet msg = createPacket(); msg.write(SSH_FXP_READLINK); msg.writeInt(requestId.longValue()); msg.writeString(linkpath, CHARSET_ENCODING); sendMessage(msg); SftpFile[] files = extractFiles(getResponse(requestId), null); return files[0].getAbsolutePath(); } catch (SshIOException ex) { throw ex.getRealException(); } catch (IOException ex) { throw new SshException(ex); } }
java
{ "resource": "" }
q20379
SftpSubsystemChannel.getAbsolutePath
train
public String getAbsolutePath(String path) throws SftpStatusException, SshException { try { UnsignedInteger32 requestId = nextRequestId(); Packet msg = createPacket(); msg.write(SSH_FXP_REALPATH); msg.writeInt(requestId.longValue()); msg.writeString(path, CHARSET_ENCODING); sendMessage(msg); SftpMessage bar = getResponse(requestId); if (bar.getType() == SSH_FXP_NAME) { SftpFile[] files = extractFiles(bar, null); if (files.length != 1) { close(); throw new SshException( "Server responded to SSH_FXP_REALPATH with too many files!", SshException.CHANNEL_FAILURE); } return files[0].getAbsolutePath(); } else if (bar.getType() == SSH_FXP_STATUS) { int status = (int) bar.readInt(); if (version >= 3) { String desc = bar.readString().trim(); throw new SftpStatusException(status, desc); } throw new SftpStatusException(status); } else { close(); throw new SshException( "The server responded with an unexpected message", SshException.CHANNEL_FAILURE); } } catch (SshIOException ex) { throw ex.getRealException(); } catch (IOException ex) { throw new SshException(ex); } }
java
{ "resource": "" }
q20380
SftpSubsystemChannel.recurseMakeDirectory
train
public void recurseMakeDirectory(String path) throws SftpStatusException, SshException { SftpFile file; if (path.trim().length() > 0) { try { file = openDirectory(path); file.close(); } catch (SshException ioe) { int idx = 0; do { idx = path.indexOf('/', idx); String tmp = (idx > -1 ? path.substring(0, idx + 1) : path); try { file = openDirectory(tmp); file.close(); } catch (SshException ioe7) { makeDirectory(tmp); } } while (idx > -1); } } }
java
{ "resource": "" }
q20381
SftpSubsystemChannel.openDirectory
train
public SftpFile openDirectory(String path) throws SftpStatusException, SshException { String absolutePath = getAbsolutePath(path); SftpFileAttributes attrs = getAttributes(absolutePath); if (!attrs.isDirectory()) { throw new SftpStatusException(SftpStatusException.SSH_FX_FAILURE, path + " is not a directory"); } try { UnsignedInteger32 requestId = nextRequestId(); Packet msg = createPacket(); msg.write(SSH_FXP_OPENDIR); msg.writeInt(requestId.longValue()); msg.writeString(path, CHARSET_ENCODING); sendMessage(msg); byte[] handle = getHandleResponse(requestId); SftpFile file = new SftpFile(absolutePath, attrs); file.setHandle(handle); file.setSFTPSubsystem(this); return file; } catch (SshIOException ex) { throw ex.getRealException(); } catch (IOException ex) { throw new SshException(ex); } }
java
{ "resource": "" }
q20382
SftpSubsystemChannel.closeFile
train
public void closeFile(SftpFile file) throws SftpStatusException, SshException { if (file.getHandle() != null) { closeHandle(file.getHandle()); EventServiceImplementation.getInstance().fireEvent( (new Event(this, J2SSHEventCodes.EVENT_SFTP_FILE_CLOSED, true)).addAttribute( J2SSHEventCodes.ATTRIBUTE_FILE_NAME, file.getAbsolutePath())); file.setHandle(null); } }
java
{ "resource": "" }
q20383
SftpSubsystemChannel.removeDirectory
train
public void removeDirectory(String path) throws SftpStatusException, SshException { try { UnsignedInteger32 requestId = nextRequestId(); Packet msg = createPacket(); msg.write(SSH_FXP_RMDIR); msg.writeInt(requestId.longValue()); msg.writeString(path, CHARSET_ENCODING); sendMessage(msg); getOKRequestStatus(requestId); } catch (SshIOException ex) { throw ex.getRealException(); } catch (IOException ex) { throw new SshException(ex); } EventServiceImplementation.getInstance().fireEvent( (new Event(this, J2SSHEventCodes.EVENT_SFTP_DIRECTORY_DELETED, true)).addAttribute( J2SSHEventCodes.ATTRIBUTE_DIRECTORY_PATH, path)); }
java
{ "resource": "" }
q20384
SftpSubsystemChannel.removeFile
train
public void removeFile(String filename) throws SftpStatusException, SshException { try { UnsignedInteger32 requestId = nextRequestId(); Packet msg = createPacket(); msg.write(SSH_FXP_REMOVE); msg.writeInt(requestId.longValue()); msg.writeString(filename, CHARSET_ENCODING); sendMessage(msg); getOKRequestStatus(requestId); } catch (SshIOException ex) { throw ex.getRealException(); } catch (IOException ex) { throw new SshException(ex); } EventServiceImplementation.getInstance() .fireEvent( (new Event(this, J2SSHEventCodes.EVENT_SFTP_FILE_DELETED, true)) .addAttribute( J2SSHEventCodes.ATTRIBUTE_FILE_NAME, filename)); }
java
{ "resource": "" }
q20385
SftpSubsystemChannel.renameFile
train
public void renameFile(String oldpath, String newpath) throws SftpStatusException, SshException { if (version < 2) { throw new SftpStatusException( SftpStatusException.SSH_FX_OP_UNSUPPORTED, "Renaming files is not supported by the server SFTP version " + String.valueOf(version)); } try { UnsignedInteger32 requestId = nextRequestId(); Packet msg = createPacket(); msg.write(SSH_FXP_RENAME); msg.writeInt(requestId.longValue()); msg.writeString(oldpath, CHARSET_ENCODING); msg.writeString(newpath, CHARSET_ENCODING); sendMessage(msg); getOKRequestStatus(requestId); } catch (SshIOException ex) { throw ex.getRealException(); } catch (IOException ex) { throw new SshException(ex); } EventServiceImplementation .getInstance() .fireEvent( (new Event(this, J2SSHEventCodes.EVENT_SFTP_FILE_RENAMED, true)) .addAttribute( J2SSHEventCodes.ATTRIBUTE_FILE_NAME, oldpath) .addAttribute( J2SSHEventCodes.ATTRIBUTE_FILE_NEW_NAME, newpath)); }
java
{ "resource": "" }
q20386
SftpSubsystemChannel.getAttributes
train
public SftpFileAttributes getAttributes(SftpFile file) throws SftpStatusException, SshException { try { if (file.getHandle() == null) { return getAttributes(file.getAbsolutePath()); } UnsignedInteger32 requestId = nextRequestId(); Packet msg = createPacket(); msg.write(SSH_FXP_FSTAT); msg.writeInt(requestId.longValue()); msg.writeBinaryString(file.getHandle()); if (version > 3) { msg.writeInt(SftpFileAttributes.SSH_FILEXFER_ATTR_SIZE | SftpFileAttributes.SSH_FILEXFER_ATTR_PERMISSIONS | SftpFileAttributes.SSH_FILEXFER_ATTR_ACCESSTIME | SftpFileAttributes.SSH_FILEXFER_ATTR_CREATETIME | SftpFileAttributes.SSH_FILEXFER_ATTR_MODIFYTIME | SftpFileAttributes.SSH_FILEXFER_ATTR_ACL | SftpFileAttributes.SSH_FILEXFER_ATTR_OWNERGROUP | SftpFileAttributes.SSH_FILEXFER_ATTR_SUBSECOND_TIMES | SftpFileAttributes.SSH_FILEXFER_ATTR_EXTENDED); } sendMessage(msg); return extractAttributes(getResponse(requestId)); } catch (SshIOException ex) { throw ex.getRealException(); } catch (IOException ex) { throw new SshException(ex); } }
java
{ "resource": "" }
q20387
SftpSubsystemChannel.makeDirectory
train
public void makeDirectory(String path) throws SftpStatusException, SshException { makeDirectory(path, new SftpFileAttributes(this, SftpFileAttributes.SSH_FILEXFER_TYPE_DIRECTORY)); }
java
{ "resource": "" }
q20388
ServerAuthenticatorNone.startSession
train
public ServerAuthenticator startSession(Socket s) throws IOException{ PushbackInputStream in = new PushbackInputStream(s.getInputStream()); OutputStream out = s.getOutputStream(); int version = in.read(); if(version == 5){ if(!selectSocks5Authentication(in,out,0)) return null; }else if(version == 4){ //Else it is the request message allready, version 4 in.unread(version); }else return null; return new ServerAuthenticatorNone(in,out); }
java
{ "resource": "" }
q20389
UDPRelayServer.start
train
public void start() throws IOException{ remote_sock.setSoTimeout(iddleTimeout); client_sock.setSoTimeout(iddleTimeout); log("Starting UDP relay server on "+relayIP+":"+relayPort); log("Remote socket "+remote_sock.getLocalAddress()+":"+ remote_sock.getLocalPort()); pipe_thread1 = new Thread(this,"pipe1"); pipe_thread2 = new Thread(this,"pipe2"); lastReadTime = System.currentTimeMillis(); pipe_thread1.start(); pipe_thread2.start(); }
java
{ "resource": "" }
q20390
Ssh2Session.startSubsystem
train
public boolean startSubsystem(String subsystem) throws SshException { ByteArrayWriter request = new ByteArrayWriter(); try { request.writeString(subsystem); boolean success = sendRequest("subsystem", true, request.toByteArray()); if (success) { EventServiceImplementation.getInstance().fireEvent( (new Event(this, J2SSHEventCodes.EVENT_SUBSYSTEM_STARTED, true)) .addAttribute( J2SSHEventCodes.ATTRIBUTE_COMMAND, subsystem)); } else { EventServiceImplementation .getInstance() .fireEvent( (new Event( this, J2SSHEventCodes.EVENT_SUBSYSTEM_STARTED, false)).addAttribute( J2SSHEventCodes.ATTRIBUTE_COMMAND, subsystem)); } return success; } catch (IOException ex) { throw new SshException(ex, SshException.INTERNAL_ERROR); } finally { try { request.close(); } catch (IOException e) { } } }
java
{ "resource": "" }
q20391
Ssh2Session.requestX11Forwarding
train
boolean requestX11Forwarding(boolean singleconnection, String protocol, String cookie, int screen) throws SshException { ByteArrayWriter request = new ByteArrayWriter(); try { request.writeBoolean(singleconnection); request.writeString(protocol); request.writeString(cookie); request.writeInt(screen); return sendRequest("x11-req", true, request.toByteArray()); } catch (IOException ex) { throw new SshException(ex, SshException.INTERNAL_ERROR); } finally { try { request.close(); } catch (IOException e) { } } }
java
{ "resource": "" }
q20392
Ssh2Session.setEnvironmentVariable
train
public boolean setEnvironmentVariable(String name, String value) throws SshException { ByteArrayWriter request = new ByteArrayWriter(); try { request.writeString(name); request.writeString(value); return sendRequest("env", true, request.toByteArray()); } catch (IOException ex) { throw new SshException(ex, SshException.INTERNAL_ERROR); } finally { try { request.close(); } catch (IOException e) { } } }
java
{ "resource": "" }
q20393
Ssh2Session.channelRequest
train
protected void channelRequest(String requesttype, boolean wantreply, byte[] requestdata) throws SshException { try { if (requesttype.equals("exit-status")) { if (requestdata != null) { exitcode = (int) ByteArrayReader.readInt(requestdata, 0); } } if (requesttype.equals("exit-signal")) { if (requestdata != null) { ByteArrayReader bar = new ByteArrayReader(requestdata, 0, requestdata.length); try { exitsignalinfo = "Signal=" + bar.readString() + " CoreDump=" + String.valueOf(bar.read() != 0) + " Message=" + bar.readString(); } finally { try { bar.close(); } catch (IOException e) { } } } } if (requesttype.equals("xon-xoff")) { flowControlEnabled = (requestdata != null && requestdata[0] != 0); } super.channelRequest(requesttype, wantreply, requestdata); } catch (IOException ex) { throw new SshException(ex, SshException.INTERNAL_ERROR); } }
java
{ "resource": "" }
q20394
ForwardingClient.startLocalForwarding
train
public void startLocalForwarding(String addressToBind, int portToBind, String hostToConnect, int portToConnect) throws SshException { String key = generateKey(addressToBind, portToBind); SocketListener listener = new SocketListener(addressToBind, portToBind, hostToConnect, portToConnect); listener.start(); socketlisteners.put(key, listener); if (!outgoingtunnels.containsKey(key)) { outgoingtunnels.put(key, new Vector<ActiveTunnel>()); } for (int i = 0; i < clientlisteners.size(); i++) { ((ForwardingClientListener) clientlisteners.elementAt(i)) .forwardingStarted( ForwardingClientListener.LOCAL_FORWARDING, key, hostToConnect, portToConnect); } EventServiceImplementation .getInstance() .fireEvent( (new Event(this, J2SSHEventCodes.EVENT_FORWARDING_LOCAL_STARTED, true)) .addAttribute( J2SSHEventCodes.ATTRIBUTE_FORWARDING_TUNNEL_ENTRANCE, key) .addAttribute( J2SSHEventCodes.ATTRIBUTE_FORWARDING_TUNNEL_EXIT, hostToConnect + ":" + portToConnect)); }
java
{ "resource": "" }
q20395
ForwardingClient.getRemoteForwardings
train
public String[] getRemoteForwardings() { String[] r = new String[remoteforwardings.size() - (remoteforwardings.containsKey(X11_KEY) ? 1 : 0)]; int index = 0; for (Enumeration<String> e = remoteforwardings.keys(); e .hasMoreElements();) { String key = e.nextElement(); if (!key.equals(X11_KEY)) r[index++] = key; } return r; }
java
{ "resource": "" }
q20396
ForwardingClient.getLocalForwardings
train
public String[] getLocalForwardings() { String[] r = new String[socketlisteners.size()]; int index = 0; for (Enumeration<String> e = socketlisteners.keys(); e .hasMoreElements();) { r[index++] = e.nextElement(); } return r; }
java
{ "resource": "" }
q20397
ForwardingClient.getRemoteForwardingTunnels
train
public ActiveTunnel[] getRemoteForwardingTunnels() throws IOException { Vector<ActiveTunnel> v = new Vector<ActiveTunnel>(); String[] remoteForwardings = getRemoteForwardings(); for (int i = 0; i < remoteForwardings.length; i++) { ActiveTunnel[] tmp = getRemoteForwardingTunnels(remoteForwardings[i]); for (int x = 0; x < tmp.length; x++) { v.add(tmp[x]); } } return (ActiveTunnel[]) v.toArray(new ActiveTunnel[v.size()]); }
java
{ "resource": "" }
q20398
ForwardingClient.getLocalForwardingTunnels
train
public ActiveTunnel[] getLocalForwardingTunnels() throws IOException { Vector<ActiveTunnel> v = new Vector<ActiveTunnel>(); String[] localForwardings = getLocalForwardings(); for (int i = 0; i < localForwardings.length; i++) { ActiveTunnel[] tmp = getLocalForwardingTunnels(localForwardings[i]); for (int x = 0; x < tmp.length; x++) { v.add(tmp[x]); } } return (ActiveTunnel[]) v.toArray(new ActiveTunnel[v.size()]); }
java
{ "resource": "" }
q20399
ForwardingClient.getX11ForwardingTunnels
train
public ActiveTunnel[] getX11ForwardingTunnels() throws IOException { if (incomingtunnels.containsKey(X11_KEY)) { Vector<ActiveTunnel> v = incomingtunnels.get(X11_KEY); ActiveTunnel[] t = new ActiveTunnel[v.size()]; v.copyInto(t); return t; } return new ActiveTunnel[] {}; }
java
{ "resource": "" }