code
stringlengths
73
34.1k
label
stringclasses
1 value
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 ) { ...
java
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()...
java
public final void setPresetSize(int sizeType) { switch (sizeType) { case SMALL: case NORMAL: case LARGE: case CUSTOM: this.presetSizeType = sizeType; break; default: throw new IllegalArgumentException("M...
java
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...
java
@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(...
java
@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...
java
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 (mFloatingActionB...
java
private void enhanceFAB(final FloatingActionButton fab, MotionEvent e) { if (hasAllItemsShown()) { if (fab.getVisibility() != View.VISIBLE) { fab.show(); } } }
java
private int getHeaderViewType(int position) { if (headerContent != null) { if (headerContent.getData() == getItem(position) && (position == 0)) { return headerContent.getViewtype(); } } return PeasyHeaderViewHolder.VIEWTYPE_NOTHING; }
java
public int getFooterViewType(int position) { if (footerContent != null) { if (footerContent.getData() == getItem(position) && (position == getLastItemIndex())) { return footerContent.getViewtype(); } } return PeasyHeaderViewHolder.VIEWTYPE_NOTHING; }
java
public boolean onItemLongClick(final View view, final int viewType, final int position, final T item, final PeasyViewHolder viewHolder) { return true; }
java
@SuppressWarnings({ "PMD.NcssCount", "PMD.UseStringBufferForStringAppends" }) public static boolean sendStaticContent( HttpRequest request, IOSubchannel channel, Function<String, URL> resolver, MaxAgeCalculator maxAgeCalculator) { String path = request.requestUri().getPath();...
java
@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(Chron...
java
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
public void setSelection(List<GraphUser> graphUsers) { List<String> userIds = new ArrayList<String>(); for(GraphUser graphUser: graphUsers) { userIds.add(graphUser.getId()); } setSelectionByIds(userIds); }
java
private void authorize(Activity activity, String[] permissions, int activityCode, SessionLoginBehavior behavior, final DialogListener listener) { checkUserSession("authorize"); pendingOpeningSession = new Session.Builder(activity). setApplicationId(mAppId). ...
java
private boolean validateServiceIntent(Context context, Intent intent) { ResolveInfo resolveInfo = context.getPackageManager().resolveService(intent, 0); if (resolveInfo == null) { return false; } return validateAppSignatureForPackage(context, resolveInfo.serviceInfo.packageN...
java
private boolean validateAppSignatureForPackage(Context context, String packageName) { PackageInfo packageInfo; try { packageInfo = context.getPackageManager().getPackageInfo(packageName, PackageManager.GET_SIGNATURES); } catch (NameNotFoundException e) { return false; ...
java
@SuppressWarnings("deprecation") String requestImpl(String graphPath, Bundle params, String httpMethod) throws FileNotFoundException, MalformedURLException, IOException { params.putString("format", "json"); if (isSessionValid()) { params.putString(TOKEN, getAccessToken()); ...
java
@Deprecated public void setSession(Session session) { if (session == null) { throw new IllegalArgumentException("session cannot be null"); } synchronized (this.lock) { this.userSetSession = session; } }
java
@Deprecated public final Session getSession() { while (true) { String cachedToken = null; Session oldSession = null; synchronized (this.lock) { if (userSetSession != null) { return userSetSession; } if (...
java
@Handler public void onStart(Start event) { synchronized (this) { if (runner != null && !runner.isInterrupted()) { return; } runner = new Thread(this, Components.simpleObjectName(this)); runner.start(); } }
java
@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...
java
@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 b...
java
private DataContainer innerJoin(DataContainer left, DataContainer right, Optional<BooleanExpression> joinCondition) { return crossJoin(left, right, joinCondition, JoinType.INNER); }
java
@SuppressWarnings("PMD.DataflowAnomalyAnalysis") protected static String derivePattern(String path) { String pattern; if ("/".equals(path)) { pattern = "/**"; } else { String patternBase = path; if (patternBase.endsWith("/")) { patternBase ...
java
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 ...
java
@Handler(channels = Channel.class) public void discard(DiscardSession event) { removeSession(event.session().id()); }
java
@Handler(priority = 1000) public void onProtocolSwitchAccepted( ProtocolSwitchAccepted event, IOSubchannel channel) { event.requestEvent().associated(Session.class) .ifPresent(session -> { channel.setAssociated(Session.class, session); }); }
java
@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 refus...
java
@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() == ...
java
@Handler @SuppressWarnings("PMD.DataflowAnomalyAnalysis") public void onClose(Close event) throws IOException, InterruptedException { for (Channel channel : event.channels()) { if (channel instanceof TcpChannelImpl && channels.contains(channel)) { ((TcpChannel...
java
@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 (Valid...
java
@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; ...
java
public static boolean matches(String pattern, URI resource) throws ParseException { return (new ResourcePattern(pattern)).matches(resource) >= 0; }
java
@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) { ...
java
@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
public ConfigurationUpdate removePath(String path) { if (path == null || !path.startsWith("/")) { throw new IllegalArgumentException("Path must start with \"/\"."); } paths.put(path, null); return this; }
java
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
public Optional<String> value(String path, String key) { return Optional.ofNullable(paths.get(path)) .flatMap(map -> Optional.ofNullable(map.get(key))); }
java
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
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 Runti...
java
public static void enableSSLValidation() { try { SSLContext.getInstance("SSL").init(null, null, null); } catch (Exception e) { throw new RuntimeException(e); } }
java
public static boolean validCertificateString(String certificateString) { try { byte[] certBytes = parseDERFromPEM(certificateString, CERT_START, CERT_END); generateCertificateFromDER(certBytes); } catch (Exception e) { return false; } return true; }
java
public RESTClient<RS, ERS> urlParameter(String name, Object value) { if (value == null) { return this; } List<Object> values = this.parameters.get(name); if (values == null) { values = new ArrayList<>(); this.parameters.put(name, values); } if (value instanceof ZonedDateTime)...
java
@Override protected Enumeration<URL> findResources(String name) { URL url = findResource(name); Vector<URL> urls = new Vector<>(); if (url != null) { urls.add(url); } return urls.elements(); }
java
public void unsetUserConfigurations(UserConfigurationsProvider provider) { if (userConfigurations.isPresent() && userConfigurations.get().equals(provider)) { this.userConfigurations = Optional.empty(); } }
java
public Attribute getAttribute(final String attributeName) { final Attribute a = attributes.get(attributeName); if (a == null) throw new IllegalArgumentException("Attribute " + attributeName + " doesn't exists"); return a; }
java
public void addAttributeValue(final String attributeName, final Value attributeValue, Environment in) { if (in == null) in = GlobalEnvironment.INSTANCE; Attribute attr = attributes.get(attributeName); if (attr == null) { attr = new Attribute(attributeName); attributes.put(attr.getName(), attr); } att...
java
@Handler public void onClose(Close event, WebAppMsgChannel appChannel) throws InterruptedException { appChannel.handleClose(event); }
java
@Handler(priority = Integer.MIN_VALUE) public void onOptions(Request.In.Options event, IOSubchannel appChannel) { if (event.requestUri() == HttpRequest.ASTERISK_REQUEST) { HttpResponse response = event.httpRequest().response().get(); response.setStatus(HttpStatus.OK); app...
java
public Matcher matcher(CharSequence s) { Matcher m = new Matcher(this); m.setTarget(s); return m; }
java
public Matcher matcher(char[] data, int start, int end) { Matcher m = new Matcher(this); m.setTarget(data, start, end); return m; }
java
public Matcher matcher(MatchResult res, String groupName) { Integer id = res.pattern().groupId(groupName); if (id == null) throw new IllegalArgumentException("group not found:" + groupName); int group = id; return matcher(res, group); }
java
public List<ColumnRelation> toList() { List<ColumnRelation> ret = new ArrayList<>(); ret.add(this); if (getNextRelation().isPresent()) { ret.addAll(getNextRelation().get().toList()); } return ret; }
java
public static void addToDataSource(DataSource parent, DataSource child) { if (!parent.getLeftDataSource().isPresent()) { parent.setLeftDataSource(child); } else if (!parent.getRightDataSource().isPresent()) { parent.setRightDataSource(child); } else { DataSour...
java
@Override public String format (LogRecord logRecord) { StringBuilder resultBuilder = new StringBuilder (); String prefix = logRecord.getLevel ().getName () + "\t"; resultBuilder.append (prefix); resultBuilder.append (Thread.currentThread ().getName ()) .append (" ") .append (sdf.format (new java.util...
java
public boolean acceptsValue(String value) { if (value==null) { return false; } else if (hasValues()) { return getValuesList().contains(value); } else { return true; } }
java
private static String getUrl(int method, String baseUrl, String endpoint, Map<String, String> params) { if (params != null) { for (Map.Entry<String, String> entry : params.entrySet()) { if (entry.getValue() == null || entry.getValue().equals("null")) { entry.setValue(""); } } } if (method == M...
java
public static boolean configure (File configFile) { boolean goOn = true; if (!configFile.exists ()) { LogHelperDebug.printError ("File " + configFile.getAbsolutePath () + " does not exist", false); goOn = false; } DocumentBuilderFactory documentBuilderFactory = null; DocumentBuilder documentBuilder = ...
java
private static void configureLoggerWrapper (Node configNode) { Node lwNameNode = configNode.getAttributes ().getNamedItem ("name"); String lwName; if (lwNameNode != null) { lwName = lwNameNode.getTextContent (); } else { lwName = "LoggerWrapper_" + String.valueOf ((new Date ()).getTime ()); } LoggerW...
java
public PermitsPool removeListener(AvailabilityListener listener) { synchronized (listeners) { for (Iterator<WeakReference<AvailabilityListener>> iter = listeners.iterator(); iter.hasNext();) { WeakReference<AvailabilityListener> item = iter.next(); if ...
java
public static String className(Class<?> clazz) { if (CoreUtils.classNames.isLoggable(Level.FINER)) { return clazz.getName(); } else { return simpleClassName(clazz); } }
java
public static Timer schedule( TimeoutHandler timeoutHandler, Instant scheduledFor) { return scheduler.schedule(timeoutHandler, scheduledFor); }
java
public static Timer schedule( TimeoutHandler timeoutHandler, Duration scheduledFor) { return scheduler.schedule( timeoutHandler, Instant.now().plus(scheduledFor)); }
java
@Deprecated public static String encodePostBody(Bundle parameters, String boundary) { if (parameters == null) return ""; StringBuilder sb = new StringBuilder(); for (String key : parameters.keySet()) { Object parameter = parameters.get(key); if (!(parameter instanceo...
java
@Deprecated public static Bundle parseUrl(String url) { // hack to prevent MalformedURLException url = url.replace("fbconnect", "http"); try { URL u = new URL(url); Bundle b = decodeUrl(u.getQuery()); b.putAll(decodeUrl(u.getRef())); return b; ...
java
@Deprecated public static String openUrl(String url, String method, Bundle params) throws MalformedURLException, IOException { // random string as boundary for multi-part http post String strBoundary = "3i2ndDfv2rTHiSisAbouNdArYfORhtTPEefj3q2f"; String endLine = "\r\n"; Ou...
java
public static String getAttachmentUrl(String applicationId, UUID callId, String attachmentName) { return String.format("%s%s/%s/%s", ATTACHMENT_URL_BASE, applicationId, callId.toString(), attachmentName); }
java
@Deprecated public Character set(final int index, final Character ok) { return set(index, ok.charValue()); }
java
private void getElements(final int from, final char[] a, final int offset, final int length) { CharArrays.ensureOffsetLength(a, offset, length); System.arraycopy(this.a, from, a, offset, length); }
java
public void removeElements(final int from, final int to) { CharArrays.ensureFromTo(size, from, to); System.arraycopy(a, to, a, from, size - to); size -= (to - from); }
java
public void addElements(final int index, final char a[], final int offset, final int length) { ensureIndex(index); CharArrays.ensureOffsetLength(a, offset, length); grow(size + length); System.arraycopy(this.a, index, this.a, index + length, size - index); System.arraycopy(a, off...
java
private void ensureIndex(final int index) { if (index < 0) throw new IndexOutOfBoundsException("Index (" + index + ") is negative"); if (index > size()) throw new IndexOutOfBoundsException("Index (" + index + ") is greater than list size (" + (size()) + ")"); }
java
protected void ensureRestrictedIndex(final int index) { if (index < 0) throw new IndexOutOfBoundsException("Index (" + index + ") is negative"); if (index >= size()) throw new IndexOutOfBoundsException("Index (" + index + ") is greater than or equal to list size (" + (size()) + ")"); }
java
public boolean containsAll(Collection<?> c) { int n = c.size(); final Iterator<?> i = c.iterator(); while (n-- != 0) if (!contains(i.next())) return false; return true; }
java
public boolean addAll(Collection<? extends Character> c) { boolean retVal = false; final Iterator<? extends Character> i = c.iterator(); int n = c.size(); while (n-- != 0) if (add(i.next())) retVal = true; return retVal; }
java
public synchronized Set<ConfigurationDetails> getConfigurationDetails() { return inventory.entries().stream() .map(c->c.getConfiguration().orElse(null)) .filter(v->v!=null) .map(v->v.getDetails()) .collect(Collectors.toSet()); }
java
public synchronized Map<String, Object> getConfiguration(String key) { return Optional.ofNullable(inventory.get(key)) .flatMap(v->v.getConfiguration()) .map(v->v.getMap()) .orElse(null); }
java
public synchronized Optional<String> addConfiguration(String niceName, String description, Map<String, Object> config) { try { if (catalog==null) { throw new FileNotFoundException(); } return sync(()-> { ConfigurationDetails p = new ConfigurationDetails.Builder(inventory.nextIdentifier()) .nice...
java
public synchronized boolean removeConfiguration(String key) { try { if (catalog==null) { throw new FileNotFoundException(); } return sync(()->inventory.remove(key)!=null); } catch (IOException e) { logger.log(Level.WARNING, "Failed to remove configuration.", e); return false; } }
java
private boolean cleanupInventory() { boolean modified = false; modified |= removeUnreadable(); modified |= recreateMismatching(); modified |= importConfigurations(); return modified; }
java
private boolean removeUnreadable() { List<File> unreadable = inventory.removeUnreadable(); unreadable.forEach(v->v.delete()); return !unreadable.isEmpty(); }
java
private boolean recreateMismatching() { List<Configuration> mismatching = inventory.removeMismatching(); mismatching.forEach(entry->{ try { inventory.add(InventoryEntry.create(entry.copyWithIdentifier(inventory.nextIdentifier()), newConfigurationFile())); } catch (IOException e1) { logger.log(Level.WA...
java
private boolean importConfigurations() { // Create a set of files in the inventory Set<File> files = inventory.entries().stream().map(v->v.getPath()).collect(Collectors.toSet()); List<File> entriesToImport = Arrays.asList(baseDir.listFiles(f-> f.isFile() && !f.equals(catalog) // Exclude the master catalog (...
java
@SuppressWarnings({ "unchecked", "PMD.ShortVariable", "PMD.AvoidDuplicateLiterals" }) public <C> C[] channels(Class<C> type) { return Arrays.stream(channels) .filter(c -> type.isAssignableFrom(c.getClass())).toArray( size -> (C[]) Array.newInstance(type, size)); }
java
@SuppressWarnings({ "unchecked", "PMD.ShortVariable" }) public <E extends EventBase<?>, C extends Channel> void forChannels( Class<C> type, BiConsumer<E, C> handler) { Arrays.stream(channels) .filter(c -> type.isAssignableFrom(c.getClass())) .forEach(c -> handler.accept((...
java
public Event<T> setResult(T result) { synchronized (this) { if (results == null) { // Make sure that we have a valid result before // calling decrementOpen results = new ArrayList<T>(); results.add(result); firstResultAs...
java
protected List<T> currentResults() { return results == null ? Collections.emptyList() : Collections.unmodifiableList(results); }
java
public static View inflateView(LayoutInflater inflater, ViewGroup parent, int layoutId) { return inflater.inflate(layoutId, parent, false); }
java
public static <VH extends PeasyViewHolder> VH GetViewHolder(PeasyViewHolder vh, Class<VH> cls) { return cls.cast(vh); }
java
<T> void bindWith(final PeasyRecyclerView<T> binder, final int viewType) { this.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int position = getLayoutPosition(); position = (position <= binder.getLastItemI...
java
@SuppressWarnings("PMD.UseVarargs") public void fire(Event<?> event, Channel[] channels) { eventPipeline.add(event, channels); }
java
@SuppressWarnings("PMD.UseVarargs") /* default */ void dispatch(EventPipeline pipeline, EventBase<?> event, Channel[] channels) { HandlerList handlers = getEventHandlers(event, channels); handlers.process(pipeline, event); }
java
public static String readlineFromStdIn() throws IOException { StringBuilder ret = new StringBuilder(); int c; while ((c = System.in.read()) != '\n' && c != -1) { if (c != '\r') ret.append((char) c); } return ret.toString(); }
java
protected final SessionState getSessionState() { if (sessionTracker != null) { Session currentSession = sessionTracker.getSession(); return (currentSession != null) ? currentSession.getState() : null; } return null; }
java
protected final String getAccessToken() { if (sessionTracker != null) { Session currentSession = sessionTracker.getOpenSession(); return (currentSession != null) ? currentSession.getAccessToken() : null; } return null; }
java
protected final Date getExpirationDate() { if (sessionTracker != null) { Session currentSession = sessionTracker.getOpenSession(); return (currentSession != null) ? currentSession.getExpirationDate() : null; } return null; }
java
protected final void closeSessionAndClearTokenInformation() { if (sessionTracker != null) { Session currentSession = sessionTracker.getOpenSession(); if (currentSession != null) { currentSession.closeAndClearTokenInformation(); } } }
java
protected final List<String> getSessionPermissions() { if (sessionTracker != null) { Session currentSession = sessionTracker.getSession(); return (currentSession != null) ? currentSession.getPermissions() : null; } return null; }
java