_id stringlengths 2 7 | title stringlengths 3 140 | partition stringclasses 3
values | text stringlengths 73 34.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q14100 | ManagedBufferPool.acquire | train | @SuppressWarnings("PMD.GuardLogStatement")
public W acquire() throws InterruptedException {
// Stop draining, because we obviously need this kind of buffers
Optional.ofNullable(idleTimer.getAndSet(null)).ifPresent(
timer -> timer.cancel());
if (createdBufs.get() < maximumBufs) {
// Haven't reached maximum, so if no buffer is queued, create one.
W buffer = queue.poll();
if (buffer != null) {
buffer.lockBuffer();
return buffer;
}
return createBuffer();
}
// Wait for buffer to become available.
if (logger.isLoggable(Level.FINE)) {
// If configured, log message after waiting some time.
W buffer = queue.poll(acquireWarningLimit, TimeUnit.MILLISECONDS);
if (buffer != null) {
buffer.lockBuffer();
return buffer;
}
logger.log(Level.FINE, new Throwable(),
() -> Thread.currentThread().getName() + " waiting > "
+ acquireWarningLimit + "ms for buffer, while executing:");
}
W buffer = queue.take();
buffer.lockBuffer();
return buffer;
} | java | {
"resource": ""
} |
q14101 | ManagedBufferPool.recollect | train | @Override
public void recollect(W buffer) {
if (queue.size() < preservedBufs) {
long effectiveDrainDelay
= drainDelay > 0 ? drainDelay : defaultDrainDelay;
if (effectiveDrainDelay > 0) {
// Enqueue
buffer.clear();
queue.add(buffer);
Timer old = idleTimer.getAndSet(Components.schedule(this::drain,
Duration.ofMillis(effectiveDrainDelay)));
if (old != null) {
old.cancel();
}
return;
}
}
// Discard
removeBuffer(buffer);
} | java | {
"resource": ""
} |
q14102 | IncludeValue.getIncludedValue | train | public Value getIncludedValue(Environment in){
return ConfigurationManager.INSTANCE.getConfiguration(configurationName, in).getAttribute(attributeName);
} | java | {
"resource": ""
} |
q14103 | IncludeValue.getConfigName | train | public ConfigurationSourceKey getConfigName() {
return new ConfigurationSourceKey(ConfigurationSourceKey.Type.FILE, ConfigurationSourceKey.Format.JSON, configurationName);
} | java | {
"resource": ""
} |
q14104 | Configuration.copyWithIdentifier | train | Configuration copyWithIdentifier(String identifier) {
return new Configuration(details.builder().identifier(identifier).build(), new HashMap<>(config));
} | java | {
"resource": ""
} |
q14105 | Configuration.write | train | void write(File f) throws FileNotFoundException, IOException {
try (ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(f))) {
os.writeObject(this);
}
} | java | {
"resource": ""
} |
q14106 | ConfigurationSource.fireUpdateEvent | train | public void fireUpdateEvent(final long timestamp){
synchronized(listeners){
for (final ConfigurationSourceListener listener : listeners){
try{
log.debug("Calling configurationSourceUpdated on "+listener);
listener.configurationSourceUpdated(this);
}catch(final Exception e){
log.error("Error in notifying configuration source listener:"+listener, e);
}
}
}
lastChangeTimestamp = timestamp;
} | java | {
"resource": ""
} |
q14107 | Inventory.remove | train | InventoryEntry remove(String key) {
InventoryEntry ret = configs.remove(key);
if (ret!=null) {
ret.getPath().delete();
}
return ret;
} | java | {
"resource": ""
} |
q14108 | Inventory.removeMismatching | train | List<Configuration> removeMismatching() {
// List mismatching
List<InventoryEntry> mismatching = configs.values().stream()
.filter(v->
(v.getConfiguration().isPresent()
&& !v.getIdentifier().equals(v.getConfiguration().get().getDetails().getKey()))
).collect(Collectors.toList());
// Remove from inventory
mismatching.forEach(v->configs.remove(v.getIdentifier()));
// Return the list of removed configurations
return mismatching.stream()
.map(v->v.getConfiguration().get())
.collect(Collectors.toList());
} | java | {
"resource": ""
} |
q14109 | Inventory.removeUnreadable | train | List<File> removeUnreadable() {
// List unreadable
List<InventoryEntry> unreadable = configs.values()
.stream()
.filter(v->!v.getConfiguration().isPresent())
.collect(Collectors.toList());
// Remove from inventory
unreadable.forEach(v->configs.remove(v.getIdentifier()));
// Return the list of removed files
return unreadable.stream()
.map(v->v.getPath())
.collect(Collectors.toList());
} | java | {
"resource": ""
} |
q14110 | FormProcessor.onGet | train | @RequestHandler(patterns = "/form,/form/**")
public void onGet(Request.In.Get event, IOSubchannel channel)
throws ParseException {
ResponseCreationSupport.sendStaticContent(event, channel,
path -> FormProcessor.class.getResource(
ResourcePattern.removeSegments(path, 1)),
null);
} | java | {
"resource": ""
} |
q14111 | FormProcessor.onPost | train | @RequestHandler(patterns = "/form,/form/**")
public void onPost(Request.In.Post event, IOSubchannel channel) {
FormContext ctx = channel
.associated(this, FormContext::new);
ctx.request = event.httpRequest();
ctx.session = event.associated(Session.class).get();
event.setResult(true);
event.stop();
} | java | {
"resource": ""
} |
q14112 | FormProcessor.onInput | train | @Handler
public void onInput(Input<ByteBuffer> event, IOSubchannel channel)
throws InterruptedException, UnsupportedEncodingException {
Optional<FormContext> ctx = channel.associated(this, FormContext.class);
if (!ctx.isPresent()) {
return;
}
ctx.get().fieldDecoder.addData(event.data());
if (!event.isEndOfRecord()) {
return;
}
long invocations = (Long) ctx.get().session.computeIfAbsent(
"invocations", key -> {
return 0L;
});
ctx.get().session.put("invocations", invocations + 1);
HttpResponse response = ctx.get().request.response().get();
response.setStatus(HttpStatus.OK);
response.setHasPayload(true);
response.setField(HttpField.CONTENT_TYPE,
MediaType.builder().setType("text", "plain")
.setParameter("charset", "utf-8").build());
String data = "First name: "
+ ctx.get().fieldDecoder.fields().get("firstname")
+ "\r\n" + "Last name: "
+ ctx.get().fieldDecoder.fields().get("lastname")
+ "\r\n" + "Previous invocations: " + invocations;
channel.respond(new Response(response));
ManagedBuffer<ByteBuffer> out = channel.byteBufferPool().acquire();
out.backingBuffer().put(data.getBytes("utf-8"));
channel.respond(Output.fromSink(out, true));
} | java | {
"resource": ""
} |
q14113 | HttpConnector.onConnected | train | @Handler(channels = NetworkChannel.class)
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
public void onConnected(Connected event, TcpChannel netConnChannel)
throws InterruptedException, IOException {
// Check if an app channel has been waiting for such a connection
WebAppMsgChannel[] appChannel = { null };
synchronized (connecting) {
connecting.computeIfPresent(event.remoteAddress(), (key, set) -> {
Iterator<WebAppMsgChannel> iter = set.iterator();
appChannel[0] = iter.next();
iter.remove();
return set.isEmpty() ? null : set;
});
}
if (appChannel[0] != null) {
appChannel[0].connected(netConnChannel);
}
} | java | {
"resource": ""
} |
q14114 | HttpConnector.onInput | train | @Handler(channels = NetworkChannel.class)
public void onInput(Input<ByteBuffer> event, TcpChannel netConnChannel)
throws InterruptedException, ProtocolException {
Optional<WebAppMsgChannel> appChannel
= netConnChannel.associated(WebAppMsgChannel.class);
if (appChannel.isPresent()) {
appChannel.get().handleNetInput(event, netConnChannel);
}
} | java | {
"resource": ""
} |
q14115 | HttpConnector.onClosed | train | @Handler(channels = NetworkChannel.class)
public void onClosed(Closed event, TcpChannel netConnChannel) {
netConnChannel.associated(WebAppMsgChannel.class).ifPresent(
appChannel -> appChannel.handleClosed(event));
pooled.remove(netConnChannel.remoteAddress(), netConnChannel);
} | java | {
"resource": ""
} |
q14116 | ThymeleafSpringResult.bindStrutsContext | train | Map<String, Object> bindStrutsContext(Object action) {
Map<String, Object> variables = new HashMap<String, Object>();
variables.put(ACTION_VARIABLE_NAME, action);
if ( action instanceof ActionSupport) {
ActionSupport actSupport = (ActionSupport)action;
// Struts2 field errors.( Map<fieldname , fielderrors>)
Map<String, List<String>> fieldErrors = actSupport.getFieldErrors();
variables.put(FIELD_ERRORS_NAME, fieldErrors);
}
return variables;
} | java | {
"resource": ""
} |
q14117 | Settings.sdkInitialize | train | public static synchronized void sdkInitialize(Context context) {
if (sdkInitialized == true) {
return;
}
BoltsMeasurementEventListener.getInstance(context.getApplicationContext());
sdkInitialized = true;
} | java | {
"resource": ""
} |
q14118 | Settings.getExecutor | train | public static Executor getExecutor() {
synchronized (LOCK) {
if (Settings.executor == null) {
Executor executor = getAsyncTaskExecutor();
if (executor == null) {
executor = new ThreadPoolExecutor(DEFAULT_CORE_POOL_SIZE, DEFAULT_MAXIMUM_POOL_SIZE,
DEFAULT_KEEP_ALIVE, TimeUnit.SECONDS, DEFAULT_WORK_QUEUE, DEFAULT_THREAD_FACTORY);
}
Settings.executor = executor;
}
}
return Settings.executor;
} | java | {
"resource": ""
} |
q14119 | Settings.setExecutor | train | public static void setExecutor(Executor executor) {
Validate.notNull(executor, "executor");
synchronized (LOCK) {
Settings.executor = executor;
}
} | java | {
"resource": ""
} |
q14120 | Settings.getAttributionId | train | public static String getAttributionId(ContentResolver contentResolver) {
try {
String [] projection = {ATTRIBUTION_ID_COLUMN_NAME};
Cursor c = contentResolver.query(ATTRIBUTION_ID_CONTENT_URI, projection, null, null, null);
if (c == null || !c.moveToFirst()) {
return null;
}
String attributionId = c.getString(c.getColumnIndex(ATTRIBUTION_ID_COLUMN_NAME));
c.close();
return attributionId;
} catch (Exception e) {
Log.d(TAG, "Caught unexpected exception in getAttributionId(): " + e.toString());
return null;
}
} | java | {
"resource": ""
} |
q14121 | Settings.getLimitEventAndDataUsage | train | public static boolean getLimitEventAndDataUsage(Context context) {
SharedPreferences preferences = context.getSharedPreferences(APP_EVENT_PREFERENCES, Context.MODE_PRIVATE);
return preferences.getBoolean("limitEventUsage", false);
} | java | {
"resource": ""
} |
q14122 | Settings.setLimitEventAndDataUsage | train | public static void setLimitEventAndDataUsage(Context context, boolean limitEventUsage) {
SharedPreferences preferences = context.getSharedPreferences(APP_EVENT_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("limitEventUsage", limitEventUsage);
editor.commit();
} | java | {
"resource": ""
} |
q14123 | ToolTipPopup.show | train | public void show() {
if (mAnchorViewRef.get() != null) {
mPopupContent = new PopupContentView(mContext);
TextView body = (TextView) mPopupContent.findViewById(
R.id.com_facebook_tooltip_bubble_view_text_body);
body.setText(mText);
if (mStyle == Style.BLUE) {
mPopupContent.bodyFrame.setBackgroundResource(
R.drawable.com_facebook_tooltip_blue_background);
mPopupContent.bottomArrow.setImageResource(
R.drawable.com_facebook_tooltip_blue_bottomnub);
mPopupContent.topArrow.setImageResource(
R.drawable.com_facebook_tooltip_blue_topnub);
mPopupContent.xOut.setImageResource(R.drawable.com_facebook_tooltip_blue_xout);
} else {
mPopupContent.bodyFrame.setBackgroundResource(
R.drawable.com_facebook_tooltip_black_background);
mPopupContent.bottomArrow.setImageResource(
R.drawable.com_facebook_tooltip_black_bottomnub);
mPopupContent.topArrow.setImageResource(
R.drawable.com_facebook_tooltip_black_topnub);
mPopupContent.xOut.setImageResource(R.drawable.com_facebook_tooltip_black_xout);
}
final Window window = ((Activity) mContext).getWindow();
final View decorView = window.getDecorView();
final int decorWidth = decorView.getWidth();
final int decorHeight = decorView.getHeight();
registerObserver();
mPopupContent.onMeasure(
View.MeasureSpec.makeMeasureSpec(decorWidth, View.MeasureSpec.AT_MOST),
View.MeasureSpec.makeMeasureSpec(decorHeight, View.MeasureSpec.AT_MOST));
mPopupWindow = new PopupWindow(
mPopupContent,
mPopupContent.getMeasuredWidth(),
mPopupContent.getMeasuredHeight());
mPopupWindow.showAsDropDown(mAnchorViewRef.get());
updateArrows();
if (mNuxDisplayTime > 0) {
mPopupContent.postDelayed(new Runnable() {
@Override
public void run() {
dismiss();
}
}, mNuxDisplayTime);
}
mPopupWindow.setTouchable(true);
mPopupContent.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dismiss();
}
});
}
} | java | {
"resource": ""
} |
q14124 | UiLifecycleHelper.onCreate | train | public void onCreate(Bundle savedInstanceState) {
Session session = Session.getActiveSession();
if (session == null) {
if (savedInstanceState != null) {
session = Session.restoreSession(activity, null, callback, savedInstanceState);
}
if (session == null) {
session = new Session(activity);
}
Session.setActiveSession(session);
}
if (savedInstanceState != null) {
pendingFacebookDialogCall = savedInstanceState.getParcelable(DIALOG_CALL_BUNDLE_SAVE_KEY);
}
} | java | {
"resource": ""
} |
q14125 | UiLifecycleHelper.onResume | train | public void onResume() {
Session session = Session.getActiveSession();
if (session != null) {
if (callback != null) {
session.addCallback(callback);
}
if (SessionState.CREATED_TOKEN_LOADED.equals(session.getState())) {
session.openForRead(null);
}
}
// add the broadcast receiver
IntentFilter filter = new IntentFilter();
filter.addAction(Session.ACTION_ACTIVE_SESSION_SET);
filter.addAction(Session.ACTION_ACTIVE_SESSION_UNSET);
// Add a broadcast receiver to listen to when the active Session
// is set or unset, and add/remove our callback as appropriate
broadcastManager.registerReceiver(receiver, filter);
} | java | {
"resource": ""
} |
q14126 | UiLifecycleHelper.onActivityResult | train | public void onActivityResult(int requestCode, int resultCode, Intent data) {
onActivityResult(requestCode, resultCode, data, null);
} | java | {
"resource": ""
} |
q14127 | UiLifecycleHelper.onActivityResult | train | public void onActivityResult(int requestCode, int resultCode, Intent data,
FacebookDialog.Callback facebookDialogCallback) {
Session session = Session.getActiveSession();
if (session != null) {
session.onActivityResult(activity, requestCode, resultCode, data);
}
handleFacebookDialogActivityResult(requestCode, resultCode, data, facebookDialogCallback);
} | java | {
"resource": ""
} |
q14128 | UiLifecycleHelper.onSaveInstanceState | train | public void onSaveInstanceState(Bundle outState) {
Session.saveSession(Session.getActiveSession(), outState);
outState.putParcelable(DIALOG_CALL_BUNDLE_SAVE_KEY, pendingFacebookDialogCall);
} | java | {
"resource": ""
} |
q14129 | UiLifecycleHelper.onPause | train | public void onPause() {
// remove the broadcast receiver
broadcastManager.unregisterReceiver(receiver);
if (callback != null) {
Session session = Session.getActiveSession();
if (session != null) {
session.removeCallback(callback);
}
}
} | java | {
"resource": ""
} |
q14130 | CoreUtils.definitionEvaluator | train | public static Evaluator definitionEvaluator(
HandlerDefinition hda) {
return definitionEvaluators.computeIfAbsent(hda.evaluator(), key -> {
try {
return hda.evaluator().getConstructor().newInstance();
} catch (InstantiationException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException e) {
throw new IllegalStateException(e);
}
});
} | java | {
"resource": ""
} |
q14131 | TaskGroupSpecification.matches | train | public boolean matches(TaskGroupInformation info) {
return getActivity().equals(info.getActivity()) &&
getInputType().equals(info.getInputType()) &&
getOutputType().equals(info.getOutputType()) &&
info.matchesLocale(getLocale());
} | java | {
"resource": ""
} |
q14132 | LoggerWrapper.logDomNodeList | train | public void logDomNodeList (String msg, NodeList nodeList) {
StackTraceElement caller = StackTraceUtils.getCallerStackTraceElement ();
String toLog = (msg != null ? msg + "\n" : "DOM nodelist:\n");
for (int i = 0; i < nodeList.getLength (); i++) {
toLog += domNodeDescription (nodeList.item (i), 0) + "\n";
}
if (caller != null) {
logger.logp (Level.FINER, caller.getClassName (), caller.getMethodName () + "():" + caller.getLineNumber (), toLog);
} else {
logger.logp (Level.FINER, "(UnknownSourceClass)", "(unknownSourceMethod)", toLog);
}
} | java | {
"resource": ""
} |
q14133 | LoggerWrapper.logDomNode | train | public void logDomNode (String msg, Node node) {
StackTraceElement caller = StackTraceUtils.getCallerStackTraceElement ();
logDomNode (msg, node, Level.FINER, caller);
} | java | {
"resource": ""
} |
q14134 | LoggerWrapper.logDomNode | train | public void logDomNode (String msg, Node node, Level level, StackTraceElement caller) {
String toLog = (msg != null ? msg + "\n" : "DOM node:\n") + domNodeDescription (node, 0);
if (caller != null) {
logger.logp (level, caller.getClassName (), caller.getMethodName () + "():" + caller.getLineNumber (), toLog);
} else {
logger.logp (level, "(UnknownSourceClass)", "(unknownSourceMethod)", toLog);
}
} | java | {
"resource": ""
} |
q14135 | LoggerWrapper.domNodeDescription | train | private String domNodeDescription (Node node, int tablevel) {
String domNodeDescription = null;
String nodeName = node.getNodeName ();
String nodeValue = node.getNodeValue ();
if (!(nodeName.equals ("#text") && nodeValue.replaceAll ("\n", "").trim ().equals (""))) {
domNodeDescription = tabs (tablevel) + node.getNodeName () + "\n";
NamedNodeMap attributes = node.getAttributes ();
if (attributes != null) {
for (int i = 0; i < attributes.getLength (); i++) {
Node attribute = attributes.item (i);
domNodeDescription += tabs (tablevel) + "-" + attribute.getNodeName () + "=" + attribute.getNodeValue () + "\n";
}
}
domNodeDescription += tabs (tablevel) + "=" + node.getNodeValue () + "\n";
NodeList children = node.getChildNodes ();
if (children != null) {
for (int i = 0; i < children.getLength (); i++) {
String childDescription = domNodeDescription (children.item (i), tablevel + 1);
if (childDescription != null) {
domNodeDescription += childDescription;
}
}
}
}
return domNodeDescription;
} | java | {
"resource": ""
} |
q14136 | LoggerWrapper.setLevel | train | public void setLevel (Level level) {
this.defaultLevel = level;
logger.setLevel (level);
for (Handler handler : logger.getHandlers ()) {
handler.setLevel (level);
}
} | java | {
"resource": ""
} |
q14137 | TcpServer.onRegistered | train | @Handler(channels = Self.class)
public void onRegistered(NioRegistration.Completed event)
throws InterruptedException, IOException {
NioHandler handler = event.event().handler();
if (handler == this) {
if (event.event().get() == null) {
fire(new Error(event,
"Registration failed, no NioDispatcher?"));
return;
}
registration = event.event().get();
purger = new Purger();
purger.start();
fire(new Ready(serverSocketChannel.getLocalAddress()));
return;
}
if (handler instanceof TcpChannelImpl) {
TcpChannelImpl channel = (TcpChannelImpl) handler;
channel.downPipeline()
.fire(new Accepted(channel.nioChannel().getLocalAddress(),
channel.nioChannel().getRemoteAddress(), false,
Collections.emptyList()), channel);
channel.registrationComplete(event.event());
}
} | java | {
"resource": ""
} |
q14138 | TcpServer.onClose | train | @Handler
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
public void onClose(Close event) throws IOException, InterruptedException {
boolean subOnly = true;
for (Channel channel : event.channels()) {
if (channel instanceof TcpChannelImpl) {
if (channels.contains(channel)) {
((TcpChannelImpl) channel).close();
}
} else {
subOnly = false;
}
}
if (subOnly || !serverSocketChannel.isOpen()) {
// Closed already
fire(new Closed());
return;
}
synchronized (channels) {
closing = true;
// Copy to avoid concurrent modification exception
Set<TcpChannelImpl> conns = new HashSet<>(channels);
for (TcpChannelImpl conn : conns) {
conn.close();
}
while (!channels.isEmpty()) {
channels.wait();
}
}
serverSocketChannel.close();
purger.interrupt();
closing = false;
fire(new Closed());
} | java | {
"resource": ""
} |
q14139 | StringUtils.tokenize2vector | train | public static Vector<String> tokenize2vector(final String source, final char delimiter) {
final Vector<String> v = new Vector<>();
StringBuilder currentS = new StringBuilder();
char c;
for (int i = 0; i < source.length(); i++) {
c = source.charAt(i);
if (c == delimiter) {
v.addElement(currentS.length() > 0 ? currentS.toString() : "");
currentS = new StringBuilder(); //TODO: should be use one SB and not create another one
} else {
currentS.append(c);
}
}
if (currentS.length() > 0)
v.addElement(currentS.toString());
return v;
} | java | {
"resource": ""
} |
q14140 | StringUtils.removeCComments | train | public static String removeCComments(final String src) {
final StringBuilder ret = new StringBuilder();
boolean inComments = false;
for (int i = 0; i < src.length(); i++) {
char c = src.charAt(i);
if (inComments) {
if (c == '*' && src.charAt(i + 1) == '/') {
inComments = false;
i++;
}
} else {
if (c == '/') {
if (src.charAt(i + 1) == '*') {
inComments = true;
i++;
} else {
ret.append(c);
}
} else
ret.append(c);
}
}
return ret.toString();
} | java | {
"resource": ""
} |
q14141 | NativeAppCallAttachmentStore.cleanupAttachmentsForCall | train | public void cleanupAttachmentsForCall(Context context, UUID callId) {
File dir = getAttachmentsDirectoryForCall(callId, false);
Utility.deleteDirectory(dir);
} | java | {
"resource": ""
} |
q14142 | ManagedBuffer.duplicate | train | @SuppressWarnings("unchecked")
public final T duplicate() {
if (backing instanceof ByteBuffer) {
return (T) ((ByteBuffer) backing).duplicate();
}
if (backing instanceof CharBuffer) {
return (T) ((CharBuffer) backing).duplicate();
}
throw new IllegalArgumentException("Backing buffer of unknown type.");
} | java | {
"resource": ""
} |
q14143 | HandlerList.process | train | public void process(EventPipeline eventPipeline, EventBase<?> event) {
try {
for (HandlerReference hdlr : this) {
try {
hdlr.invoke(event);
if (event.isStopped()) {
break;
}
} catch (AssertionError t) {
// JUnit support
CoreUtils.setAssertionError(t);
event.handlingError(eventPipeline, t);
} catch (Error e) { // NOPMD
// Wouldn't have caught it, if it was possible.
throw e;
} catch (Throwable t) { // NOPMD
// Errors have been rethrown, so this should work.
event.handlingError(eventPipeline, t);
}
}
} finally { // NOPMD
try {
event.handled();
} catch (AssertionError t) {
// JUnit support
CoreUtils.setAssertionError(t);
event.handlingError(eventPipeline, t);
} catch (Error e) { // NOPMD
// Wouldn't have caught it, if it was possible.
throw e;
} catch (Throwable t) { // NOPMD
// Errors have been rethrown, so this should work.
event.handlingError(eventPipeline, t);
}
}
} | java | {
"resource": ""
} |
q14144 | SessionTracker.getOpenSession | train | public Session getOpenSession() {
Session openSession = getSession();
if (openSession != null && openSession.isOpened()) {
return openSession;
}
return null;
} | java | {
"resource": ""
} |
q14145 | SessionTracker.setSession | train | public void setSession(Session newSession) {
if (newSession == null) {
if (session != null) {
// We're current tracking a Session. Remove the callback
// and start tracking the active Session.
session.removeCallback(callback);
session = null;
addBroadcastReceiver();
if (getSession() != null) {
getSession().addCallback(callback);
}
}
} else {
if (session == null) {
// We're currently tracking the active Session, but will be
// switching to tracking a different Session object.
Session activeSession = Session.getActiveSession();
if (activeSession != null) {
activeSession.removeCallback(callback);
}
broadcastManager.unregisterReceiver(receiver);
} else {
// We're currently tracking a Session, but are now switching
// to a new Session, so we remove the callback from the old
// Session, and add it to the new one.
session.removeCallback(callback);
}
session = newSession;
session.addCallback(callback);
}
} | java | {
"resource": ""
} |
q14146 | SessionTracker.stopTracking | train | public void stopTracking() {
if (!isTracking) {
return;
}
Session session = getSession();
if (session != null) {
session.removeCallback(callback);
}
broadcastManager.unregisterReceiver(receiver);
isTracking = false;
} | java | {
"resource": ""
} |
q14147 | LinkedIOSubchannel.associated | train | @Override
@SuppressWarnings("PMD.ShortVariable")
public <V> Optional<V> associated(Object by, Class<V> type) {
Optional<V> result = super.associated(by, type);
if (!result.isPresent()) {
IOSubchannel upstream = upstreamChannel();
if (upstream != null) {
return upstream.associated(by, type);
}
}
return result;
} | java | {
"resource": ""
} |
q14148 | FacebookAppLinkResolver.getAppLinkFromUrlInBackground | train | public Task<AppLink> getAppLinkFromUrlInBackground(final Uri uri) {
ArrayList<Uri> uris = new ArrayList<Uri>();
uris.add(uri);
Task<Map<Uri, AppLink>> resolveTask = getAppLinkFromUrlsInBackground(uris);
return resolveTask.onSuccess(new Continuation<Map<Uri, AppLink>, AppLink>() {
@Override
public AppLink then(Task<Map<Uri, AppLink>> resolveUrisTask) throws Exception {
return resolveUrisTask.getResult().get(uri);
}
});
} | java | {
"resource": ""
} |
q14149 | BatchFlusher.flush | train | public void flush() {
if (eventLoop.inEventLoop()) {
pending++;
if (pending >= maxPending) {
pending = 0;
channel.flush();
}
}
if (woken == 0 && WOKEN.compareAndSet(this, 0, 1)) {
woken = 1;
eventLoop.execute(wakeup);
}
} | java | {
"resource": ""
} |
q14150 | InputStreamMonitor.onStart | train | @Handler
public void onStart(Start event) {
synchronized (this) {
if (runner != null) {
return;
}
buffers = new ManagedBufferPool<>(ManagedBuffer::new,
() -> {
return ByteBuffer.allocateDirect(bufferSize);
}, 2);
runner = new Thread(this, Components.simpleObjectName(this));
// Because this cannot reliably be stopped, it doesn't prevent
// shutdown.
runner.setDaemon(true);
runner.start();
}
} | java | {
"resource": ""
} |
q14151 | InputStreamMonitor.onStop | train | @Handler(priority = -10000)
public void onStop(Stop event) throws InterruptedException {
synchronized (this) {
if (runner == null) {
return;
}
runner.interrupt();
synchronized (this) {
if (registered) {
unregisterAsGenerator();
registered = false;
}
}
runner = null;
}
} | java | {
"resource": ""
} |
q14152 | ComponentVertex.componentVertex | train | public static ComponentVertex componentVertex(
ComponentType component, Channel componentChannel) {
if (component instanceof ComponentVertex) {
return (ComponentVertex) component;
}
return ComponentProxy.getComponentProxy(component, componentChannel);
} | java | {
"resource": ""
} |
q14153 | ComponentVertex.setTree | train | private void setTree(ComponentTree tree) {
synchronized (this) {
this.tree = tree;
for (ComponentVertex child : children) {
child.setTree(tree);
}
}
} | java | {
"resource": ""
} |
q14154 | ComponentVertex.collectHandlers | train | @SuppressWarnings("PMD.UseVarargs")
/* default */ void collectHandlers(Collection<HandlerReference> hdlrs,
EventBase<?> event, Channel[] channels) {
for (HandlerReference hdlr : handlers) {
if (hdlr.handles(event, channels)) {
hdlrs.add(hdlr);
}
}
for (ComponentVertex child : children) {
child.collectHandlers(hdlrs, event, channels);
}
} | java | {
"resource": ""
} |
q14155 | PlacePickerFragment.getSelection | train | public GraphPlace getSelection() {
Collection<GraphPlace> selection = getSelectedGraphObjects();
return (selection != null && !selection.isEmpty()) ? selection.iterator().next() : null;
} | java | {
"resource": ""
} |
q14156 | FieldErrorAttributeProcessor.hasFieldError | train | protected boolean hasFieldError(String fieldname) {
if ( StringUtils.isEmpty(fieldname)) {
return false;
}
Object action = ActionContext.getContext().getActionInvocation().getAction();
// check action instance 'ActionSupport'.
if (!(action instanceof ActionSupport)) {
return false;
}
ActionSupport asupport = (ActionSupport) action;
Map<String, List<String>> fieldErrors = asupport.getFieldErrors();
if (CollectionUtils.isEmpty(fieldErrors)) {
return false;
}
List<String> targetFieldErrors = fieldErrors.get(fieldname);
if (CollectionUtils.isEmpty(targetFieldErrors)) {
return false;
}
return true;
} | java | {
"resource": ""
} |
q14157 | FieldErrorAttributeProcessor.getFieldValue | train | protected Object getFieldValue(String fieldname) {
ActionContext actionCtx = ActionContext.getContext();
ValueStack valueStack = actionCtx.getValueStack();
Object value = valueStack.findValue(fieldname, false);
String overwriteValue = getOverwriteValue(fieldname);
if ( overwriteValue != null ) {
return overwriteValue;
}
return value;
} | java | {
"resource": ""
} |
q14158 | FieldErrorAttributeProcessor.getOverwriteValue | train | protected String getOverwriteValue(String fieldname) {
ActionContext ctx = ServletActionContext.getContext();
ValueStack stack = ctx.getValueStack();
Map<Object ,Object> overrideMap = stack.getExprOverrides();
// If convertion error has not, do nothing.
if ( overrideMap == null || overrideMap.isEmpty()) {
return null;
}
if (! overrideMap.containsKey(fieldname)) {
return null;
}
String convertionValue = (String)overrideMap.get(fieldname);
// Struts2-Conponent is wrapped String quote, which erase for output value.
String altString = StringEscapeUtils.unescapeJava(convertionValue);
altString = altString.substring(1, altString.length() -1);
return altString;
} | java | {
"resource": ""
} |
q14159 | ProfilePictureView.setPresetSize | train | public final void setPresetSize(int sizeType) {
switch (sizeType) {
case SMALL:
case NORMAL:
case LARGE:
case CUSTOM:
this.presetSizeType = sizeType;
break;
default:
throw new IllegalArgumentException("Must use a predefined preset size");
}
requestLayout();
} | java | {
"resource": ""
} |
q14160 | ProfilePictureView.setProfileId | train | public final void setProfileId(String profileId) {
boolean force = false;
if (Utility.isNullOrEmpty(this.profileId) || !this.profileId.equalsIgnoreCase(profileId)) {
// Clear out the old profilePicture before requesting for the new one.
setBlankProfilePicture();
force = true;
}
this.profileId = profileId;
refreshImage(force);
} | java | {
"resource": ""
} |
q14161 | ProfilePictureView.onSaveInstanceState | train | @Override
protected Parcelable onSaveInstanceState() {
Parcelable superState = super.onSaveInstanceState();
Bundle instanceState = new Bundle();
instanceState.putParcelable(SUPER_STATE_KEY, superState);
instanceState.putString(PROFILE_ID_KEY, profileId);
instanceState.putInt(PRESET_SIZE_KEY, presetSizeType);
instanceState.putBoolean(IS_CROPPED_KEY, isCropped);
instanceState.putParcelable(BITMAP_KEY, imageContents);
instanceState.putInt(BITMAP_WIDTH_KEY, queryWidth);
instanceState.putInt(BITMAP_HEIGHT_KEY, queryHeight);
instanceState.putBoolean(PENDING_REFRESH_KEY, lastRequest != null);
return instanceState;
} | java | {
"resource": ""
} |
q14162 | ProfilePictureView.onRestoreInstanceState | train | @Override
protected void onRestoreInstanceState(Parcelable state) {
if (state.getClass() != Bundle.class) {
super.onRestoreInstanceState(state);
} else {
Bundle instanceState = (Bundle)state;
super.onRestoreInstanceState(instanceState.getParcelable(SUPER_STATE_KEY));
profileId = instanceState.getString(PROFILE_ID_KEY);
presetSizeType = instanceState.getInt(PRESET_SIZE_KEY);
isCropped = instanceState.getBoolean(IS_CROPPED_KEY);
queryWidth = instanceState.getInt(BITMAP_WIDTH_KEY);
queryHeight = instanceState.getInt(BITMAP_HEIGHT_KEY);
setImageBitmap((Bitmap)instanceState.getParcelable(BITMAP_KEY));
if (instanceState.getBoolean(PENDING_REFRESH_KEY)) {
refreshImage(true);
}
}
} | java | {
"resource": ""
} |
q14163 | PeasyRecyclerView.enhanceFAB | train | private void enhanceFAB(final FloatingActionButton fab, int dx, int dy) {
if (isEnhancedFAB() && getFab() != null) {
final FloatingActionButton mFloatingActionButton = this.fab;
if (getLinearLayoutManager() != null) {
if (dy > 0) {
if (mFloatingActionButton.getVisibility() == View.VISIBLE) {
mFloatingActionButton.hide();
}
} else {
if (mFloatingActionButton.getVisibility() != View.VISIBLE) {
mFloatingActionButton.show();
}
}
}
}
} | java | {
"resource": ""
} |
q14164 | PeasyRecyclerView.enhanceFAB | train | private void enhanceFAB(final FloatingActionButton fab, MotionEvent e) {
if (hasAllItemsShown()) {
if (fab.getVisibility() != View.VISIBLE) {
fab.show();
}
}
} | java | {
"resource": ""
} |
q14165 | PeasyRecyclerView.getHeaderViewType | train | private int getHeaderViewType(int position) {
if (headerContent != null) {
if (headerContent.getData() == getItem(position) && (position == 0)) {
return headerContent.getViewtype();
}
}
return PeasyHeaderViewHolder.VIEWTYPE_NOTHING;
} | java | {
"resource": ""
} |
q14166 | PeasyRecyclerView.getFooterViewType | train | public int getFooterViewType(int position) {
if (footerContent != null) {
if (footerContent.getData() == getItem(position) && (position == getLastItemIndex())) {
return footerContent.getViewtype();
}
}
return PeasyHeaderViewHolder.VIEWTYPE_NOTHING;
} | java | {
"resource": ""
} |
q14167 | PeasyRecyclerView.onItemLongClick | train | public boolean onItemLongClick(final View view, final int viewType, final int position, final T item, final PeasyViewHolder viewHolder) {
return true;
} | java | {
"resource": ""
} |
q14168 | ResponseCreationSupport.sendStaticContent | train | @SuppressWarnings({ "PMD.NcssCount",
"PMD.UseStringBufferForStringAppends" })
public static boolean sendStaticContent(
HttpRequest request, IOSubchannel channel,
Function<String, URL> resolver, MaxAgeCalculator maxAgeCalculator) {
String path = request.requestUri().getPath();
URL resourceUrl = resolver.apply(path);
ResourceInfo info;
URLConnection resConn;
InputStream resIn;
try {
if (resourceUrl == null) {
throw new IOException();
}
info = ResponseCreationSupport.resourceInfo(resourceUrl);
if (Boolean.TRUE.equals(info.isDirectory())) {
throw new IOException();
}
resConn = resourceUrl.openConnection();
resIn = resConn.getInputStream();
} catch (IOException e1) {
try {
if (!path.endsWith("/")) {
path += "/";
}
path += "index.html";
resourceUrl = resolver.apply(path);
if (resourceUrl == null) {
return false;
}
info = ResponseCreationSupport.resourceInfo(resourceUrl);
resConn = resourceUrl.openConnection();
resIn = resConn.getInputStream();
} catch (IOException e2) {
return false;
}
}
HttpResponse response = request.response().get();
response.setField(HttpField.LAST_MODIFIED,
Optional.ofNullable(info.getLastModifiedAt())
.orElseGet(() -> Instant.now()));
// Get content type and derive max age
MediaType mediaType = HttpResponse.contentType(
ResponseCreationSupport.uriFromUrl(resourceUrl));
setMaxAge(response,
(maxAgeCalculator == null ? DEFAULT_MAX_AGE_CALCULATOR
: maxAgeCalculator).maxAge(request, mediaType));
// Check if sending is really required.
Optional<Instant> modifiedSince = request
.findValue(HttpField.IF_MODIFIED_SINCE, Converters.DATE_TIME);
if (modifiedSince.isPresent() && info.getLastModifiedAt() != null
&& !info.getLastModifiedAt().isAfter(modifiedSince.get())) {
response.setStatus(HttpStatus.NOT_MODIFIED);
channel.respond(new Response(response));
} else {
response.setContentType(mediaType);
response.setStatus(HttpStatus.OK);
channel.respond(new Response(response));
// Start sending content (Output events as resonses)
(new InputStreamPipeline(resIn, channel).suppressClose()).run();
}
return true;
} | java | {
"resource": ""
} |
q14169 | ResponseCreationSupport.resourceInfo | train | @SuppressWarnings("PMD.EmptyCatchBlock")
public static ResourceInfo resourceInfo(URL resource) {
try {
Path path = Paths.get(resource.toURI());
return new ResourceInfo(Files.isDirectory(path),
Files.getLastModifiedTime(path).toInstant()
.with(ChronoField.NANO_OF_SECOND, 0));
} catch (FileSystemNotFoundException | IOException
| URISyntaxException e) {
// Fall through
}
if ("jar".equals(resource.getProtocol())) {
try {
JarURLConnection conn
= (JarURLConnection) resource.openConnection();
JarEntry entry = conn.getJarEntry();
return new ResourceInfo(entry.isDirectory(),
entry.getLastModifiedTime().toInstant()
.with(ChronoField.NANO_OF_SECOND, 0));
} catch (IOException e) {
// Fall through
}
}
try {
URLConnection conn = resource.openConnection();
long lastModified = conn.getLastModified();
if (lastModified != 0) {
return new ResourceInfo(null, Instant.ofEpochMilli(
lastModified).with(ChronoField.NANO_OF_SECOND, 0));
}
} catch (IOException e) {
// Fall through
}
return new ResourceInfo(null, null);
} | java | {
"resource": ""
} |
q14170 | ResponseCreationSupport.setMaxAge | train | public static long setMaxAge(HttpResponse response, int maxAge) {
List<Directive> directives = new ArrayList<>();
directives.add(new Directive("max-age", maxAge));
response.setField(HttpField.CACHE_CONTROL, directives);
return maxAge;
} | java | {
"resource": ""
} |
q14171 | FriendPickerFragment.setSelection | train | public void setSelection(List<GraphUser> graphUsers) {
List<String> userIds = new ArrayList<String>();
for(GraphUser graphUser: graphUsers) {
userIds.add(graphUser.getId());
}
setSelectionByIds(userIds);
} | java | {
"resource": ""
} |
q14172 | Facebook.authorize | train | private void authorize(Activity activity, String[] permissions, int activityCode,
SessionLoginBehavior behavior, final DialogListener listener) {
checkUserSession("authorize");
pendingOpeningSession = new Session.Builder(activity).
setApplicationId(mAppId).
setTokenCachingStrategy(getTokenCache()).
build();
pendingAuthorizationActivity = activity;
pendingAuthorizationPermissions = (permissions != null) ? permissions : new String[0];
StatusCallback callback = new StatusCallback() {
@Override
public void call(Session callbackSession, SessionState state, Exception exception) {
// Invoke user-callback.
onSessionCallback(callbackSession, state, exception, listener);
}
};
Session.OpenRequest openRequest = new Session.OpenRequest(activity).
setCallback(callback).
setLoginBehavior(behavior).
setRequestCode(activityCode).
setPermissions(Arrays.asList(pendingAuthorizationPermissions));
openSession(pendingOpeningSession, openRequest, pendingAuthorizationPermissions.length > 0);
} | java | {
"resource": ""
} |
q14173 | Facebook.validateServiceIntent | train | private boolean validateServiceIntent(Context context, Intent intent) {
ResolveInfo resolveInfo = context.getPackageManager().resolveService(intent, 0);
if (resolveInfo == null) {
return false;
}
return validateAppSignatureForPackage(context, resolveInfo.serviceInfo.packageName);
} | java | {
"resource": ""
} |
q14174 | Facebook.validateAppSignatureForPackage | train | private boolean validateAppSignatureForPackage(Context context, String packageName) {
PackageInfo packageInfo;
try {
packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES);
} catch (NameNotFoundException e) {
return false;
}
for (Signature signature : packageInfo.signatures) {
if (signature.toCharsString().equals(FB_APP_SIGNATURE)) {
return true;
}
}
return false;
} | java | {
"resource": ""
} |
q14175 | Facebook.requestImpl | train | @SuppressWarnings("deprecation")
String requestImpl(String graphPath, Bundle params, String httpMethod) throws FileNotFoundException,
MalformedURLException, IOException {
params.putString("format", "json");
if (isSessionValid()) {
params.putString(TOKEN, getAccessToken());
}
String url = (graphPath != null) ? GRAPH_BASE_URL + graphPath : RESTSERVER_URL;
return Util.openUrl(url, httpMethod, params);
} | java | {
"resource": ""
} |
q14176 | Facebook.setSession | train | @Deprecated
public void setSession(Session session) {
if (session == null) {
throw new IllegalArgumentException("session cannot be null");
}
synchronized (this.lock) {
this.userSetSession = session;
}
} | java | {
"resource": ""
} |
q14177 | Facebook.getSession | train | @Deprecated
public final Session getSession() {
while (true) {
String cachedToken = null;
Session oldSession = null;
synchronized (this.lock) {
if (userSetSession != null) {
return userSetSession;
}
if ((session != null) || !sessionInvalidated) {
return session;
}
cachedToken = accessToken;
oldSession = session;
}
if (cachedToken == null) {
return null;
}
// At this point we do not have a valid session, but mAccessToken is
// non-null.
// So we can try building a session based on that.
List<String> permissions;
if (oldSession != null) {
permissions = oldSession.getPermissions();
} else if (pendingAuthorizationPermissions != null) {
permissions = Arrays.asList(pendingAuthorizationPermissions);
} else {
permissions = Collections.<String>emptyList();
}
Session newSession = new Session.Builder(pendingAuthorizationActivity).
setApplicationId(mAppId).
setTokenCachingStrategy(getTokenCache()).
build();
if (newSession.getState() != SessionState.CREATED_TOKEN_LOADED) {
return null;
}
Session.OpenRequest openRequest =
new Session.OpenRequest(pendingAuthorizationActivity).setPermissions(permissions);
openSession(newSession, openRequest, !permissions.isEmpty());
Session invalidatedSession = null;
Session returnSession = null;
synchronized (this.lock) {
if (sessionInvalidated || (session == null)) {
invalidatedSession = session;
returnSession = session = newSession;
sessionInvalidated = false;
}
}
if (invalidatedSession != null) {
invalidatedSession.close();
}
if (returnSession != null) {
return returnSession;
}
// Else token state changed between the synchronized blocks, so
// retry..
}
} | java | {
"resource": ""
} |
q14178 | NioDispatcher.onStart | train | @Handler
public void onStart(Start event) {
synchronized (this) {
if (runner != null && !runner.isInterrupted()) {
return;
}
runner = new Thread(this, Components.simpleObjectName(this));
runner.start();
}
} | java | {
"resource": ""
} |
q14179 | NioDispatcher.onStop | train | @Handler(priority = -10000)
public void onStop(Stop event) throws InterruptedException {
synchronized (this) {
if (runner == null) {
return;
}
// It just might happen that the wakeup() occurs between the
// check for running and the select() in the thread's run loop,
// but we -- obviously -- cannot put the select() in a
// synchronized(this).
while (runner.isAlive()) {
runner.interrupt(); // *Should* be sufficient, but...
selector.wakeup(); // Make sure
runner.join(10);
}
runner = null;
}
} | java | {
"resource": ""
} |
q14180 | NioDispatcher.onNioRegistration | train | @Handler
public void onNioRegistration(NioRegistration event)
throws IOException {
SelectableChannel channel = event.ioChannel();
channel.configureBlocking(false);
SelectionKey key;
synchronized (selectorGate) {
selector.wakeup(); // make sure selector isn't blocking
key = channel.register(
selector, event.ops(), event.handler());
}
event.setResult(new Registration(key));
} | java | {
"resource": ""
} |
q14181 | ScanStrategy.innerJoin | train | private DataContainer innerJoin(DataContainer left, DataContainer right, Optional<BooleanExpression> joinCondition) {
return crossJoin(left, right, joinCondition, JoinType.INNER);
} | java | {
"resource": ""
} |
q14182 | SessionManager.derivePattern | train | @SuppressWarnings("PMD.DataflowAnomalyAnalysis")
protected static String derivePattern(String path) {
String pattern;
if ("/".equals(path)) {
pattern = "/**";
} else {
String patternBase = path;
if (patternBase.endsWith("/")) {
patternBase = path.substring(0, path.length() - 1);
}
pattern = path + "," + path + "/**";
}
return pattern;
} | java | {
"resource": ""
} |
q14183 | SessionManager.createSessionId | train | protected String createSessionId(HttpResponse response) {
StringBuilder sessionIdBuilder = new StringBuilder();
byte[] bytes = new byte[16];
secureRandom.nextBytes(bytes);
for (byte b : bytes) {
sessionIdBuilder.append(Integer.toHexString(b & 0xff));
}
String sessionId = sessionIdBuilder.toString();
HttpCookie sessionCookie = new HttpCookie(idName(), sessionId);
sessionCookie.setPath(path);
sessionCookie.setHttpOnly(true);
response.computeIfAbsent(HttpField.SET_COOKIE, CookieList::new)
.value().add(sessionCookie);
response.computeIfAbsent(
HttpField.CACHE_CONTROL, CacheControlDirectives::new)
.value().add(new Directive("no-cache", "SetCookie, Set-Cookie2"));
return sessionId;
} | java | {
"resource": ""
} |
q14184 | SessionManager.discard | train | @Handler(channels = Channel.class)
public void discard(DiscardSession event) {
removeSession(event.session().id());
} | java | {
"resource": ""
} |
q14185 | SessionManager.onProtocolSwitchAccepted | train | @Handler(priority = 1000)
public void onProtocolSwitchAccepted(
ProtocolSwitchAccepted event, IOSubchannel channel) {
event.requestEvent().associated(Session.class)
.ifPresent(session -> {
channel.setAssociated(Session.class, session);
});
} | java | {
"resource": ""
} |
q14186 | TcpConnector.onOpenConnection | train | @Handler
public void onOpenConnection(OpenTcpConnection event) {
try {
SocketChannel socketChannel = SocketChannel.open(event.address());
channels.add(new TcpChannelImpl(socketChannel));
} catch (ConnectException e) {
fire(new ConnectError(event, "Connection refused.", e));
} catch (IOException e) {
fire(new ConnectError(event, "Failed to open TCP connection.", e));
}
} | java | {
"resource": ""
} |
q14187 | TcpConnector.onRegistered | train | @Handler(channels = Self.class)
public void onRegistered(NioRegistration.Completed event)
throws InterruptedException, IOException {
NioHandler handler = event.event().handler();
if (!(handler instanceof TcpChannelImpl)) {
return;
}
if (event.event().get() == null) {
fire(new Error(event, "Registration failed, no NioDispatcher?",
new Throwable()));
return;
}
TcpChannelImpl channel = (TcpChannelImpl) handler;
channel.registrationComplete(event.event());
channel.downPipeline()
.fire(new Connected(channel.nioChannel().getLocalAddress(),
channel.nioChannel().getRemoteAddress()), channel);
} | java | {
"resource": ""
} |
q14188 | TcpConnector.onClose | train | @Handler
@SuppressWarnings("PMD.DataflowAnomalyAnalysis")
public void onClose(Close event) throws IOException, InterruptedException {
for (Channel channel : event.channels()) {
if (channel instanceof TcpChannelImpl
&& channels.contains(channel)) {
((TcpChannelImpl) channel).close();
}
}
} | java | {
"resource": ""
} |
q14189 | ValidatorFactoryMaker.newValidator | train | @Override
public Validator newValidator(String identifier) {
if (identifier==null) {
return null;
}
ValidatorFactory template;
synchronized (map) {
verifyMapIntegrity();
template = map.get(identifier);
}
if (template!=null) {
try {
return template.newValidator(identifier);
} catch (ValidatorFactoryException e) {
logger.log(Level.WARNING, "Failed to create validator.", e);
return null;
}
} else {
return null;
}
} | java | {
"resource": ""
} |
q14190 | ResourcePattern.matches | train | @SuppressWarnings({ "PMD.CyclomaticComplexity", "PMD.NPathComplexity",
"PMD.CollapsibleIfStatements", "PMD.DataflowAnomalyAnalysis" })
public int matches(URI resource) {
if (protocol != null && !protocol.equals("*")) {
if (resource.getScheme() == null) {
return -1;
}
if (Arrays.stream(protocol.split(","))
.noneMatch(proto -> proto.equals(resource.getScheme()))) {
return -1;
}
}
if (host != null && !host.equals("*")) {
if (resource.getHost() == null
|| !resource.getHost().equals(host)) {
return -1;
}
}
if (port != null && !port.equals("*")) {
if (Integer.parseInt(port) != resource.getPort()) {
return -1;
}
}
String[] reqElements = PathSpliterator.stream(resource.getPath())
.skip(1).toArray(size -> new String[size]);
String[] reqElementsPlus = null; // Created lazily
for (int pathIdx = 0; pathIdx < pathPatternElements.length; pathIdx++) {
String[] pathPattern = pathPatternElements[pathIdx];
if (prefixSegs[pathIdx] == pathPattern.length - 1
&& lastIsEmpty(pathPattern)) {
// Special case, pattern ends with vertical bar
if (reqElementsPlus == null) {
reqElementsPlus = reqElements;
if (!lastIsEmpty(reqElementsPlus)) {
reqElementsPlus = Arrays.copyOf(
reqElementsPlus, reqElementsPlus.length + 1);
reqElementsPlus[reqElementsPlus.length - 1] = "";
}
}
if (matchPath(pathPattern, reqElementsPlus)) {
return prefixSegs[pathIdx];
}
} else {
if (matchPath(pathPattern, reqElements)) {
return prefixSegs[pathIdx];
}
}
}
return -1;
} | java | {
"resource": ""
} |
q14191 | ResourcePattern.matches | train | public static boolean matches(String pattern, URI resource)
throws ParseException {
return (new ResourcePattern(pattern)).matches(resource) >= 0;
} | java | {
"resource": ""
} |
q14192 | StaticContentDispatcher.onGet | train | @RequestHandler(dynamic = true)
public void onGet(Request.In.Get event, IOSubchannel channel)
throws ParseException, IOException {
int prefixSegs = resourcePattern.matches(event.requestUri());
if (prefixSegs < 0) {
return;
}
if (contentDirectory == null) {
getFromUri(event, channel, prefixSegs);
} else {
getFromFileSystem(event, channel, prefixSegs);
}
} | java | {
"resource": ""
} |
q14193 | EchoUntilQuit.onInput | train | @Handler
@SuppressWarnings("PMD.SystemPrintln")
public void onInput(Input<ByteBuffer> event) {
String data = Charset.defaultCharset().decode(event.data()).toString();
System.out.print(data);
if (data.trim().equals("QUIT")) {
fire(new Stop());
}
} | java | {
"resource": ""
} |
q14194 | ConfigurationUpdate.removePath | train | public ConfigurationUpdate removePath(String path) {
if (path == null || !path.startsWith("/")) {
throw new IllegalArgumentException("Path must start with \"/\".");
}
paths.put(path, null);
return this;
} | java | {
"resource": ""
} |
q14195 | ConfigurationUpdate.values | train | public Optional<Map<String,String>> values(String path) {
Map<String,String> result = paths.get(path);
if (result == null) {
return Optional.empty();
}
return Optional.of(Collections.unmodifiableMap(result));
} | java | {
"resource": ""
} |
q14196 | ConfigurationUpdate.value | train | public Optional<String> value(String path, String key) {
return Optional.ofNullable(paths.get(path))
.flatMap(map -> Optional.ofNullable(map.get(key)));
} | java | {
"resource": ""
} |
q14197 | TextUtils.isRange | train | public static boolean isRange(String value) {
if (value == null) {
return false;
}
try {
Set<Integer> values = parseRange(value);
return values.size() > 0;
} catch (Exception e) {
return false;
}
} | java | {
"resource": ""
} |
q14198 | SSLTools.disableSSLValidation | train | public static void disableSSLValidation() {
try {
SSLContext context = SSLContext.getInstance("SSL");
context.init(null, new TrustManager[]{new UnsafeTrustManager()}, null);
HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
} catch (Exception e) {
throw new RuntimeException(e);
}
} | java | {
"resource": ""
} |
q14199 | SSLTools.enableSSLValidation | train | public static void enableSSLValidation() {
try {
SSLContext.getInstance("SSL").init(null, null, null);
} catch (Exception e) {
throw new RuntimeException(e);
}
} | java | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.