code
stringlengths
73
34.1k
label
stringclasses
1 value
protected void fire(ActionRuntime runtime) throws IOException, ServletException { final ActionResponseReflector reflector = createResponseReflector(runtime); ready(runtime, reflector); final OptionalThing<VirtualForm> form = prepareActionForm(runtime); populateParameter(runtime, form); ...
java
protected GsonJsonEngine createGsonJsonEngine(JsonEngineResource resource) { final boolean serializeNulls = isGsonSerializeNulls(); final boolean prettyPrinting = isGsonPrettyPrinting(); final Consumer<GsonBuilder> builderSetupper = prepareGsonBuilderSetupper(serializeNulls, prettyPrinting); ...
java
public static BegunTx<?> getBegunTxOnThread() { final Stack<BegunTx<?>> stack = threadLocal.get(); return stack != null ? stack.peek() : null; }
java
public static void setBegunTxOnThread(BegunTx<?> begunTx) { if (begunTx == null) { String msg = "The argument[begunTx] must not be null."; throw new IllegalArgumentException(msg); } Stack<BegunTx<?>> stack = threadLocal.get(); if (stack == null) { stac...
java
public static boolean existsBegunTxOnThread() { final Stack<BegunTx<?>> stack = threadLocal.get(); return stack != null ? !stack.isEmpty() : false; }
java
public static void clearBegunTxOnThread() { final Stack<BegunTx<?>> stack = threadLocal.get(); if (stack != null) { stack.pop(); // remove latest if (stack.isEmpty()) { perfectlyClear(); } } }
java
public static RomanticTransaction getRomanticTransaction() { final Stack<RomanticTransaction> stack = threadLocal.get(); return stack != null ? stack.peek() : null; }
java
public static void setRomanticTransaction(RomanticTransaction romanticTransaction) { if (romanticTransaction == null) { String msg = "The argument 'romanticTransaction' should not be null."; throw new IllegalArgumentException(msg); } Stack<RomanticTransaction> stack = thr...
java
private boolean visitColumnsAndColumnFacets(VisitContext context, VisitCallback callback, boolean visitRows) { if (visitRows) { setRowIndex(-1); } if (getChildCount() > 0) { fo...
java
private boolean visitRows(VisitContext context, VisitCallback callback, boolean visitRows) { // Iterate over our UIColumn children, once per row int processed = 0; int rowIndex = 0; int rows = 0; if (visitRows) { ...
java
public boolean isForwardToHtml() { if (!isHtmlResponse()) { // e.g. exception, AJAX return false; } final HtmlResponse htmlResponse = ((HtmlResponse) actionResponse); return !htmlResponse.isRedirectTo() && isHtmlTemplateResponse(htmlResponse); }
java
public boolean handleActionPath(String requestPath, ActionFoundPathHandler handler) throws Exception { assertArgumentNotNull("requestPath", requestPath); assertArgumentNotNull("handler", handler); final MappingPathResource pathResource = customizeActionMapping(requestPath); return mappin...
java
public synchronized String encrypt(String plainText) { assertArgumentNotNull("plainText", plainText); if (encryptingCipher == null) { initialize(); } return new String(encodeHex(doEncrypt(plainText))); }
java
public UrlChain moreUrl(Object... urlParts) { final String argTitle = "urlParts"; assertArgumentNotNull(argTitle, urlParts); checkWrongUrlChainUse(argTitle, urlParts); this.urlParts = urlParts; return this; }
java
public UrlChain params(Object... paramsOnGet) { final String argTitle = "paramsOnGet"; assertArgumentNotNull(argTitle, paramsOnGet); checkWrongUrlChainUse(argTitle, paramsOnGet); this.paramsOnGet = paramsOnGet; return this; }
java
protected void assertArgumentNotNull(String argumentName, Object value) { if (argumentName == null) { String msg = "The argument name should not be null: argName=null value=" + value; throw new IllegalArgumentException(msg); } if (value == null) { String msg =...
java
@Nonnull public BigDecimal toBigDecimal() { int scale = 0; String text = getIntegerPart(); String t_fraction = getFractionalPart(); if (t_fraction != null) { text += getFractionalPart(); // XXX Wrong for anything but base 10. scale += t_fraction.le...
java
protected void handleSqlCount(ActionRuntime runtime) { final CallbackContext context = CallbackContext.getCallbackContextOnThread(); if (context == null) { return; } final SqlStringFilter filter = context.getSqlStringFilter(); if (filter == null || !(filter instanceof...
java
protected void handleTooManySqlExecution(ActionRuntime runtime, ExecutedSqlCounter sqlCounter, int sqlExecutionCountLimit) { final int totalCountOfSql = sqlCounter.getTotalCountOfSql(); final String actionDisp = buildActionDisp(runtime); logger.warn("*Too many SQL executions: {}/{} in {}", total...
java
protected void handleMailCount(ActionRuntime runtime) { if (ThreadCacheContext.exists()) { final PostedMailCounter counter = ThreadCacheContext.findMailCounter(); if (counter != null) { saveRequestedMailCount(counter); } } }
java
protected void handleRemoteApiCount(ActionRuntime runtime) { if (ThreadCacheContext.exists()) { final CalledRemoteApiCounter counter = ThreadCacheContext.findRemoteApiCounter(); if (counter != null) { saveRequestedRemoteApiCount(counter); } } }
java
public UIComponent getFacet(String name) { if (facets != null) { return (facets.get(name)); } else { return (null); } }
java
private Object saveBehaviorsState(FacesContext context){ Object state = null; if (null != behaviors && behaviors.size() >0){ boolean stateWritten = false; Object[] attachedBehaviors = new Object[behaviors.size()]; int i = 0; for (List<ClientBehavior> event...
java
@SuppressWarnings("unchecked") public static <OBJ> OBJ getObject(String key) { if (!exists()) { throwThreadCacheNotInitializedException(key); } return (OBJ) threadLocal.get().get(key); }
java
public static void setObject(String key, Object value) { if (!exists()) { throwThreadCacheNotInitializedException(key); } threadLocal.get().put(key, value); }
java
@SuppressWarnings("unchecked") public static <OBJ> OBJ removeObject(String key) { if (!exists()) { throwThreadCacheNotInitializedException(key); } return (OBJ) threadLocal.get().remove(key); }
java
public static boolean determineObject(String key) { if (!exists()) { throwThreadCacheNotInitializedException(key); } final Object obj = threadLocal.get().get(key); return obj != null && (boolean) obj; }
java
public static void clearAccessContextOnThread() { final Stack<AccessContext> stack = threadLocal.get(); if (stack != null) { stack.pop(); // remove latest if (stack.isEmpty()) { perfectlyClear(); } } }
java
public static void endAccessContext() { AccessContext.clearAccessContextOnThread(); final AccessContext accessContext = SuspendedAccessContext.getAccessContextOnThread(); if (accessContext != null) { // resume AccessContext.setAccessContextOnThread(accessContext); Suspend...
java
protected TreeMap<String, Object> prepareOrderedMap(Object form, Set<ConstraintViolation<Object>> vioSet) { final Map<String, Object> vioPropMap = new HashMap<>(vioSet.size()); for (ConstraintViolation<Object> vio : vioSet) { final String propertyPath = extractPropertyPath(vio); ...
java
public static boolean cannotBeValidatable(Object value) { // called by e.g. ResponseBeanValidator return value instanceof String // yes-yes-yes || value instanceof Number // e.g. Integer || DfTypeUtil.isAnyLocalDate(value) // e.g. LocalDate || value instanceof Bo...
java
@CheckForNull public String getPath() { Source parent = getParent(); if (parent != null) return parent.getPath(); return null; }
java
@CheckForNull public String getName() { Source parent = getParent(); if (parent != null) return parent.getName(); return null; }
java
@Nonnull public Token skipline(boolean white) throws IOException, LexerException { for (;;) { Token tok = token(); switch (tok.getType()) { case EOF: /* There ought to be a newline before EOF. * At least...
java
void notifyListenersOnStateChange() { LOGGER.debug("Notifying connection listeners about state change to {}", state); for (ConnectionListener listener : connectionListeners) { switch (state) { case CONNECTED: listener.onConnectionEstablished...
java
void establishConnection () throws IOException { synchronized (operationOnConnectionMonitor) { if (state == State.CLOSED) { throw new IOException("Attempt to establish a connection with a closed connection factory"); } else if (state == State.CONNECTED) { ...
java
public static String sliceOf( String str, int start, int end ) { return slc(str, start, end); }
java
public static String slcEnd( String str, int end ) { return FastStringUtils.noCopyStringFromChars( Chr.slcEnd( FastStringUtils.toCharArray(str), end ) ); }
java
public static char idx( String str, int index ) { int i = calculateIndex( str.length(), index ); char c = str.charAt( i ); return c; }
java
public static String idx( String str, int index, char c ) { char[] chars = str.toCharArray(); Chr.idx( chars, index, c ); return new String( chars ); }
java
public static boolean in( char c, String str ) { return Chr.in ( c, FastStringUtils.toCharArray(str) ); }
java
public static String add( String str, String str2 ) { return FastStringUtils.noCopyStringFromChars( Chr.add( FastStringUtils.toCharArray(str), FastStringUtils.toCharArray(str2) ) ); }
java
public static String add( String... strings ) { int length = 0; for ( String str : strings ) { if ( str == null ) { continue; } length += str.length(); } CharBuf builder = CharBuf.createExact( length ); for ( String str : string...
java
public static String sputl(Object... messages) { CharBuf buf = CharBuf.create(100); return sputl(buf, messages).toString(); }
java
public static String sputs(Object... messages) { CharBuf buf = CharBuf.create(80); return sputs(buf, messages).toString(); }
java
public static CharBuf sputl(CharBuf buf, Object... messages) { for (Object message : messages) { if (message == null) { buf.add("<NULL>"); } else if (message.getClass().isArray()) { buf.add(toListOrSingletonList(message).toString()); } else { ...
java
private Object parseFile(File file, String scharset) { Charset charset = scharset==null || scharset.length ()==0 ? StandardCharsets.UTF_8 : Charset.forName ( scharset ); if (file.length() > 2_000_000) { try (Reader reader = Files.newBufferedReader( Classpaths.path(file.toString()), charset ...
java
public static void puts(Object... messages) { for (Object message : messages) { IO.print(message); if (!(message instanceof Terminal.Escape)) IO.print(' '); } IO.println(); }
java
private int compareOrder( CacheEntry other ) { if ( order > other.order ) { //this order is lower so it has higher priority return 1; } else if ( order < other.order ) {//this order is higher so it has lower priority return -1; } else if ( order == other.order ) {//equa...
java
private int compareToLFU( CacheEntry other ) { int cmp = compareReadCount( other ); if ( cmp != 0 ) { return cmp; } cmp = compareTime( other ); if ( cmp != 0 ) { return cmp; } return compareOrder( other ); }
java
private int compareToLRU( CacheEntry other ) { int cmp = compareTime( other ); if ( cmp != 0 ) { return cmp; } cmp = compareOrder( other ); if ( cmp != 0 ) { return cmp; } return compareReadCount( other ); }
java
private int compareToFIFO( CacheEntry other ) { int cmp = compareOrder( other ); if ( cmp != 0 ) { return cmp; } cmp = compareTime( other ); if ( cmp != 0 ) { return cmp; } return cmp = compareReadCount( other ); }
java
@SuppressWarnings("unchecked") public <T> T readBodyAs(Class<T> type) { if (String.class.isAssignableFrom(type)) { return (T)readBodyAsString(); } else if (Number.class.isAssignableFrom(type)) { return (T)readBodyAsNumber((Class<Number>)type); } else if (Boolean...
java
public String readBodyAsString() { Charset charset = readCharset(); byte[] bodyContent = message.getBodyContent(); return new String(bodyContent, charset); }
java
@SuppressWarnings("unchecked") public <T> T readBodyAsObject(Class<T> type) { Charset charset = readCharset(); InputStream inputStream = new ByteArrayInputStream(message.getBodyContent()); InputStreamReader inputReader = new InputStreamReader(inputStream, charset); StreamSource ...
java
public <T> void addEvent(Class<T> eventType, PublisherConfiguration configuration) { publisherConfigurations.put(eventType, configuration); }
java
MessagePublisher providePublisher(PublisherReliability reliability, Class<?> eventType) { Map<Class<?>, MessagePublisher> localPublishers = publishers.get(); if (localPublishers == null) { localPublishers = new HashMap<Class<?>, MessagePublisher>(); publishers.set(localPublis...
java
static Message buildMessage(PublisherConfiguration publisherConfiguration, Object event) { Message message = new Message(publisherConfiguration.basicProperties) .exchange(publisherConfiguration.exchange) .routingKey(publisherConfiguration.routingKey); if (publisherCon...
java
public <T> Message body(T body, Charset charset) { messageWriter.writeBody(body, charset); return this; }
java
public Message contentEncoding(String charset) { basicProperties = basicProperties.builder() .contentEncoding(charset) .build(); return this; }
java
public Message contentType(String contentType) { basicProperties = basicProperties.builder() .contentType(contentType) .build(); return this; }
java
public void publish(Channel channel, DeliveryOptions deliveryOptions) throws IOException { // Assure to have a timestamp if (basicProperties.getTimestamp() == null) { basicProperties.builder().timestamp(new Date()); } boolean mandatory = deliveryOptions == DeliveryOpti...
java
@SuppressWarnings("unchecked") Object buildEvent(Message message) { Object event = eventPool.get(); if (event instanceof ContainsData) { ((ContainsData) event).setData(message.getBodyContent()); } else if (event instanceof ContainsContent) { Class<?> parameterTy...
java
@SuppressWarnings("unchecked") static Class<?> getParameterType(Object object, Class<?> expectedType) { Collection<Class<?>> extendedAndImplementedTypes = getExtendedAndImplementedTypes(object.getClass(), new LinkedList<Class<?>>()); for (Class<?> type : extendedAndImplemented...
java
static List<Class<?>> getExtendedAndImplementedTypes(Class<?> clazz, List<Class<?>> hierarchy) { hierarchy.add(clazz); Class<?> superClass = clazz.getSuperclass(); if (superClass != null) { hierarchy = getExtendedAndImplementedTypes(superClass, hierarchy); } for...
java
protected Channel provideChannel() throws IOException { if (channel == null || !channel.isOpen()) { Connection connection = connectionFactory.newConnection(); channel = connection.createChannel(); } return channel; }
java
protected void handleIoException(int attempt, IOException ioException) throws IOException { if (channel != null && channel.isOpen()) { try { channel.close(); } catch (IOException e) { LOGGER.warn("Failed to close channel after failed publish", e); ...
java
public static String getSortableFieldFromClass( Class<?> clazz ) { /** See if the fieldName is in the field listStream already. * We keep a hash-map cache. * */ String fieldName = getSortableField( clazz ); /** * Not found in cache. */ if ( fieldName...
java
public void configureFactory(Class<?> clazz) { ConnectionConfiguration connectionConfiguration = resolveConnectionConfiguration(clazz); if (connectionConfiguration == null) { return; } connectionFactory.setHost(connectionConfiguration.host()); connectionFactory....
java
private final void buildIfNeededMap() { if ( map == null ) { map = new HashMap<>( items.length ); for ( Entry<String, Value> miv : items ) { if ( miv == null ) { break; } map.put( miv.getKey(), miv.getValue() ); ...
java
public static boolean respondsTo(Object object, String method) { if (object instanceof Class) { return Reflection.respondsTo((Class) object, method); } else { return Reflection.respondsTo(object, method); } }
java
public <T> void writeBodyFromObject(T bodyAsObject, Charset charset) { @SuppressWarnings("unchecked") Class<T> clazz = (Class<T>)bodyAsObject.getClass(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Writer outputWriter = new OutputStreamWriter(outputStream, chars...
java
public static boolean toBoolean(Object obj, boolean defaultValue) { if (obj == null) { return defaultValue; } if (obj instanceof Boolean) { return ((Boolean) obj).booleanValue(); } else if (obj instanceof Number || obj.getClass().isPrimitive()) { int...
java
public void addConsumer(Consumer consumer, String queue) { addConsumer(consumer, new ConsumerConfiguration(queue), DEFAULT_AMOUNT_OF_INSTANCES); }
java
public synchronized void addConsumer(Consumer consumer, ConsumerConfiguration configuration, int instances) { for (int i=0; i < instances; i++) { this.consumerHolders.add(new ConsumerHolder(consumer, configuration)); } }
java
protected List<ConsumerHolder> filterConsumersForClass(Class<? extends Consumer> consumerClass) { List<ConsumerHolder> consumerHolderSubList = new LinkedList<ConsumerHolder>(); for (ConsumerHolder consumerHolder : consumerHolders) { if (consumerClass.isAssignableFrom(consumerHolder.getCon...
java
protected List<ConsumerHolder> filterConsumersForEnabledFlag(boolean enabled) { List<ConsumerHolder> consumerHolderSubList = new LinkedList<ConsumerHolder>(); for (ConsumerHolder consumerHolder : consumerHolders) { if (consumerHolder.isEnabled() == enabled) { consumerHold...
java
protected List<ConsumerHolder> filterConsumersForActiveFlag(boolean active) { List<ConsumerHolder> consumerHolderSubList = new LinkedList<ConsumerHolder>(); for (ConsumerHolder consumerHolder : consumerHolders) { if (consumerHolder.isActive() == active) { consumerHolderSu...
java
protected void enableConsumers(List<ConsumerHolder> consumerHolders) throws IOException { checkPreconditions(consumerHolders); try { for (ConsumerHolder consumerHolder : consumerHolders) { consumerHolder.enable(); } } catch (IOException e) { ...
java
protected void activateConsumers(List<ConsumerHolder> consumerHolders) throws IOException { synchronized (activationMonitor) { for (ConsumerHolder consumerHolder : consumerHolders) { try { consumerHolder.activate(); } catch (IOException e) { ...
java
protected void deactivateConsumers(List<ConsumerHolder> consumerHolders) { synchronized (activationMonitor) { for (ConsumerHolder consumerHolder : consumerHolders) { consumerHolder.deactivate(); } } }
java
protected void checkPreconditions(List<ConsumerHolder> consumerHolders) throws IOException { Channel channel = createChannel(); for (ConsumerHolder consumerHolder : consumerHolders) { String queue = consumerHolder.getConfiguration().getQueueName(); try { chan...
java
protected Channel createChannel() throws IOException { LOGGER.debug("Creating channel"); Connection connection = connectionFactory.newConnection(); Channel channel = connection.createChannel(); LOGGER.debug("Created channel"); return channel; }
java
public final char[] findNextChar( boolean inMiddleOfString, boolean wasEscapeChar, int match, int esc ) { try{ ensureBuffer(); //grow the buffer and read in if needed int idx = index; char[] _chars = readBuf; int length = this.length; int ch = thi...
java
public boolean addArray(float... values) { if (end + values.length >= this.values.length) { this.values = grow(this.values, (this.values.length + values.length) * 2); } System.arraycopy(values, 0, this.values, end, values.length); end += values.length; return true; ...
java
private static PropertyDescriptor getPropertyDescriptor( final Class<?> type, final String propertyName ) { Exceptions.requireNonNull(type); Exceptions.requireNonNull(propertyName); if ( !propertyName.contains( "." ) ) { return doGetPropertyDescriptor( type, propertyName ); ...
java
public boolean open() { LibMediaInfo lib = LibMediaInfo.INSTANCE; handle = lib.MediaInfo_New(); if (handle != null) { int opened = lib.MediaInfo_Open(handle, new WString(filename)); if (opened == 1) { return true; } else { lib.M...
java
public void close() { if (handle != null) { LibMediaInfo.INSTANCE.MediaInfo_Close(handle); LibMediaInfo.INSTANCE.MediaInfo_Delete(handle); } }
java
MediaInfo parse() { try { BufferedReader reader = new BufferedReader(new StringReader(data)); MediaInfo mediaInfo = new MediaInfo(); String sectionName; String line; Sections sections; Section section = null; while (parseState !...
java
private void checkChildrenCount() { if (getChildCount() != 2) Log.e(getResources().getString(R.string.tag), getResources().getString(R.string.wrong_number_children_error)); }
java
public static MediaInfo mediaInfo(String filename) { MediaInfo result; LibMediaInfo lib = LibMediaInfo.INSTANCE; Pointer handle = lib.MediaInfo_New(); if (handle != null) { try { int opened = lib.MediaInfo_Open(handle, new WString(filename)); i...
java
public Sections sections(String type) { Sections result = sectionsByType.get(type); if (result == null) { result = new Sections(); sectionsByType.put(type, result); } return result; }
java
public Section first(String type) { Section result; Sections sections = sections(type); if (sections != null) { result = sections.first(); } else { result = null; } return result; }
java
public void completeAnimationToFullHeight(int completeExpandAnimationSpeed) { HeightAnimation heightAnim = new HeightAnimation(animableView, animableView.getMeasuredHeight(), displayHeight); heightAnim.setDuration(completeExpandAnimationSpeed); heightAnim.setInterpolator(new DecelerateInterpola...
java
public void completeAnimationToInitialHeight(int completeShrinkAnimationSpeed, int initialAnimableLayoutHeight) { HeightAnimation heightAnim = new HeightAnimation(animableView, animableView.getMeasuredHeight(), initialAnimableLayoutHeight); heightAnim.setDuration(completeShrinkAnimationSpeed); ...
java
static Integer integer(String value) { Integer result; if (value != null) { value = value.trim(); Matcher matcher = INTEGER_PATTERN.matcher(value); if (matcher.matches()) { result = Integer.parseInt(matcher.group(1).replace(" ", "")); } els...
java
static BigDecimal decimal(String value) { BigDecimal result; if (value != null) { value = value.trim(); Matcher matcher = DECIMAL_PATTERN.matcher(value); if (matcher.matches()) { result = new BigDecimal(matcher.group(1)); } else { ...
java
static Duration duration(String value) { Duration result; if (value != null) { value = value.trim(); Matcher matcher = DURATION_PATTERN.matcher(value); if (matcher.matches()) { int hours = matcher.group(1) != null ? Integer.parseInt(matcher.group(1)) :...
java
private void loadWebConfigs(Environment environment, SpringConfiguration config, ApplicationContext appCtx) throws ClassNotFoundException { // Load filters. loadFilters(config.getFilters(), environment); // Load servlet listener. environment.servlets().addServletListeners(new RestContex...
java
@SuppressWarnings("unchecked") private void loadFilters(Map<String, FilterConfiguration> filters, Environment environment) throws ClassNotFoundException { if (filters != null) { for (Map.Entry<String, FilterConfiguration> filterEntry : filters.entrySet()) { FilterConfiguration fi...
java