_id
stringlengths
2
7
title
stringlengths
3
140
partition
stringclasses
3 values
text
stringlengths
73
34.1k
language
stringclasses
1 value
meta_information
dict
q6700
CachedConnectionStrategy.threadWatch
train
protected void threadWatch(final ConnectionHandle c) { this.threadFinalizableRefs.put(c, new FinalizableWeakReference<Thread>(Thread.currentThread(), this.finalizableRefQueue) { public void finalizeReferent() { try { if (!CachedConnectionStrategy.this.pool.poolShuttingDown){ logger.debug("Monitored thread is dead, closing off allocated connection."); } c.internalClose(); } catch (SQLException e) { e.printStackTrace(); } CachedConnectionStrategy.this.threadFinalizableRefs.remove(c); } }); }
java
{ "resource": "" }
q6701
BoneCP.shutdown
train
public synchronized void shutdown(){ if (!this.poolShuttingDown){ logger.info("Shutting down connection pool..."); this.poolShuttingDown = true; this.shutdownStackTrace = captureStackTrace(SHUTDOWN_LOCATION_TRACE); this.keepAliveScheduler.shutdownNow(); // stop threads from firing. this.maxAliveScheduler.shutdownNow(); // stop threads from firing. this.connectionsScheduler.shutdownNow(); // stop threads from firing. this.asyncExecutor.shutdownNow(); try { this.connectionsScheduler.awaitTermination(5, TimeUnit.SECONDS); this.maxAliveScheduler.awaitTermination(5, TimeUnit.SECONDS); this.keepAliveScheduler.awaitTermination(5, TimeUnit.SECONDS); this.asyncExecutor.awaitTermination(5, TimeUnit.SECONDS); if (this.closeConnectionExecutor != null){ this.closeConnectionExecutor.shutdownNow(); this.closeConnectionExecutor.awaitTermination(5, TimeUnit.SECONDS); } } catch (InterruptedException e) { // do nothing } this.connectionStrategy.terminateAllConnections(); unregisterDriver(); registerUnregisterJMX(false); if (finalizableRefQueue != null) { finalizableRefQueue.close(); } logger.info("Connection pool has been shutdown."); } }
java
{ "resource": "" }
q6702
BoneCP.unregisterDriver
train
protected void unregisterDriver(){ String jdbcURL = this.config.getJdbcUrl(); if ((jdbcURL != null) && this.config.isDeregisterDriverOnClose()){ logger.info("Unregistering JDBC driver for : "+jdbcURL); try { DriverManager.deregisterDriver(DriverManager.getDriver(jdbcURL)); } catch (SQLException e) { logger.info("Unregistering driver failed.", e); } } }
java
{ "resource": "" }
q6703
BoneCP.destroyConnection
train
protected void destroyConnection(ConnectionHandle conn) { postDestroyConnection(conn); conn.setInReplayMode(true); // we're dead, stop attempting to replay anything try { conn.internalClose(); } catch (SQLException e) { logger.error("Error in attempting to close connection", e); } }
java
{ "resource": "" }
q6704
BoneCP.postDestroyConnection
train
protected void postDestroyConnection(ConnectionHandle handle){ ConnectionPartition partition = handle.getOriginatingPartition(); if (this.finalizableRefQueue != null && handle.getInternalConnection() != null){ //safety this.finalizableRefs.remove(handle.getInternalConnection()); // assert o != null : "Did not manage to remove connection from finalizable ref queue"; } partition.updateCreatedConnections(-1); partition.setUnableToCreateMoreTransactions(false); // we can create new ones now, this is an optimization // "Destroying" for us means: don't put it back in the pool. if (handle.getConnectionHook() != null){ handle.getConnectionHook().onDestroy(handle); } }
java
{ "resource": "" }
q6705
BoneCP.obtainInternalConnection
train
protected Connection obtainInternalConnection(ConnectionHandle connectionHandle) throws SQLException { boolean tryAgain = false; Connection result = null; Connection oldRawConnection = connectionHandle.getInternalConnection(); String url = this.getConfig().getJdbcUrl(); int acquireRetryAttempts = this.getConfig().getAcquireRetryAttempts(); long acquireRetryDelayInMs = this.getConfig().getAcquireRetryDelayInMs(); AcquireFailConfig acquireConfig = new AcquireFailConfig(); acquireConfig.setAcquireRetryAttempts(new AtomicInteger(acquireRetryAttempts)); acquireConfig.setAcquireRetryDelayInMs(acquireRetryDelayInMs); acquireConfig.setLogMessage("Failed to acquire connection to "+url); ConnectionHook connectionHook = this.getConfig().getConnectionHook(); do{ result = null; try { // keep track of this hook. result = this.obtainRawInternalConnection(); tryAgain = false; if (acquireRetryAttempts != this.getConfig().getAcquireRetryAttempts()){ logger.info("Successfully re-established connection to "+url); } this.getDbIsDown().set(false); connectionHandle.setInternalConnection(result); // call the hook, if available. if (connectionHook != null){ connectionHook.onAcquire(connectionHandle); } ConnectionHandle.sendInitSQL(result, this.getConfig().getInitSQL()); } catch (SQLException e) { // call the hook, if available. if (connectionHook != null){ tryAgain = connectionHook.onAcquireFail(e, acquireConfig); } else { logger.error(String.format("Failed to acquire connection to %s. Sleeping for %d ms. Attempts left: %d", url, acquireRetryDelayInMs, acquireRetryAttempts), e); try { if (acquireRetryAttempts > 0){ Thread.sleep(acquireRetryDelayInMs); } tryAgain = (acquireRetryAttempts--) > 0; } catch (InterruptedException e1) { tryAgain=false; } } if (!tryAgain){ if (oldRawConnection != null) { oldRawConnection.close(); } if (result != null) { result.close(); } connectionHandle.setInternalConnection(oldRawConnection); throw e; } } } while (tryAgain); return result; }
java
{ "resource": "" }
q6706
BoneCP.registerUnregisterJMX
train
protected void registerUnregisterJMX(boolean doRegister) { if (this.mbs == null ){ // this way makes it easier for mocking. this.mbs = ManagementFactory.getPlatformMBeanServer(); } try { String suffix = ""; if (this.config.getPoolName()!=null){ suffix="-"+this.config.getPoolName(); } ObjectName name = new ObjectName(MBEAN_BONECP +suffix); ObjectName configname = new ObjectName(MBEAN_CONFIG + suffix); if (doRegister){ if (!this.mbs.isRegistered(name)){ this.mbs.registerMBean(this.statistics, name); } if (!this.mbs.isRegistered(configname)){ this.mbs.registerMBean(this.config, configname); } } else { if (this.mbs.isRegistered(name)){ this.mbs.unregisterMBean(name); } if (this.mbs.isRegistered(configname)){ this.mbs.unregisterMBean(configname); } } } catch (Exception e) { logger.error("Unable to start/stop JMX", e); } }
java
{ "resource": "" }
q6707
BoneCP.watchConnection
train
protected void watchConnection(ConnectionHandle connectionHandle) { String message = captureStackTrace(UNCLOSED_EXCEPTION_MESSAGE); this.closeConnectionExecutor.submit(new CloseThreadMonitor(Thread.currentThread(), connectionHandle, message, this.closeConnectionWatchTimeoutInMs)); }
java
{ "resource": "" }
q6708
BoneCP.getAsyncConnection
train
public ListenableFuture<Connection> getAsyncConnection(){ return this.asyncExecutor.submit(new Callable<Connection>() { public Connection call() throws Exception { return getConnection(); }}); }
java
{ "resource": "" }
q6709
BoneCP.maybeSignalForMoreConnections
train
protected void maybeSignalForMoreConnections(ConnectionPartition connectionPartition) { if (!connectionPartition.isUnableToCreateMoreTransactions() && !this.poolShuttingDown && connectionPartition.getAvailableConnections()*100/connectionPartition.getMaxConnections() <= this.poolAvailabilityThreshold){ connectionPartition.getPoolWatchThreadSignalQueue().offer(new Object()); // item being pushed is not important. } }
java
{ "resource": "" }
q6710
BoneCP.internalReleaseConnection
train
protected void internalReleaseConnection(ConnectionHandle connectionHandle) throws SQLException { if (!this.cachedPoolStrategy){ connectionHandle.clearStatementCaches(false); } if (connectionHandle.getReplayLog() != null){ connectionHandle.getReplayLog().clear(); connectionHandle.recoveryResult.getReplaceTarget().clear(); } if (connectionHandle.isExpired() || (!this.poolShuttingDown && connectionHandle.isPossiblyBroken() && !isConnectionHandleAlive(connectionHandle))){ if (connectionHandle.isExpired()) { connectionHandle.internalClose(); } ConnectionPartition connectionPartition = connectionHandle.getOriginatingPartition(); postDestroyConnection(connectionHandle); maybeSignalForMoreConnections(connectionPartition); connectionHandle.clearStatementCaches(true); return; // don't place back in queue - connection is broken or expired. } connectionHandle.setConnectionLastUsedInMs(System.currentTimeMillis()); if (!this.poolShuttingDown){ putConnectionBackInPartition(connectionHandle); } else { connectionHandle.internalClose(); } }
java
{ "resource": "" }
q6711
BoneCP.putConnectionBackInPartition
train
protected void putConnectionBackInPartition(ConnectionHandle connectionHandle) throws SQLException { if (this.cachedPoolStrategy && ((CachedConnectionStrategy)this.connectionStrategy).tlConnections.dumbGet().getValue()){ connectionHandle.logicallyClosed.set(true); ((CachedConnectionStrategy)this.connectionStrategy).tlConnections.set(new AbstractMap.SimpleEntry<ConnectionHandle, Boolean>(connectionHandle, false)); } else { BlockingQueue<ConnectionHandle> queue = connectionHandle.getOriginatingPartition().getFreeConnections(); if (!queue.offer(connectionHandle)){ // this shouldn't fail connectionHandle.internalClose(); } } }
java
{ "resource": "" }
q6712
BoneCP.isConnectionHandleAlive
train
public boolean isConnectionHandleAlive(ConnectionHandle connection) { Statement stmt = null; boolean result = false; boolean logicallyClosed = connection.logicallyClosed.get(); try { connection.logicallyClosed.compareAndSet(true, false); // avoid checks later on if it's marked as closed. String testStatement = this.config.getConnectionTestStatement(); ResultSet rs = null; if (testStatement == null) { // Make a call to fetch the metadata instead of a dummy query. rs = connection.getMetaData().getTables( null, null, KEEPALIVEMETADATA, METADATATABLE ); } else { stmt = connection.createStatement(); stmt.execute(testStatement); } if (rs != null) { rs.close(); } result = true; } catch (SQLException e) { // connection must be broken! result = false; } finally { connection.logicallyClosed.set(logicallyClosed); connection.setConnectionLastResetInMs(System.currentTimeMillis()); result = closeStatement(stmt, result); } return result; }
java
{ "resource": "" }
q6713
BoneCP.getTotalLeased
train
public int getTotalLeased(){ int total=0; for (int i=0; i < this.partitionCount && this.partitions[i] != null; i++){ total+=this.partitions[i].getCreatedConnections()-this.partitions[i].getAvailableConnections(); } return total; }
java
{ "resource": "" }
q6714
BoneCP.getTotalCreatedConnections
train
public int getTotalCreatedConnections(){ int total=0; for (int i=0; i < this.partitionCount && this.partitions[i] != null; i++){ total+=this.partitions[i].getCreatedConnections(); } return total; }
java
{ "resource": "" }
q6715
ConnectionPartition.addFreeConnection
train
protected void addFreeConnection(ConnectionHandle connectionHandle) throws SQLException{ connectionHandle.setOriginatingPartition(this); // assume success to avoid racing where we insert an item in a queue and having that item immediately // taken and closed off thus decrementing the created connection count. updateCreatedConnections(1); if (!this.disableTracking){ trackConnectionFinalizer(connectionHandle); } // the instant the following line is executed, consumers can start making use of this // connection. if (!this.freeConnections.offer(connectionHandle)){ // we failed. rollback. updateCreatedConnections(-1); // compensate our createdConnection count. if (!this.disableTracking){ this.pool.getFinalizableRefs().remove(connectionHandle.getInternalConnection()); } // terminate the internal handle. connectionHandle.internalClose(); } }
java
{ "resource": "" }
q6716
DefaultConnectionStrategy.terminateAllConnections
train
public void terminateAllConnections(){ this.terminationLock.lock(); try{ // close off all connections. for (int i=0; i < this.pool.partitionCount; i++) { this.pool.partitions[i].setUnableToCreateMoreTransactions(false); // we can create new ones now, this is an optimization List<ConnectionHandle> clist = new LinkedList<ConnectionHandle>(); this.pool.partitions[i].getFreeConnections().drainTo(clist); for (ConnectionHandle c: clist){ this.pool.destroyConnection(c); } } } finally { this.terminationLock.unlock(); } }
java
{ "resource": "" }
q6717
StatementHandle.queryTimerEnd
train
protected void queryTimerEnd(String sql, long queryStartTime) { if ((this.queryExecuteTimeLimit != 0) && (this.connectionHook != null)){ long timeElapsed = (System.nanoTime() - queryStartTime); if (timeElapsed > this.queryExecuteTimeLimit){ this.connectionHook.onQueryExecuteTimeLimitExceeded(this.connectionHandle, this, sql, this.logParams, timeElapsed); } } if (this.statisticsEnabled){ this.statistics.incrementStatementsExecuted(); this.statistics.addStatementExecuteTime(System.nanoTime() - queryStartTime); } }
java
{ "resource": "" }
q6718
ProcessUtil.getMBeanServerConnection
train
public static MBeanServerConnection getMBeanServerConnection(Process p, boolean startAgent) { try { final JMXServiceURL serviceURL = getLocalConnectorAddress(p, startAgent); final JMXConnector connector = JMXConnectorFactory.connect(serviceURL); final MBeanServerConnection mbsc = connector.getMBeanServerConnection(); return mbsc; } catch (Exception e) { throw new RuntimeException(e); } }
java
{ "resource": "" }
q6719
ProcessUtil.getLocalConnectorAddress
train
public static JMXServiceURL getLocalConnectorAddress(Process p, boolean startAgent) { return getLocalConnectorAddress(Integer.toString(getPid(p)), startAgent); }
java
{ "resource": "" }
q6720
Jar.setAttribute
train
public final Jar setAttribute(String name, String value) { verifyNotSealed(); if (jos != null) throw new IllegalStateException("Manifest cannot be modified after entries are added."); getManifest().getMainAttributes().putValue(name, value); return this; }
java
{ "resource": "" }
q6721
Jar.setAttribute
train
public final Jar setAttribute(String section, String name, String value) { verifyNotSealed(); if (jos != null) throw new IllegalStateException("Manifest cannot be modified after entries are added."); Attributes attr = getManifest().getAttributes(section); if (attr == null) { attr = new Attributes(); getManifest().getEntries().put(section, attr); } attr.putValue(name, value); return this; }
java
{ "resource": "" }
q6722
Jar.setListAttribute
train
public Jar setListAttribute(String name, Collection<?> values) { return setAttribute(name, join(values)); }
java
{ "resource": "" }
q6723
Jar.setMapAttribute
train
public Jar setMapAttribute(String name, Map<String, ?> values) { return setAttribute(name, join(values)); }
java
{ "resource": "" }
q6724
Jar.getAttribute
train
public String getAttribute(String section, String name) { Attributes attr = getManifest().getAttributes(section); return attr != null ? attr.getValue(name) : null; }
java
{ "resource": "" }
q6725
Jar.getListAttribute
train
public List<String> getListAttribute(String section, String name) { return split(getAttribute(section, name)); }
java
{ "resource": "" }
q6726
Jar.getMapAttribute
train
public Map<String, String> getMapAttribute(String name, String defaultValue) { return mapSplit(getAttribute(name), defaultValue); }
java
{ "resource": "" }
q6727
Jar.addClass
train
public Jar addClass(Class<?> clazz) throws IOException { final String resource = clazz.getName().replace('.', '/') + ".class"; return addEntry(resource, clazz.getClassLoader().getResourceAsStream(resource)); }
java
{ "resource": "" }
q6728
Jar.addPackageOf
train
public Jar addPackageOf(Class<?> clazz, Filter filter) throws IOException { try { final String path = clazz.getPackage().getName().replace('.', '/'); URL dirURL = clazz.getClassLoader().getResource(path); if (dirURL != null && dirURL.getProtocol().equals("file")) addDir(Paths.get(path), Paths.get(dirURL.toURI()), filter, false); else { if (dirURL == null) // In case of a jar file, we can't actually find a directory. dirURL = clazz.getClassLoader().getResource(clazz.getName().replace('.', '/') + ".class"); if (dirURL.getProtocol().equals("jar")) { final URI jarUri = new URI(dirURL.getPath().substring(0, dirURL.getPath().indexOf('!'))); try (JarInputStream jis1 = newJarInputStream(Files.newInputStream(Paths.get(jarUri)))) { for (JarEntry entry; (entry = jis1.getNextJarEntry()) != null;) { try { if (entry.getName().startsWith(path + '/')) { if (filter == null || filter.filter(entry.getName())) addEntryNoClose(jos, entry.getName(), jis1); } } catch (ZipException e) { if (!e.getMessage().startsWith("duplicate entry")) throw e; } } } } else throw new AssertionError(); } return this; } catch (URISyntaxException e) { throw new AssertionError(e); } }
java
{ "resource": "" }
q6729
Jar.setJarPrefix
train
public Jar setJarPrefix(String value) { verifyNotSealed(); if (jos != null) throw new IllegalStateException("Really executable cannot be set after entries are added."); if (value != null && jarPrefixFile != null) throw new IllegalStateException("A prefix has already been set (" + jarPrefixFile + ")"); this.jarPrefixStr = value; return this; }
java
{ "resource": "" }
q6730
Jar.setJarPrefix
train
public Jar setJarPrefix(Path file) { verifyNotSealed(); if (jos != null) throw new IllegalStateException("Really executable cannot be set after entries are added."); if (file != null && jarPrefixStr != null) throw new IllegalStateException("A prefix has already been set (" + jarPrefixStr + ")"); this.jarPrefixFile = file; return this; }
java
{ "resource": "" }
q6731
Jar.write
train
public <T extends OutputStream> T write(T os) throws IOException { close(); if (!(this.os instanceof ByteArrayOutputStream)) throw new IllegalStateException("Cannot write to another target if setOutputStream has been called"); final byte[] content = ((ByteArrayOutputStream) this.os).toByteArray(); if (packer != null) packer.pack(new JarInputStream(new ByteArrayInputStream(content)), os); else os.write(content); os.close(); return os; }
java
{ "resource": "" }
q6732
CapsuleLauncher.newCapsule
train
public Capsule newCapsule(String mode, Path wrappedJar) { final String oldMode = properties.getProperty(PROP_MODE); final ClassLoader oldCl = Thread.currentThread().getContextClassLoader(); Thread.currentThread().setContextClassLoader(capsuleClass.getClassLoader()); try { setProperty(PROP_MODE, mode); final Constructor<?> ctor = accessible(capsuleClass.getDeclaredConstructor(Path.class)); final Object capsule = ctor.newInstance(jarFile); if (wrappedJar != null) { final Method setTarget = accessible(capsuleClass.getDeclaredMethod("setTarget", Path.class)); setTarget.invoke(capsule, wrappedJar); } return wrap(capsule); } catch (ReflectiveOperationException e) { throw new RuntimeException("Could not create capsule instance.", e); } finally { setProperty(PROP_MODE, oldMode); Thread.currentThread().setContextClassLoader(oldCl); } }
java
{ "resource": "" }
q6733
CapsuleLauncher.findJavaHomes
train
@SuppressWarnings("unchecked") public static Map<String, List<Path>> findJavaHomes() { try { return (Map<String, List<Path>>) accessible(Class.forName(CAPSULE_CLASS_NAME).getDeclaredMethod("getJavaHomes")).invoke(null); } catch (ReflectiveOperationException e) { throw new AssertionError(e); } }
java
{ "resource": "" }
q6734
CapsuleLauncher.enableJMX
train
public static List<String> enableJMX(List<String> jvmArgs) { final String arg = "-D" + OPT_JMX_REMOTE; if (jvmArgs.contains(arg)) return jvmArgs; final List<String> cmdLine2 = new ArrayList<>(jvmArgs); cmdLine2.add(arg); return cmdLine2; }
java
{ "resource": "" }
q6735
ChromeCast.setVolumeByIncrement
train
public final void setVolumeByIncrement(float level) throws IOException { Volume volume = this.getStatus().volume; float total = volume.level; if (volume.increment <= 0f) { throw new ChromeCastException("Volume.increment is <= 0"); } // With floating points we always have minor decimal variations, using the Math.min/max // works around this issue // Increase volume if (level > total) { while (total < level) { total = Math.min(total + volume.increment, level); setVolume(total); } // Decrease Volume } else if (level < total) { while (total > level) { total = Math.max(total - volume.increment, level); setVolume(total); } } }
java
{ "resource": "" }
q6736
Channel.connect
train
private void connect() throws IOException, GeneralSecurityException { synchronized (closedSync) { if (socket == null || socket.isClosed()) { SSLContext sc = SSLContext.getInstance("SSL"); sc.init(null, new TrustManager[] { new X509TrustAllManager() }, new SecureRandom()); socket = sc.getSocketFactory().createSocket(); socket.connect(address); } /** * Authenticate */ CastChannel.DeviceAuthMessage authMessage = CastChannel.DeviceAuthMessage.newBuilder() .setChallenge(CastChannel.AuthChallenge.newBuilder().build()) .build(); CastChannel.CastMessage msg = CastChannel.CastMessage.newBuilder() .setDestinationId(DEFAULT_RECEIVER_ID) .setNamespace("urn:x-cast:com.google.cast.tp.deviceauth") .setPayloadType(CastChannel.CastMessage.PayloadType.BINARY) .setProtocolVersion(CastChannel.CastMessage.ProtocolVersion.CASTV2_1_0) .setSourceId(name) .setPayloadBinary(authMessage.toByteString()) .build(); write(msg); CastChannel.CastMessage response = read(); CastChannel.DeviceAuthMessage authResponse = CastChannel.DeviceAuthMessage.parseFrom(response.getPayloadBinary()); if (authResponse.hasError()) { throw new ChromeCastException("Authentication failed: " + authResponse.getError().getErrorType().toString()); } /** * Send 'PING' message */ PingThread pingThread = new PingThread(); pingThread.run(); /** * Send 'CONNECT' message to start session */ write("urn:x-cast:com.google.cast.tp.connection", StandardMessage.connect(), DEFAULT_RECEIVER_ID); /** * Start ping/pong and reader thread */ pingTimer = new Timer(name + " PING"); pingTimer.schedule(pingThread, 1000, PING_PERIOD); reader = new ReadThread(); reader.start(); if (closed) { closed = false; notifyListenerOfConnectionEvent(true); } } }
java
{ "resource": "" }
q6737
ExecutorServiceUtils.newSingleThreadDaemonExecutor
train
public static ExecutorService newSingleThreadDaemonExecutor() { return Executors.newSingleThreadExecutor(r -> { Thread t = Executors.defaultThreadFactory().newThread(r); t.setDaemon(true); return t; }); }
java
{ "resource": "" }
q6738
ExecutorServiceUtils.newScheduledDaemonThreadPool
train
public static ScheduledExecutorService newScheduledDaemonThreadPool(int corePoolSize) { return Executors.newScheduledThreadPool(corePoolSize, r -> { Thread t = Executors.defaultThreadFactory().newThread(r); t.setDaemon(true); return t; }); }
java
{ "resource": "" }
q6739
MenuDrawer.createMenuDrawer
train
private static MenuDrawer createMenuDrawer(Activity activity, int dragMode, Position position, Type type) { MenuDrawer drawer; if (type == Type.STATIC) { drawer = new StaticDrawer(activity); } else if (type == Type.OVERLAY) { drawer = new OverlayDrawer(activity, dragMode); if (position == Position.LEFT || position == Position.START) { drawer.setupUpIndicator(activity); } } else { drawer = new SlidingDrawer(activity, dragMode); if (position == Position.LEFT || position == Position.START) { drawer.setupUpIndicator(activity); } } drawer.mDragMode = dragMode; drawer.setPosition(position); return drawer; }
java
{ "resource": "" }
q6740
MenuDrawer.attachToContent
train
private static void attachToContent(Activity activity, MenuDrawer menuDrawer) { /** * Do not call mActivity#setContentView. * E.g. if using with a ListActivity, Activity#setContentView is overridden and dispatched to * MenuDrawer#setContentView, which then again would call Activity#setContentView. */ ViewGroup content = (ViewGroup) activity.findViewById(android.R.id.content); content.removeAllViews(); content.addView(menuDrawer, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); }
java
{ "resource": "" }
q6741
MenuDrawer.attachToDecor
train
private static void attachToDecor(Activity activity, MenuDrawer menuDrawer) { ViewGroup decorView = (ViewGroup) activity.getWindow().getDecorView(); ViewGroup decorChild = (ViewGroup) decorView.getChildAt(0); decorView.removeAllViews(); decorView.addView(menuDrawer, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); menuDrawer.mContentContainer.addView(decorChild, decorChild.getLayoutParams()); }
java
{ "resource": "" }
q6742
MenuDrawer.setActiveView
train
public void setActiveView(View v, int position) { final View oldView = mActiveView; mActiveView = v; mActivePosition = position; if (mAllowIndicatorAnimation && oldView != null) { startAnimatingIndicator(); } invalidate(); }
java
{ "resource": "" }
q6743
MenuDrawer.getIndicatorStartPos
train
private int getIndicatorStartPos() { switch (getPosition()) { case TOP: return mIndicatorClipRect.left; case RIGHT: return mIndicatorClipRect.top; case BOTTOM: return mIndicatorClipRect.left; default: return mIndicatorClipRect.top; } }
java
{ "resource": "" }
q6744
MenuDrawer.animateIndicatorInvalidate
train
private void animateIndicatorInvalidate() { if (mIndicatorScroller.computeScrollOffset()) { mIndicatorOffset = mIndicatorScroller.getCurr(); invalidate(); if (!mIndicatorScroller.isFinished()) { postOnAnimation(mIndicatorRunnable); return; } } completeAnimatingIndicator(); }
java
{ "resource": "" }
q6745
MenuDrawer.setDropShadowColor
train
public void setDropShadowColor(int color) { GradientDrawable.Orientation orientation = getDropShadowOrientation(); final int endColor = color & 0x00FFFFFF; mDropShadowDrawable = new GradientDrawable(orientation, new int[] { color, endColor, }); invalidate(); }
java
{ "resource": "" }
q6746
MenuDrawer.setSlideDrawable
train
public void setSlideDrawable(Drawable drawable) { mSlideDrawable = new SlideDrawable(drawable); mSlideDrawable.setIsRtl(ViewHelper.getLayoutDirection(this) == LAYOUT_DIRECTION_RTL); if (mActionBarHelper != null) { mActionBarHelper.setDisplayShowHomeAsUpEnabled(true); if (mDrawerIndicatorEnabled) { mActionBarHelper.setActionBarUpIndicator(mSlideDrawable, isMenuVisible() ? mDrawerOpenContentDesc : mDrawerClosedContentDesc); } } }
java
{ "resource": "" }
q6747
MenuDrawer.getContentContainer
train
public ViewGroup getContentContainer() { if (mDragMode == MENU_DRAG_CONTENT) { return mContentContainer; } else { return (ViewGroup) findViewById(android.R.id.content); } }
java
{ "resource": "" }
q6748
MenuDrawer.setMenuView
train
public void setMenuView(int layoutResId) { mMenuContainer.removeAllViews(); mMenuView = LayoutInflater.from(getContext()).inflate(layoutResId, mMenuContainer, false); mMenuContainer.addView(mMenuView); }
java
{ "resource": "" }
q6749
BottomDrawerSample.onClick
train
@Override public void onClick(View v) { String tag = (String) v.getTag(); mContentTextView.setText(String.format("%s clicked.", tag)); mMenuDrawer.setActiveView(v); }
java
{ "resource": "" }
q6750
DraggableDrawer.animateOffsetTo
train
protected void animateOffsetTo(int position, int velocity, boolean animate) { endDrag(); endPeek(); final int startX = (int) mOffsetPixels; final int dx = position - startX; if (dx == 0 || !animate) { setOffsetPixels(position); setDrawerState(position == 0 ? STATE_CLOSED : STATE_OPEN); stopLayerTranslation(); return; } int duration; velocity = Math.abs(velocity); if (velocity > 0) { duration = 4 * Math.round(1000.f * Math.abs((float) dx / velocity)); } else { duration = (int) (600.f * Math.abs((float) dx / mMenuSize)); } duration = Math.min(duration, mMaxAnimationDuration); animateOffsetTo(position, duration); }
java
{ "resource": "" }
q6751
ParsedLineIterator.pollParsedWord
train
public ParsedWord pollParsedWord() { if(hasNextWord()) { //set correct next char if(parsedLine.words().size() > (word+1)) character = parsedLine.words().get(word+1).lineIndex(); else character = -1; return parsedLine.words().get(word++); } else return new ParsedWord(null, -1); }
java
{ "resource": "" }
q6752
ParsedLineIterator.pollChar
train
public char pollChar() { if(hasNextChar()) { if(hasNextWord() && character+1 >= parsedLine.words().get(word).lineIndex()+ parsedLine.words().get(word).word().length()) word++; return parsedLine.line().charAt(character++); } return '\u0000'; }
java
{ "resource": "" }
q6753
ParsedLineIterator.updateIteratorPosition
train
public void updateIteratorPosition(int length) { if(length > 0) { //make sure we dont go OB if((length + character) > parsedLine.line().length()) length = parsedLine.line().length() - character; //move word counter to the correct word while(hasNextWord() && (length + character) >= parsedLine.words().get(word).lineIndex() + parsedLine.words().get(word).word().length()) word++; character = length + character; } else throw new IllegalArgumentException("The length given must be > 0 and not exceed the boundary of the line (including the current position)"); }
java
{ "resource": "" }
q6754
AeshCommandLineParser.printHelp
train
@Override public String printHelp() { List<CommandLineParser<CI>> parsers = getChildParsers(); if (parsers != null && parsers.size() > 0) { StringBuilder sb = new StringBuilder(); sb.append(processedCommand.printHelp(helpNames())) .append(Config.getLineSeparator()) .append(processedCommand.name()) .append(" commands:") .append(Config.getLineSeparator()); int maxLength = 0; for (CommandLineParser child : parsers) { int length = child.getProcessedCommand().name().length(); if (length > maxLength) { maxLength = length; } } for (CommandLineParser child : parsers) { sb.append(child.getFormattedCommand(4, maxLength + 2)) .append(Config.getLineSeparator()); } return sb.toString(); } else return processedCommand.printHelp(helpNames()); }
java
{ "resource": "" }
q6755
AeshCommandLineParser.parse
train
@Override public void parse(String line, Mode mode) { parse(lineParser.parseLine(line, line.length()).iterator(), mode); }
java
{ "resource": "" }
q6756
AeshCommandPopulator.populateObject
train
@Override public void populateObject(ProcessedCommand<Command<CI>, CI> processedCommand, InvocationProviders invocationProviders, AeshContext aeshContext, CommandLineParser.Mode mode) throws CommandLineParserException, OptionValidatorException { if(processedCommand.parserExceptions().size() > 0 && mode == CommandLineParser.Mode.VALIDATE) throw processedCommand.parserExceptions().get(0); for(ProcessedOption option : processedCommand.getOptions()) { if(option.getValues() != null && option.getValues().size() > 0) option.injectValueIntoField(getObject(), invocationProviders, aeshContext, mode == CommandLineParser.Mode.VALIDATE ); else if(option.getDefaultValues().size() > 0) { option.injectValueIntoField(getObject(), invocationProviders, aeshContext, mode == CommandLineParser.Mode.VALIDATE); } else if(option.getOptionType().equals(OptionType.GROUP) && option.getProperties().size() > 0) option.injectValueIntoField(getObject(), invocationProviders, aeshContext, mode == CommandLineParser.Mode.VALIDATE); else resetField(getObject(), option.getFieldName(), option.hasValue()); } //arguments if(processedCommand.getArguments() != null && (processedCommand.getArguments().getValues().size() > 0 || processedCommand.getArguments().getDefaultValues().size() > 0)) processedCommand.getArguments().injectValueIntoField(getObject(), invocationProviders, aeshContext, mode == CommandLineParser.Mode.VALIDATE); else if(processedCommand.getArguments() != null) resetField(getObject(), processedCommand.getArguments().getFieldName(), true); //argument if(processedCommand.getArgument() != null && (processedCommand.getArgument().getValues().size() > 0 || processedCommand.getArgument().getDefaultValues().size() > 0)) processedCommand.getArgument().injectValueIntoField(getObject(), invocationProviders, aeshContext, mode == CommandLineParser.Mode.VALIDATE); else if(processedCommand.getArgument() != null) resetField(getObject(), processedCommand.getArgument().getFieldName(), true); }
java
{ "resource": "" }
q6757
ProcessedCommand.getOptionLongNamesWithDash
train
public List<TerminalString> getOptionLongNamesWithDash() { List<ProcessedOption> opts = getOptions(); List<TerminalString> names = new ArrayList<>(opts.size()); for (ProcessedOption o : opts) { if(o.getValues().size() == 0 && o.activator().isActivated(new ParsedCommand(this))) names.add(o.getRenderedNameWithDashes()); } return names; }
java
{ "resource": "" }
q6758
ProcessedCommand.printHelp
train
public String printHelp(String commandName) { int maxLength = 0; int width = 80; List<ProcessedOption> opts = getOptions(); for (ProcessedOption o : opts) { if(o.getFormattedLength() > maxLength) maxLength = o.getFormattedLength(); } StringBuilder sb = new StringBuilder(); //first line sb.append("Usage: "); if(commandName == null || commandName.length() == 0) sb.append(name()); else sb.append(commandName); if(opts.size() > 0) sb.append(" [<options>]"); if(argument != null) { if(argument.isTypeAssignableByResourcesOrFile()) sb.append(" <file>"); else sb.append(" <").append(argument.getFieldName()).append(">"); } if(arguments != null) { if(arguments.isTypeAssignableByResourcesOrFile()) sb.append(" [<files>]"); else sb.append(" [<").append(arguments.getFieldName()).append(">]"); } sb.append(Config.getLineSeparator()); //second line sb.append(description()).append(Config.getLineSeparator()); //options and arguments if (opts.size() > 0) sb.append(Config.getLineSeparator()).append("Options:").append(Config.getLineSeparator()); for (ProcessedOption o : opts) sb.append(o.getFormattedOption(2, maxLength+4, width)).append(Config.getLineSeparator()); if(arguments != null) { sb.append(Config.getLineSeparator()).append("Arguments:").append(Config.getLineSeparator()); sb.append(arguments.getFormattedOption(2, maxLength+4, width)).append(Config.getLineSeparator()); } if(argument != null) { sb.append(Config.getLineSeparator()).append("Argument:").append(Config.getLineSeparator()); sb.append(argument.getFormattedOption(2, maxLength+4, width)).append(Config.getLineSeparator()); } return sb.toString(); }
java
{ "resource": "" }
q6759
ProcessedCommand.hasUniqueLongOption
train
public boolean hasUniqueLongOption(String optionName) { if(hasLongOption(optionName)) { for(ProcessedOption o : getOptions()) { if(o.name().startsWith(optionName) && !o.name().equals(optionName)) return false; } return true; } return false; }
java
{ "resource": "" }
q6760
ClassFileBuffer.seek
train
public void seek(final int position) throws IOException { if (position < 0) { throw new IllegalArgumentException("position < 0: " + position); } if (position > size) { throw new EOFException(); } this.pointer = position; }
java
{ "resource": "" }
q6761
SettingsImpl.editMode
train
@Override public EditMode editMode() { if(readInputrc) { try { return EditModeBuilder.builder().parseInputrc(new FileInputStream(inputrc())).create(); } catch(FileNotFoundException e) { return EditModeBuilder.builder(mode()).create(); } } else return EditModeBuilder.builder(mode()).create(); }
java
{ "resource": "" }
q6762
SettingsImpl.logFile
train
@Override public String logFile() { if(logFile == null) { logFile = Config.getTmpDir()+Config.getPathSeparator()+"aesh.log"; } return logFile; }
java
{ "resource": "" }
q6763
AnnotationDetector.detect
train
public void detect(final String... packageNames) throws IOException { final String[] pkgNameFilter = new String[packageNames.length]; for (int i = 0; i < pkgNameFilter.length; ++i) { pkgNameFilter[i] = packageNames[i].replace('.', '/'); if (!pkgNameFilter[i].endsWith("/")) { pkgNameFilter[i] = pkgNameFilter[i].concat("/"); } } final Set<File> files = new HashSet<>(); final ClassLoader loader = Thread.currentThread().getContextClassLoader(); for (final String packageName : pkgNameFilter) { final Enumeration<URL> resourceEnum = loader.getResources(packageName); while (resourceEnum.hasMoreElements()) { final URL url = resourceEnum.nextElement(); if ("file".equals(url.getProtocol())) { final File dir = toFile(url); if (dir.isDirectory()) { files.add(dir); } else { throw new AssertionError("Not a recognized file URL: " + url); } } else { final File jarFile = toFile(openJarURLConnection(url).getJarFileURL()); if (jarFile.isFile()) { files.add(jarFile); } else { throw new AssertionError("Not a File: " + jarFile); } } } } if (DEBUG) { print("Files to scan: %s", files); } if (!files.isEmpty()) { // see http://shipilev.net/blog/2016/arrays-wisdom-ancients/#_conclusion detect(new ClassFileIterator(files.toArray(new File[0]), pkgNameFilter)); } }
java
{ "resource": "" }
q6764
FileIterator.addReverse
train
private void addReverse(final File[] files) { for (int i = files.length - 1; i >= 0; --i) { stack.add(files[i]); } }
java
{ "resource": "" }
q6765
ContextualStoreImpl.getContextual
train
public <C extends Contextual<I>, I> C getContextual(String id) { return this.<C, I>getContextual(new StringBeanIdentifier(id)); }
java
{ "resource": "" }
q6766
ConversationContextActivator.processDestructionQueue
train
private void processDestructionQueue(HttpServletRequest request) { Object contextsAttribute = request.getAttribute(DESTRUCTION_QUEUE_ATTRIBUTE_NAME); if (contextsAttribute instanceof Map) { Map<String, List<ContextualInstance<?>>> contexts = cast(contextsAttribute); synchronized (contexts) { FastEvent<String> beforeDestroyedEvent = FastEvent.of(String.class, beanManager, BeforeDestroyed.Literal.CONVERSATION); FastEvent<String> destroyedEvent = FastEvent.of(String.class, beanManager, Destroyed.Literal.CONVERSATION); for (Iterator<Entry<String, List<ContextualInstance<?>>>> iterator = contexts.entrySet().iterator(); iterator.hasNext();) { Entry<String, List<ContextualInstance<?>>> entry = iterator.next(); beforeDestroyedEvent.fire(entry.getKey()); for (ContextualInstance<?> contextualInstance : entry.getValue()) { destroyContextualInstance(contextualInstance); } // Note that for the attached/current conversation we fire the destroyed event twice because we can't reliably identify such a conversation destroyedEvent.fire(entry.getKey()); iterator.remove(); } } } }
java
{ "resource": "" }
q6767
SessionBeanAwareInjectionPointBean.unregisterContextualInstance
train
public static void unregisterContextualInstance(EjbDescriptor<?> descriptor) { Set<Class<?>> classes = CONTEXTUAL_SESSION_BEANS.get(); classes.remove(descriptor.getBeanClass()); if (classes.isEmpty()) { CONTEXTUAL_SESSION_BEANS.remove(); } }
java
{ "resource": "" }
q6768
StaticMethodInjectionPoint.getParameterValues
train
protected Object[] getParameterValues(Object specialVal, BeanManagerImpl manager, CreationalContext<?> ctx, CreationalContext<?> transientReferenceContext) { if (getInjectionPoints().isEmpty()) { if (specialInjectionPointIndex == -1) { return Arrays2.EMPTY_ARRAY; } else { return new Object[] { specialVal }; } } Object[] parameterValues = new Object[getParameterInjectionPoints().size()]; List<ParameterInjectionPoint<?, X>> parameters = getParameterInjectionPoints(); for (int i = 0; i < parameterValues.length; i++) { ParameterInjectionPoint<?, ?> param = parameters.get(i); if (i == specialInjectionPointIndex) { parameterValues[i] = specialVal; } else if (hasTransientReferenceParameter && param.getAnnotated().isAnnotationPresent(TransientReference.class)) { parameterValues[i] = param.getValueToInject(manager, transientReferenceContext); } else { parameterValues[i] = param.getValueToInject(manager, ctx); } } return parameterValues; }
java
{ "resource": "" }
q6769
SpecializationAndEnablementRegistry.resolveSpecializedBeans
train
public Set<? extends AbstractBean<?, ?>> resolveSpecializedBeans(Bean<?> specializingBean) { if (specializingBean instanceof AbstractClassBean<?>) { AbstractClassBean<?> abstractClassBean = (AbstractClassBean<?>) specializingBean; if (abstractClassBean.isSpecializing()) { return specializedBeans.getValue(specializingBean); } } if (specializingBean instanceof ProducerMethod<?, ?>) { ProducerMethod<?, ?> producerMethod = (ProducerMethod<?, ?>) specializingBean; if (producerMethod.isSpecializing()) { return specializedBeans.getValue(specializingBean); } } return Collections.emptySet(); }
java
{ "resource": "" }
q6770
DecoratorProxyFactory.addHandlerInitializerMethod
train
private void addHandlerInitializerMethod(ClassFile proxyClassType, ClassMethod staticConstructor) throws Exception { ClassMethod classMethod = proxyClassType.addMethod(AccessFlag.PRIVATE, INIT_MH_METHOD_NAME, BytecodeUtils.VOID_CLASS_DESCRIPTOR, LJAVA_LANG_OBJECT); final CodeAttribute b = classMethod.getCodeAttribute(); b.aload(0); StaticMethodInformation methodInfo = new StaticMethodInformation(INIT_MH_METHOD_NAME, new Class[] { Object.class }, void.class, classMethod.getClassFile().getName()); invokeMethodHandler(classMethod, methodInfo, false, DEFAULT_METHOD_RESOLVER, staticConstructor); b.checkcast(MethodHandler.class); b.putfield(classMethod.getClassFile().getName(), METHOD_HANDLER_FIELD_NAME, DescriptorUtils.makeDescriptor(MethodHandler.class)); b.returnInstruction(); BeanLogger.LOG.createdMethodHandlerInitializerForDecoratorProxy(getBeanType()); }
java
{ "resource": "" }
q6771
DecoratorProxyFactory.isEqual
train
private static boolean isEqual(Method m, Method a) { if (m.getName().equals(a.getName()) && m.getParameterTypes().length == a.getParameterTypes().length && m.getReturnType().isAssignableFrom(a.getReturnType())) { for (int i = 0; i < m.getParameterTypes().length; i++) { if (!(m.getParameterTypes()[i].isAssignableFrom(a.getParameterTypes()[i]))) { return false; } } return true; } return false; }
java
{ "resource": "" }
q6772
WeldServletLifecycle.createDeployment
train
protected CDI11Deployment createDeployment(ServletContext context, CDI11Bootstrap bootstrap) { ImmutableSet.Builder<Metadata<Extension>> extensionsBuilder = ImmutableSet.builder(); extensionsBuilder.addAll(bootstrap.loadExtensions(WeldResourceLoader.getClassLoader())); if (isDevModeEnabled) { extensionsBuilder.add(new MetadataImpl<Extension>(DevelopmentMode.getProbeExtension(resourceLoader), "N/A")); } final Iterable<Metadata<Extension>> extensions = extensionsBuilder.build(); final TypeDiscoveryConfiguration typeDiscoveryConfiguration = bootstrap.startExtensions(extensions); final EEModuleDescriptor eeModule = new EEModuleDescriptorImpl(context.getContextPath(), ModuleType.WEB); final DiscoveryStrategy strategy = DiscoveryStrategyFactory.create(resourceLoader, bootstrap, typeDiscoveryConfiguration.getKnownBeanDefiningAnnotations(), Boolean.parseBoolean(context.getInitParameter(Jandex.DISABLE_JANDEX_DISCOVERY_STRATEGY))); if (Jandex.isJandexAvailable(resourceLoader)) { try { Class<? extends BeanArchiveHandler> handlerClass = Reflections.loadClass(resourceLoader, JANDEX_SERVLET_CONTEXT_BEAN_ARCHIVE_HANDLER); strategy.registerHandler((SecurityActions.newConstructorInstance(handlerClass, new Class<?>[] { ServletContext.class }, context))); } catch (Exception e) { throw CommonLogger.LOG.unableToInstantiate(JANDEX_SERVLET_CONTEXT_BEAN_ARCHIVE_HANDLER, Arrays.toString(new Object[] { context }), e); } } else { strategy.registerHandler(new ServletContextBeanArchiveHandler(context)); } strategy.setScanner(new WebAppBeanArchiveScanner(resourceLoader, bootstrap, context)); Set<WeldBeanDeploymentArchive> beanDeploymentArchives = strategy.performDiscovery(); String isolation = context.getInitParameter(CONTEXT_PARAM_ARCHIVE_ISOLATION); if (isolation == null || Boolean.valueOf(isolation)) { CommonLogger.LOG.archiveIsolationEnabled(); } else { CommonLogger.LOG.archiveIsolationDisabled(); Set<WeldBeanDeploymentArchive> flatDeployment = new HashSet<WeldBeanDeploymentArchive>(); flatDeployment.add(WeldBeanDeploymentArchive.merge(bootstrap, beanDeploymentArchives)); beanDeploymentArchives = flatDeployment; } for (BeanDeploymentArchive archive : beanDeploymentArchives) { archive.getServices().add(EEModuleDescriptor.class, eeModule); } CDI11Deployment deployment = new WeldDeployment(resourceLoader, bootstrap, beanDeploymentArchives, extensions) { @Override protected WeldBeanDeploymentArchive createAdditionalBeanDeploymentArchive() { WeldBeanDeploymentArchive archive = super.createAdditionalBeanDeploymentArchive(); archive.getServices().add(EEModuleDescriptor.class, eeModule); return archive; } }; if (strategy.getClassFileServices() != null) { deployment.getServices().add(ClassFileServices.class, strategy.getClassFileServices()); } return deployment; }
java
{ "resource": "" }
q6773
WeldServletLifecycle.findContainer
train
protected Container findContainer(ContainerContext ctx, StringBuilder dump) { Container container = null; // 1. Custom container class String containerClassName = ctx.getServletContext().getInitParameter(Container.CONTEXT_PARAM_CONTAINER_CLASS); if (containerClassName != null) { try { Class<Container> containerClass = Reflections.classForName(resourceLoader, containerClassName); container = SecurityActions.newInstance(containerClass); WeldServletLogger.LOG.containerDetectionSkipped(containerClassName); } catch (Exception e) { WeldServletLogger.LOG.unableToInstantiateCustomContainerClass(containerClassName); WeldServletLogger.LOG.catchingDebug(e); } } if (container == null) { // 2. Service providers Iterable<Container> extContainers = ServiceLoader.load(Container.class, getClass().getClassLoader()); container = checkContainers(ctx, dump, extContainers); if (container == null) { // 3. Built-in containers in predefined order container = checkContainers(ctx, dump, Arrays.asList(TomcatContainer.INSTANCE, JettyContainer.INSTANCE, UndertowContainer.INSTANCE, GwtDevHostedModeContainer.INSTANCE)); } } return container; }
java
{ "resource": "" }
q6774
ResolvableBuilder.createMetadataProvider
train
private Resolvable createMetadataProvider(Class<?> rawType) { Set<Type> types = Collections.<Type>singleton(rawType); return new ResolvableImpl(rawType, types, declaringBean, qualifierInstances, delegate); }
java
{ "resource": "" }
q6775
InterceptedSubclassFactory.hasAbstractPackagePrivateSuperClassWithImplementation
train
private boolean hasAbstractPackagePrivateSuperClassWithImplementation(Class<?> clazz, BridgeMethod bridgeMethod) { Class<?> superClass = clazz.getSuperclass(); while (superClass != null) { if (Modifier.isAbstract(superClass.getModifiers()) && Reflections.isPackagePrivate(superClass.getModifiers())) { // if superclass is abstract, we need to dig deeper for (Method method : superClass.getDeclaredMethods()) { if (bridgeMethod.signature.matches(method) && method.getGenericReturnType().equals(bridgeMethod.returnType) && !Reflections.isAbstract(method)) { // this is the case we are after -> methods have same signature and the one in super class has actual implementation return true; } } } superClass = superClass.getSuperclass(); } return false; }
java
{ "resource": "" }
q6776
InterceptedSubclassFactory.addSpecialMethods
train
protected void addSpecialMethods(ClassFile proxyClassType, ClassMethod staticConstructor) { try { // Add special methods for interceptors for (Method method : LifecycleMixin.class.getMethods()) { BeanLogger.LOG.addingMethodToProxy(method); MethodInformation methodInfo = new RuntimeMethodInformation(method); createInterceptorBody(proxyClassType.addMethod(method), methodInfo, false, staticConstructor); } Method getInstanceMethod = TargetInstanceProxy.class.getMethod("weld_getTargetInstance"); Method getInstanceClassMethod = TargetInstanceProxy.class.getMethod("weld_getTargetClass"); generateGetTargetInstanceBody(proxyClassType.addMethod(getInstanceMethod)); generateGetTargetClassBody(proxyClassType.addMethod(getInstanceClassMethod)); Method setMethodHandlerMethod = ProxyObject.class.getMethod("weld_setHandler", MethodHandler.class); generateSetMethodHandlerBody(proxyClassType.addMethod(setMethodHandlerMethod)); Method getMethodHandlerMethod = ProxyObject.class.getMethod("weld_getHandler"); generateGetMethodHandlerBody(proxyClassType.addMethod(getMethodHandlerMethod)); } catch (Exception e) { throw new WeldException(e); } }
java
{ "resource": "" }
q6777
Decorators.checkDelegateType
train
public static void checkDelegateType(Decorator<?> decorator) { Set<Type> types = new HierarchyDiscovery(decorator.getDelegateType()).getTypeClosure(); for (Type decoratedType : decorator.getDecoratedTypes()) { if(!types.contains(decoratedType)) { throw BeanLogger.LOG.delegateMustSupportEveryDecoratedType(decoratedType, decorator); } } }
java
{ "resource": "" }
q6778
Decorators.checkAbstractMethods
train
public static <T> void checkAbstractMethods(Set<Type> decoratedTypes, EnhancedAnnotatedType<T> type, BeanManagerImpl beanManager) { if (decoratedTypes == null) { decoratedTypes = new HashSet<Type>(type.getInterfaceClosure()); decoratedTypes.remove(Serializable.class); } Set<MethodSignature> signatures = new HashSet<MethodSignature>(); for (Type decoratedType : decoratedTypes) { for (EnhancedAnnotatedMethod<?, ?> method : ClassTransformer.instance(beanManager) .getEnhancedAnnotatedType(Reflections.getRawType(decoratedType), beanManager.getId()).getEnhancedMethods()) { signatures.add(method.getSignature()); } } for (EnhancedAnnotatedMethod<?, ?> method : type.getEnhancedMethods()) { if (Reflections.isAbstract(((AnnotatedMethod<?>) method).getJavaMember())) { MethodSignature methodSignature = method.getSignature(); if (!signatures.contains(methodSignature)) { throw BeanLogger.LOG.abstractMethodMustMatchDecoratedType(method, Formats.formatAsStackTraceElement(method.getJavaMember())); } } } }
java
{ "resource": "" }
q6779
AbstractBean.checkSpecialization
train
public void checkSpecialization() { if (isSpecializing()) { boolean isNameDefined = getAnnotated().isAnnotationPresent(Named.class); String previousSpecializedBeanName = null; for (AbstractBean<?, ?> specializedBean : getSpecializedBeans()) { String name = specializedBean.getName(); if (previousSpecializedBeanName != null && name != null && !previousSpecializedBeanName.equals(specializedBean.getName())) { // there may be multiple beans specialized by this bean - make sure they all share the same name throw BeanLogger.LOG.beansWithDifferentBeanNamesCannotBeSpecialized(previousSpecializedBeanName, specializedBean.getName(), this); } previousSpecializedBeanName = name; if (isNameDefined && name != null) { throw BeanLogger.LOG.nameNotAllowedOnSpecialization(getAnnotated(), specializedBean.getAnnotated()); } // When a specializing bean extends the raw type of a generic superclass, types of the generic superclass are // added into types of the specializing bean because of assignability rules. However, ParameterizedTypes among // these types are NOT types of the specializing bean (that's the way java works) boolean rawInsteadOfGeneric = (this instanceof AbstractClassBean<?> && specializedBean.getBeanClass().getTypeParameters().length > 0 && !(((AbstractClassBean<?>) this).getBeanClass().getGenericSuperclass() instanceof ParameterizedType)); for (Type specializedType : specializedBean.getTypes()) { if (rawInsteadOfGeneric && specializedType instanceof ParameterizedType) { throw BeanLogger.LOG.specializingBeanMissingSpecializedType(this, specializedType, specializedBean); } boolean contains = getTypes().contains(specializedType); if (!contains) { for (Type specializingType : getTypes()) { // In case 'type' is a ParameterizedType, two bean types equivalent in the CDI sense may not be // equal in the java sense. Therefore we have to use our own equality util. if (TypeEqualitySpecializationUtils.areTheSame(specializingType, specializedType)) { contains = true; break; } } } if (!contains) { throw BeanLogger.LOG.specializingBeanMissingSpecializedType(this, specializedType, specializedBean); } } } } }
java
{ "resource": "" }
q6780
BeanDeploymentModule.fireEvent
train
public void fireEvent(Type eventType, Object event, Annotation... qualifiers) { final EventMetadata metadata = new EventMetadataImpl(eventType, null, qualifiers); notifier.fireEvent(eventType, event, metadata, qualifiers); }
java
{ "resource": "" }
q6781
Defaults.getJlsDefaultValue
train
@SuppressWarnings("unchecked") public static <T> T getJlsDefaultValue(Class<T> type) { if(!type.isPrimitive()) { return null; } return (T) JLS_PRIMITIVE_DEFAULT_VALUES.get(type); }
java
{ "resource": "" }
q6782
ProbeExtension.afterDeploymentValidation
train
public void afterDeploymentValidation(@Observes @Priority(1) AfterDeploymentValidation event, BeanManager beanManager) { BeanManagerImpl manager = BeanManagerProxy.unwrap(beanManager); probe.init(manager); if (isJMXSupportEnabled(manager)) { try { MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); mbs.registerMBean(new ProbeDynamicMBean(jsonDataProvider, JsonDataProvider.class), constructProbeJsonDataMBeanName(manager, probe)); } catch (MalformedObjectNameException | InstanceAlreadyExistsException | MBeanRegistrationException | NotCompliantMBeanException e) { event.addDeploymentProblem(ProbeLogger.LOG.unableToRegisterMBean(JsonDataProvider.class, manager.getContextId(), e)); } } addContainerLifecycleEvent(event, null, beanManager); exportDataIfNeeded(manager); }
java
{ "resource": "" }
q6783
Selectors.matchPath
train
static boolean matchPath(String[] tokenizedPattern, String[] strDirs, boolean isCaseSensitive) { int patIdxStart = 0; int patIdxEnd = tokenizedPattern.length - 1; int strIdxStart = 0; int strIdxEnd = strDirs.length - 1; // up to first '**' while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) { String patDir = tokenizedPattern[patIdxStart]; if (patDir.equals(DEEP_TREE_MATCH)) { break; } if (!match(patDir, strDirs[strIdxStart], isCaseSensitive)) { return false; } patIdxStart++; strIdxStart++; } if (strIdxStart > strIdxEnd) { // String is exhausted for (int i = patIdxStart; i <= patIdxEnd; i++) { if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) { return false; } } return true; } else { if (patIdxStart > patIdxEnd) { // String not exhausted, but pattern is. Failure. return false; } } // up to last '**' while (patIdxStart <= patIdxEnd && strIdxStart <= strIdxEnd) { String patDir = tokenizedPattern[patIdxEnd]; if (patDir.equals(DEEP_TREE_MATCH)) { break; } if (!match(patDir, strDirs[strIdxEnd], isCaseSensitive)) { return false; } patIdxEnd--; strIdxEnd--; } if (strIdxStart > strIdxEnd) { // String is exhausted for (int i = patIdxStart; i <= patIdxEnd; i++) { if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) { return false; } } return true; } while (patIdxStart != patIdxEnd && strIdxStart <= strIdxEnd) { int patIdxTmp = -1; for (int i = patIdxStart + 1; i <= patIdxEnd; i++) { if (tokenizedPattern[i].equals(DEEP_TREE_MATCH)) { patIdxTmp = i; break; } } if (patIdxTmp == patIdxStart + 1) { // '**/**' situation, so skip one patIdxStart++; continue; } // Find the pattern between padIdxStart & padIdxTmp in str between // strIdxStart & strIdxEnd int patLength = (patIdxTmp - patIdxStart - 1); int strLength = (strIdxEnd - strIdxStart + 1); int foundIdx = -1; strLoop: for (int i = 0; i <= strLength - patLength; i++) { for (int j = 0; j < patLength; j++) { String subPat = tokenizedPattern[patIdxStart + j + 1]; String subStr = strDirs[strIdxStart + i + j]; if (!match(subPat, subStr, isCaseSensitive)) { continue strLoop; } } foundIdx = strIdxStart + i; break; } if (foundIdx == -1) { return false; } patIdxStart = patIdxTmp; strIdxStart = foundIdx + patLength; } for (int i = patIdxStart; i <= patIdxEnd; i++) { if (!tokenizedPattern[i].equals(DEEP_TREE_MATCH)) { return false; } } return true; }
java
{ "resource": "" }
q6784
Selectors.tokenize
train
static String[] tokenize(String str) { char sep = '.'; int start = 0; int len = str.length(); int count = 0; for (int pos = 0; pos < len; pos++) { if (str.charAt(pos) == sep) { if (pos != start) { count++; } start = pos + 1; } } if (len != start) { count++; } String[] l = new String[count]; count = 0; start = 0; for (int pos = 0; pos < len; pos++) { if (str.charAt(pos) == sep) { if (pos != start) { String tok = str.substring(start, pos); l[count++] = tok; } start = pos + 1; } } if (len != start) { String tok = str.substring(start); l[count/* ++ */] = tok; } return l; }
java
{ "resource": "" }
q6785
RunWithinInterceptionDecorationContextGenerator.endIfStarted
train
void endIfStarted(CodeAttribute b, ClassMethod method) { b.aload(getLocalVariableIndex(0)); b.dup(); final BranchEnd ifnotnull = b.ifnull(); b.checkcast(Stack.class); b.invokevirtual(Stack.class.getName(), END_INTERCEPTOR_CONTEXT_METHOD_NAME, EMPTY_PARENTHESES + VOID_CLASS_DESCRIPTOR); BranchEnd ifnull = b.gotoInstruction(); b.branchEnd(ifnotnull); b.pop(); // remove null Stack b.branchEnd(ifnull); }
java
{ "resource": "" }
q6786
AbstractContext.get
train
@Override @SuppressFBWarnings(value = "UL_UNRELEASED_LOCK", justification = "False positive from FindBugs") public <T> T get(Contextual<T> contextual, CreationalContext<T> creationalContext) { if (!isActive()) { throw new ContextNotActiveException(); } checkContextInitialized(); final BeanStore beanStore = getBeanStore(); if (beanStore == null) { return null; } if (contextual == null) { throw ContextLogger.LOG.contextualIsNull(); } BeanIdentifier id = getId(contextual); ContextualInstance<T> beanInstance = beanStore.get(id); if (beanInstance != null) { return beanInstance.getInstance(); } else if (creationalContext != null) { LockedBean lock = null; try { if (multithreaded) { lock = beanStore.lock(id); beanInstance = beanStore.get(id); if (beanInstance != null) { return beanInstance.getInstance(); } } T instance = contextual.create(creationalContext); if (instance != null) { beanInstance = new SerializableContextualInstanceImpl<Contextual<T>, T>(contextual, instance, creationalContext, serviceRegistry.get(ContextualStore.class)); beanStore.put(id, beanInstance); } return instance; } finally { if (lock != null) { lock.unlock(); } } } else { return null; } }
java
{ "resource": "" }
q6787
AbstractContext.destroy
train
protected void destroy() { ContextLogger.LOG.contextCleared(this); final BeanStore beanStore = getBeanStore(); if (beanStore == null) { throw ContextLogger.LOG.noBeanStoreAvailable(this); } for (BeanIdentifier id : beanStore) { destroyContextualInstance(beanStore.get(id)); } beanStore.clear(); }
java
{ "resource": "" }
q6788
Iterables.addAll
train
public static <T> boolean addAll(Collection<T> target, Iterable<? extends T> iterable) { if (iterable instanceof Collection) { return target.addAll((Collection<? extends T>) iterable); } return Iterators.addAll(target, iterable.iterator()); }
java
{ "resource": "" }
q6789
FieldProducerFactory.createProducer
train
@Override public <T> Producer<T> createProducer(final Bean<X> declaringBean, final Bean<T> bean, DisposalMethod<X, T> disposalMethod) { EnhancedAnnotatedField<T, X> enhancedField = getManager().getServices().get(MemberTransformer.class).loadEnhancedMember(field, getManager().getId()); return new ProducerFieldProducer<X, T>(enhancedField, disposalMethod) { @Override public AnnotatedField<X> getAnnotated() { return field; } @Override public BeanManagerImpl getBeanManager() { return getManager(); } @Override public Bean<X> getDeclaringBean() { return declaringBean; } @Override public Bean<T> getBean() { return bean; } }; }
java
{ "resource": "" }
q6790
WeldDeployment.createAdditionalBeanDeploymentArchive
train
protected WeldBeanDeploymentArchive createAdditionalBeanDeploymentArchive() { WeldBeanDeploymentArchive additionalBda = new WeldBeanDeploymentArchive(ADDITIONAL_BDA_ID, Collections.synchronizedSet(new HashSet<String>()), null); additionalBda.getServices().addAll(getServices().entrySet()); beanDeploymentArchives.add(additionalBda); setBeanDeploymentArchivesAccessibility(); return additionalBda; }
java
{ "resource": "" }
q6791
WeldDeployment.setBeanDeploymentArchivesAccessibility
train
protected void setBeanDeploymentArchivesAccessibility() { for (WeldBeanDeploymentArchive beanDeploymentArchive : beanDeploymentArchives) { Set<WeldBeanDeploymentArchive> accessibleArchives = new HashSet<>(); for (WeldBeanDeploymentArchive candidate : beanDeploymentArchives) { if (candidate.equals(beanDeploymentArchive)) { continue; } accessibleArchives.add(candidate); } beanDeploymentArchive.setAccessibleBeanDeploymentArchives(accessibleArchives); } }
java
{ "resource": "" }
q6792
Parsers.parseType
train
static Type parseType(String value, ResourceLoader resourceLoader) { value = value.trim(); // Wildcards if (value.equals(WILDCARD)) { return WildcardTypeImpl.defaultInstance(); } if (value.startsWith(WILDCARD_EXTENDS)) { Type upperBound = parseType(value.substring(WILDCARD_EXTENDS.length(), value.length()), resourceLoader); if (upperBound == null) { return null; } return WildcardTypeImpl.withUpperBound(upperBound); } if (value.startsWith(WILDCARD_SUPER)) { Type lowerBound = parseType(value.substring(WILDCARD_SUPER.length(), value.length()), resourceLoader); if (lowerBound == null) { return null; } return WildcardTypeImpl.withLowerBound(lowerBound); } // Array if (value.contains(ARRAY)) { Type componentType = parseType(value.substring(0, value.indexOf(ARRAY)), resourceLoader); if (componentType == null) { return null; } return new GenericArrayTypeImpl(componentType); } int chevLeft = value.indexOf(CHEVRONS_LEFT); String rawValue = chevLeft < 0 ? value : value.substring(0, chevLeft); Class<?> rawRequiredType = tryLoadClass(rawValue, resourceLoader); if (rawRequiredType == null) { return null; } if (rawRequiredType.getTypeParameters().length == 0) { return rawRequiredType; } // Parameterized type int chevRight = value.lastIndexOf(CHEVRONS_RIGHT); if (chevRight < 0) { return null; } List<String> parts = split(value.substring(chevLeft + 1, chevRight), ',', CHEVRONS_LEFT.charAt(0), CHEVRONS_RIGHT.charAt(0)); Type[] typeParameters = new Type[parts.size()]; for (int i = 0; i < typeParameters.length; i++) { Type typeParam = parseType(parts.get(i), resourceLoader); if (typeParam == null) { return null; } typeParameters[i] = typeParam; } return new ParameterizedTypeImpl(rawRequiredType, typeParameters); }
java
{ "resource": "" }
q6793
PortletSupport.isPortletEnvSupported
train
public static boolean isPortletEnvSupported() { if (enabled == null) { synchronized (PortletSupport.class) { if (enabled == null) { try { PortletSupport.class.getClassLoader().loadClass("javax.portlet.PortletContext"); enabled = true; } catch (Throwable ignored) { enabled = false; } } } } return enabled; }
java
{ "resource": "" }
q6794
PortletSupport.getBeanManager
train
public static BeanManager getBeanManager(Object ctx) { return (BeanManager) javax.portlet.PortletContext.class.cast(ctx).getAttribute(WeldServletLifecycle.BEAN_MANAGER_ATTRIBUTE_NAME); }
java
{ "resource": "" }
q6795
GlobalEnablementBuilder.filter
train
private <T> List<Class<?>> filter(List<Class<?>> enabledClasses, List<Class<?>> globallyEnabledClasses, LogMessageCallback logMessageCallback, BeanDeployment deployment) { for (Iterator<Class<?>> iterator = enabledClasses.iterator(); iterator.hasNext(); ) { Class<?> enabledClass = iterator.next(); if (globallyEnabledClasses.contains(enabledClass)) { logMessageCallback.log(enabledClass, deployment.getBeanDeploymentArchive().getId()); iterator.remove(); } } return enabledClasses; }
java
{ "resource": "" }
q6796
TypeSafeResolver.resolve
train
public F resolve(R resolvable, boolean cache) { R wrappedResolvable = wrap(resolvable); if (cache) { return resolved.getValue(wrappedResolvable); } else { return resolverFunction.apply(wrappedResolvable); } }
java
{ "resource": "" }
q6797
TypeSafeResolver.findMatching
train
private Set<T> findMatching(R resolvable) { Set<T> result = new HashSet<T>(); for (T bean : getAllBeans(resolvable)) { if (matches(resolvable, bean)) { result.add(bean); } } return result; }
java
{ "resource": "" }
q6798
BeanDeployerEnvironment.resolveDisposalBeans
train
public <X> Set<DisposalMethod<X, ?>> resolveDisposalBeans(Set<Type> types, Set<Annotation> qualifiers, AbstractClassBean<X> declaringBean) { // We can always cache as this is only ever called by Weld where we avoid non-static inner classes for annotation literals Set<DisposalMethod<X, ?>> beans = cast(disposalMethodResolver.resolve(new ResolvableBuilder(manager).addTypes(types).addQualifiers(qualifiers).setDeclaringBean(declaringBean).create(), true)); resolvedDisposalBeans.addAll(beans); return Collections.unmodifiableSet(beans); }
java
{ "resource": "" }
q6799
SessionBeans.getSessionBeanTypes
train
private static <T> Set<Type> getSessionBeanTypes(EnhancedAnnotated<T, ?> annotated, EjbDescriptor<T> ejbDescriptor) { ImmutableSet.Builder<Type> types = ImmutableSet.builder(); // session beans Map<Class<?>, Type> typeMap = new LinkedHashMap<Class<?>, Type>(); HierarchyDiscovery beanClassDiscovery = HierarchyDiscovery.forNormalizedType(ejbDescriptor.getBeanClass()); for (BusinessInterfaceDescriptor<?> businessInterfaceDescriptor : ejbDescriptor.getLocalBusinessInterfaces()) { // first we need to resolve the local interface Type resolvedLocalInterface = beanClassDiscovery.resolveType(Types.getCanonicalType(businessInterfaceDescriptor.getInterface())); SessionBeanHierarchyDiscovery interfaceDiscovery = new SessionBeanHierarchyDiscovery(resolvedLocalInterface); if (beanClassDiscovery.getTypeMap().containsKey(businessInterfaceDescriptor.getInterface())) { // WELD-1675 Only add types also included in Annotated.getTypeClosure() for (Entry<Class<?>, Type> entry : interfaceDiscovery.getTypeMap().entrySet()) { if (annotated.getTypeClosure().contains(entry.getValue())) { typeMap.put(entry.getKey(), entry.getValue()); } } } else { // Session bean class does not implement the business interface and @javax.ejb.Local applied to the session bean class typeMap.putAll(interfaceDiscovery.getTypeMap()); } } if (annotated.isAnnotationPresent(Typed.class)) { types.addAll(Beans.getTypedTypes(typeMap, annotated.getJavaClass(), annotated.getAnnotation(Typed.class))); } else { typeMap.put(Object.class, Object.class); types.addAll(typeMap.values()); } return Beans.getLegalBeanTypes(types.build(), annotated); }
java
{ "resource": "" }