code
stringlengths
73
34.1k
label
stringclasses
1 value
public void remove( Widget w ) { int index = indexOf( w ); if( index == -1 ) { throw new NoSuchElementException(); } remove( index ); }
java
Class<?> getSetterPropertyType( Clazz<?> clazz, String name ) { ClassInfoCache cache = retrieveCache( clazz ); Class<?> res = cache.getSetterType( name ); if( res != null ) return res; String setterName = "set" + capitalizeFirstLetter( name ); Method setter = clazz.getMethod( setterName ); if( setter != null && setter.getParameterTypes().size() == 1 ) { res = setter.getParameterTypes().get( 0 ); } else { Field field = clazz.getAllField( name ); if( field != null ) res = field.getType(); } if( res != null ) cache.setSetterType( name, res ); return res; }
java
boolean hasObjectDynamicProperty( Object object, String propertyName ) { DynamicPropertyBag bag = propertyBagAccess.getObjectDynamicPropertyBag( object ); return bag != null && bag.contains( propertyName ); }
java
public void register( Object source, String path ) { unregister(); dataBinding = Binder.bind( source, path ).mode( Mode.OneWay ).to( adapter ).activate(); }
java
public static BindingCreation bind( Object source, String propertyPath ) { return createBinder( new CompositePropertyAdapter( source, propertyPath ) ); }
java
public static DataBinding map( Object source, Object destination ) { return bindObject( source ).mapTo( destination ); }
java
public HttpResponse postTopicMessage(String topicName, String jsonPayload, Map<String, String> headers) throws RestClientException { return postMessage(Type.TOPIC, topicName, jsonPayload, headers); }
java
public HttpResponse postQueueMessage(String queueName, String jsonPayload, Map<String, String> headers) throws RestClientException { return postMessage(Type.QUEUE, queueName, jsonPayload, headers); }
java
public void run( AcceptsOneWidget container ) { /** Add our widgets in the container */ container.setWidget( UiBuilder.addIn( new VerticalPanel(), personListWidget, personneForm, categoryForm, nextButton ) ); /* * Bind things together */ // selectedPerson to person form Bind( personListWidget, "selectedPersonne" ).Mode( Mode.OneWay ).Log("PERSONNEFORM").To( personneForm, "personne" ); // maps the selected person's category to the category form Bind( personListWidget, "selectedPersonne.category" ).Mode( Mode.OneWay ).MapTo( categoryForm ); // selected person's description to Window's title Bind( personListWidget, "selectedPersonne.description" ).Mode( Mode.OneWay ).To( new WriteOnlyPropertyAdapter() { @Override public void setValue( Object object ) { Window.setTitle( (String) object ); } } ); /* * Initialize person list widget */ personListWidget.setPersonList( famille ); personListWidget.setSelectedPersonne( famille.get( 0 ) ); nextButton.addClickHandler( nextButtonClickHandler ); }
java
private void _RemoveValidator( Row item, int column ) { // already clean ? if( m_currentEditedItem == null && m_currentEditedColumn < 0 ) return; // touch the table if( m_callback != null ) m_callback.onTouchCellContent( item, column ); if( m_currentEditor != null ) m_currentEditor.removeFromParent(); m_currentEditor = null; m_currentEditedItem = null; m_currentEditedColumn = -1; }
java
public static void processFile( String input, String mappingPath, String outputFile, boolean doPrune, Log log ) throws IOException { Set<String> usedClassNames = new HashSet<>(); input = replaceClassNames( input, mappingPath, usedClassNames, log ); log.debug( usedClassNames.size() + " used css classes in the mapping file" ); log.debug( "used css classes : " + usedClassNames ); CssRewriter cssRewriter = new CssRewriter( usedClassNames, doPrune, log ); input = cssRewriter.process( input ); input += "\r\n// generated by HexaCss maven plugin, see http://www.lteconsulting.fr/hexacss"; writeFile( outputFile, input, log ); }
java
public void updateGroup(long groupId, String name, boolean isPrivate) { LinkedMultiValueMap<String, String> params = new LinkedMultiValueMap<String, String>(); params.set("name",name); params.set("private", String.valueOf(isPrivate)); restTemplate.put(buildUri("groups/"+groupId), params); }
java
static Map<String, String> getVersionAttributes(URL url) throws IOException { Map<String, String> ret = new LinkedHashMap<>(); try (InputStream inputStream = url.openStream()) { Manifest manifest = new Manifest(inputStream); Attributes attributes = manifest.getMainAttributes(); for (String key : VERSION_ATTRIBUTES) { final String value = attributes.getValue(key); ret.put(key, value == null ? UNKNOWN_VALUE : value); } } return ret; }
java
@Override protected View createOverlayView() { LinearLayout ll = new LinearLayout(getContext()); ll.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT,FrameLayout.LayoutParams.MATCH_PARENT)); ll.setGravity(Gravity.CENTER); View progressBar = createProgressBar(); ll.addView(progressBar); return ll; }
java
protected String getNestName() { if (nestName == null || nestName.equals(NestSubsystemExtension.NEST_NAME_AUTOGENERATE)) { return this.envServiceValue.getValue().getNodeName(); } else { return nestName; } }
java
@RobotKeyword("Connect to MQTT Broker") @ArgumentNames({ "broker", "clientId" }) public void connectToMQTTBroker(String broker, String clientId) throws MqttException { client = new MqttClient(broker, clientId); System.out.println("*INFO:" + System.currentTimeMillis() + "* connecting to broker"); client.connect(); System.out.println("*INFO:" + System.currentTimeMillis() + "* connected"); }
java
@RobotKeywordOverload @ArgumentNames({ "topic", "message" }) public void publishToMQTTSynchronously(String topic, Object message) throws MqttException { publishToMQTTSynchronously(topic, message, 0, false); }
java
@RobotKeyword("Publish to MQTT Synchronously") @ArgumentNames({ "topic", "message", "qos=0", "retained=false" }) public void publishToMQTTSynchronously(String topic, Object message, int qos, boolean retained) throws MqttException { MqttMessage msg; if (message instanceof String) { msg = new MqttMessage(message.toString().getBytes()); } else { msg = new MqttMessage((byte[]) message); } msg.setQos(qos); msg.setRetained(retained); System.out.println("*INFO:" + System.currentTimeMillis() + "* publishing message"); client.publish(topic, msg); System.out.println("*INFO:" + System.currentTimeMillis() + "* published"); }
java
@RobotKeyword("Disconnect from MQTT Broker") public void disconnectFromMQTTBroker() { if (client != null) { try { client.disconnect(); } catch (MqttException e) { throw new RuntimeException(e.getLocalizedMessage()); } } }
java
@RobotKeyword("Subscribe to MQTT Broker and validate that it received a specific message") @ArgumentNames({ "broker", "clientId", "topic", "expectedPayload", "timeout" }) public void subscribeToMQTTAndValidate(String broker, String clientId, String topic, String expectedPayload, long timeout) { MqttClient client = null; try { MqttClientPersistence persistence = new MemoryPersistence(); client = new MqttClient(broker, clientId, persistence); // set clean session to false so the state is remembered across // sessions MqttConnectOptions connOpts = new MqttConnectOptions(); connOpts.setCleanSession(false); // set callback before connecting so prior messages are delivered as // soon as we connect MQTTResponseHandler handler = new MQTTResponseHandler(); client.setCallback(handler); System.out.println("*INFO:" + System.currentTimeMillis() + "* Connecting to broker: " + broker); client.connect(connOpts); System.out.println("*INFO:" + System.currentTimeMillis() + "* Subscribing to topic: " + topic); client.subscribe(topic); System.out.println("*INFO:" + System.currentTimeMillis() + "* Subscribed to topic: " + topic); // now loop until either we receive the message in the topic or // timeout System.out.println("*INFO:" + System.currentTimeMillis() + "* Waiting for message to arrive"); boolean validated = false; byte[] payload; MqttMessage message; long endTime = System.currentTimeMillis() + timeout; while (true) { /* * If expected payload is empty, all we need to validate is * receiving the message in the topic. If expected payload is * not empty, then we need to validate that it is contained in * the actual payload */ message = handler.getNextMessage(timeout); if (message != null) { // received a message in the topic payload = message.getPayload(); String payloadStr = new String(payload); if (expectedPayload.isEmpty() || (payloadStr.matches(expectedPayload))) { validated = true; break; } } // update timeout to remaining time and check if ((timeout = endTime - System.currentTimeMillis()) <= 0) { System.out.println("*DEBUG:" + System.currentTimeMillis() + "* timeout: " + timeout); break; } } if (!validated) { throw new RuntimeException( "The expected payload didn't arrive in the topic"); } } catch (MqttException e) { throw new RuntimeException(e.getLocalizedMessage()); } finally { try { client.disconnect(); } catch (MqttException e) { // empty } } }
java
private String _getUniqueKey() { StringBuilder b = new StringBuilder(); b.append( service ); b.append( "#" ); b.append( method ); if( params != null ) { b.append( "#" ); b.append( params.toString() ); } return b.toString(); }
java
public void initialize(@Observes @Initialized(ApplicationScoped.class) Object ignore) { log.debugf("Initializing [%s]", this.getClass().getName()); try { feedSessionListenerProducer = new BiFunction<String, Session, WsSessionListener>() { @Override public WsSessionListener apply(String key, Session session) { // In the future, if we need other queues/topics that need to be listened to, we add them here. final Endpoint endpoint = Constants.FEED_COMMAND_QUEUE; BasicMessageListener<BasicMessage> busEndpointListener = new FeedBusEndpointListener(session, key, endpoint); return new BusWsSessionListener(Constants.HEADER_FEEDID, key, endpoint, busEndpointListener); } }; wsEndpoints.getFeedSessions().addWsSessionListenerProducer(feedSessionListenerProducer); uiClientSessionListenerProducer = new BiFunction<String, Session, WsSessionListener>() { @Override public WsSessionListener apply(String key, Session session) { // In the future, if we need other queues/topics that need to be listened to, we add them here. final Endpoint endpoint = Constants.UI_COMMAND_QUEUE; BasicMessageListener<BasicMessage> busEndpointListener = new UiClientBusEndpointListener( commandContextFactory, busCommands, endpoint); return new BusWsSessionListener(Constants.HEADER_UICLIENTID, key, endpoint, busEndpointListener); } }; wsEndpoints.getUiClientSessions().addWsSessionListenerProducer(uiClientSessionListenerProducer); } catch (Exception e) { log.errorCouldNotInitialize(e, this.getClass().getName()); } }
java
void modifyData(final TrieNode<V> node, final V value) { node.value = value; ++modCount; ++size; }
java
private void addNode(final TrieNode<V> node, final CharSequence key, final int beginIndex, final TrieNode<V> newNode) { final int lastKeyIndex = key.length() - 1; TrieNode<V> currentNode = node; int i = beginIndex; for (; i < lastKeyIndex; i++) { final TrieNode<V> nextNode = new TrieNode<V>(false); currentNode.children.put(key.charAt(i), nextNode); currentNode = nextNode; } currentNode.children.put(key.charAt(i), newNode); }
java
V removeMapping(final Object o) { if (!(o instanceof Map.Entry)) { throw new IllegalArgumentException(); } @SuppressWarnings("unchecked") final Entry<? extends CharSequence, V> e = (Map.Entry<? extends CharSequence, V>) o; final CharSequence key = keyCheck(e.getKey()); final V value = e.getValue(); final TrieNode<V> currentNode = findPreviousNode(key); if (currentNode == null) { /* Node not found for the given key */ return null; } final TrieNode<V> node = currentNode.children.get(key.charAt(key .length() - 1)); if (node == null || !node.inUse) { /* Node not found for the given key or is not in use */ return null; } final V removed = node.value; if (removed != value && (removed == null || !removed.equals(value))) { /* * Value in the map differs from the value given in the entry so do * nothing and return null. */ return null; } node.unset(); --size; ++modCount; if (node.children.isEmpty()) { /* Since there are no children left, we can compact the trie */ compact(key); } return removed; }
java
private void compact(final CharSequence key) { final int keyLength = key.length(); TrieNode<V> currentNode = getRoot(); TrieNode<V> lastInUseNode = currentNode; int lastInUseIndex = 0; for (int i = 0; i < keyLength && currentNode != null; i++) { if (currentNode.inUse) { lastInUseNode = currentNode; lastInUseIndex = i; } currentNode = currentNode.children.get(key.charAt(i)); } currentNode = lastInUseNode; for (int i = lastInUseIndex; i < keyLength; i++) { currentNode = currentNode.children.remove(key.charAt(i)).unset(); } }
java
public static String getTypeQualifiedName(TypeMirror type) throws CodeGenerationIncompleteException { if(type.toString().equals("<any>")) { throw new CodeGenerationIncompleteException("Type reported as <any> is likely a not-yet " + "generated parameterized type."); } switch( type.getKind() ) { case ARRAY: return getTypeQualifiedName( ((ArrayType) type).getComponentType() ) + "[]"; case BOOLEAN: return "boolean"; case BYTE: return "byte"; case CHAR: return "char"; case DOUBLE: return "double"; case FLOAT: return "float"; case INT: return "int"; case LONG: return "long"; case SHORT: return "short"; case DECLARED: StringBuilder b = new StringBuilder(); b.append( ((TypeElement) ((DeclaredType) type).asElement()).getQualifiedName().toString() ); if( !((DeclaredType) type).getTypeArguments().isEmpty() ) { b.append( "<" ); boolean addComa = false; for( TypeMirror pType : ((DeclaredType) type).getTypeArguments() ) { if( addComa ) b.append( ", " ); else addComa = true; b.append( getTypeQualifiedName( pType ) ); } b.append( ">" ); } return b.toString(); default: return type.toString(); } }
java
public boolean IsInside( String pDate ) { if( periods == null ) { if( days == null ) // security added to avoid null exception return false; if( days.getDay( CalendarFunctions.date_get_day( pDate ) ).get() > 0 ) return true; return false; } for( int i = 0; i < periods.size(); i++ ) { Period period = periods.get( i ); if( period.getFrom().compareTo( pDate ) > 0 ) return false; if( (period.getFrom().compareTo( pDate ) <= 0) && (period.getTo().compareTo( pDate ) >= 0) ) return true; } return false; }
java
public boolean IsContained( String pFrom, String pTo ) { if( periods == null ) { // echo "IsContained() TO BE IMPLEMENTED FLLKJ :: {{ } ''<br/>"; throw new RuntimeException( "Error Periods is Null" ); } for( int i = 0; i < periods.size(); i++ ) { Period period = periods.get( i ); if( period.getFrom().compareTo( pFrom ) > 0 ) return false; if( (pFrom.compareTo( period.getFrom() ) >= 0) && (pTo.compareTo( period.getTo() ) <= 0) ) return true; } return false; }
java
public void Resolve( String pFrom, String pTo ) { if( periods != null ) { // call on an already resolved CalendarPeriod // echo // "LJLJKZHL KJH ELF B.EB EKJGF EFJBH EKLFJHL JGH <{{ : ' } <br/>"; throw new RuntimeException( "Error call on an already resolved CalendarPeriod" ); } // echo "Resolving from $from to $to " . implode( ".", $this->days ) . // "<br/>"; // if all days are selected, make a whole period // build the micro periods int nb = 0; for( int i = 0; i < 7; i++ ) nb += days.getDay( i ).get(); if( nb == 7 ) { periods = new ArrayList<Period>(); periods.add( new Period( pFrom, pTo ) ); return; } else if( nb == 0 ) { periods = new ArrayList<Period>(); return; } // echo "Continuing<br/>"; int fromDay = CalendarFunctions.date_get_day( pFrom ); // we have at least one gap Groups groups = new Groups(); Group curGroup = null; for( int i = fromDay; i < fromDay + 7; i++ ) { if( days.getDay( i % 7 ).get() > 0 ) { if( curGroup == null ) // no group created yet curGroup = new Group( i - fromDay, i - fromDay ); else if( curGroup.getTo() == i - fromDay - 1 ) // day jointed to // current group curGroup.setTo( i - fromDay ); else // day disjointed from current group { groups.add( curGroup ); curGroup = new Group( i - fromDay, i - fromDay ); } } } if( curGroup != null ) groups.add( curGroup ); // Dump( $groups ); // now generate the periods // String msg = "Starts on " + pFrom + ", which day is a " + fromDay + // "<br/>"; // for( int i = 0; i < groups.size(); i++ ) // { // Group group = groups.get( i ); // msg += "Group : " + group.implode( " to " ) + "<br/>"; // } // echo "From day : $from : $fromDay <br/>"; String firstOccurence = pFrom; // echo "First occurence : $firstOccurence<br/>"; days = null; periods = new ArrayList<Period>(); while( firstOccurence.compareTo( pTo ) <= 0 ) { // msg += "Occurence " + firstOccurence + "<br/>"; // day of $firstOccurence is always $fromDay // foreach( $groups as $group ) for( int i = 0; i < groups.size(); i++ ) { Group group = groups.get( i ); String mpFrom = CalendarFunctions.date_add_day( firstOccurence, group.getFrom() ); if( mpFrom.compareTo( pTo ) <= 0 ) { String mpTo = CalendarFunctions.date_add_day( firstOccurence, group.getTo() ); if( mpTo.compareTo( pTo ) > 0 ) mpTo = pTo; // msg += "Adding " + mpFrom + ", " + mpTo + "<br/>"; periods.add( new Period( mpFrom, mpTo ) ); } } firstOccurence = CalendarFunctions.date_add_day( firstOccurence, 7 ); } // ServerState::inst()->AddMessage( $msg ); }
java
private List<Period> _Intersect( List<Period> periods1, List<Period> periods2 ) { List<Period> result = new ArrayList<Period>(); int count1 = periods1.size(); int count2 = periods2.size(); int i = 0; int j = 0; while( i < count1 && j < count2 ) { // one of the periods begins after the end of the other if( periods1.get( i ).getFrom().compareTo( periods2.get( j ).getTo() ) > 0 ) { // period 1 begins after period 2 finishes => period2 is // eliminated ! j++; } else if( periods2.get( j ).getFrom().compareTo( periods1.get( i ).getTo() ) > 0 ) { // period 2 begins after end of period 1 => period 1 is eliminated // ! i++; } // after that test, we can assume there is a non-void intersection else { // result[] = array( max($periods1[$i][0],$periods2[$j][0]), // min($periods1[$i][1],$periods2[$j][1]) ); result.add( new Period( CalendarFunctions.max_date( periods1.get( i ).getFrom(), periods2.get( j ).getFrom() ), CalendarFunctions.min_date( periods1.get( i ).getTo(), periods2.get( j ).getTo() ) ) ); if( periods1.get( i ).getTo().compareTo( periods2.get( j ).getTo() ) > 0 ) j++; else i++; } } return result; }
java
protected Integer compareNullObjects(Object object1, Object object2) { if ((object1 == null) && (object2 == null)) { return 0; } if (object1 == null) { return 1; } if (object2 == null) { return -1; } return null; }
java
public PathBuilder append( String cmd, double... coords ) { s.append( cmd ).append( " " ); for( double a : coords ) { s.append( a ).append( " " ); } return this; }
java
@AroundInvoke public Object handle(InvocationContext ic) throws Exception { Method m = ic.getMethod(); Object targetObject = ic.getTarget(); Class<?> targetClass = targetObject == null ? m.getDeclaringClass() : targetObject.getClass(); CatchHandler exceptionHandlerAnnotation = AnnotationUtils .findAnnotation(m, targetClass, CatchHandler.class); Exception unexpectedException = null; if (exceptionHandlerAnnotation == null) { throw new IllegalStateException( "The interceptor annotation can not be determined!"); } CatchHandling[] exceptionHandlingAnnotations = exceptionHandlerAnnotation .value(); Class<? extends Throwable>[] unwrap = exceptionHandlerAnnotation .unwrap(); try { return ic.proceed(); } catch (Exception ex) { if (!contains(unwrap, InvocationTargetException.class)) { unwrap = Arrays.copyOf(unwrap, unwrap.length + 1); unwrap[unwrap.length - 1] = InvocationTargetException.class; } // Unwrap Exception if ex is instanceof InvocationTargetException Throwable t = ExceptionUtils.unwrap(ex, InvocationTargetException.class); boolean exceptionHandled = false; boolean cleanupInvoked = false; if (exceptionHandlingAnnotations.length > 0) { for (CatchHandling handling : exceptionHandlingAnnotations) { if (handling.exception().isInstance(t)) { try { handleThrowable(t); exceptionHandled = true; } catch (Exception unexpected) { unexpectedException = unexpected; } // Only invoke cleanup declared at handling level if (!handling.cleanup().equals(Object.class)) { cleanupInvoked = invokeCleanups(targetClass, targetObject, handling.cleanup(), t); } break; } } } // Handle the default exception type if no handlings are // declared or the handling did not handle the exception if (!exceptionHandled) { if (exceptionHandlerAnnotation.exception().isInstance(t)) { try { handleThrowable(t); exceptionHandled = true; } catch (Exception unexpected) { unexpectedException = unexpected; } if (!exceptionHandlerAnnotation.cleanup().equals( Object.class) && !cleanupInvoked) { if (!cleanupInvoked) { invokeCleanups(targetClass, targetObject, exceptionHandlerAnnotation.cleanup(), t); } } } } if (!exceptionHandled) { if (t instanceof Exception) { unexpectedException = (Exception) t; } else { unexpectedException = new Exception(t); } } } if (unexpectedException != null) { throw unexpectedException; } return null; }
java
private boolean invokeCleanups(Class<?> clazz, Object target, Class<?> cleanupClazz, Throwable exception) throws Exception { boolean invoked = false; if (!cleanupClazz.equals(Object.class)) { // Christian Beikov 29.07.2013: Traverse whole hierarchy // instead of retrieving the annotation directly from // the class object. List<Method> methods = ReflectionUtils.getMethods(target.getClass(), Cleanup.class); Method m = null; for (Method candidate : methods) { Cleanup c = AnnotationUtils.findAnnotation(candidate, Cleanup.class); if (cleanupClazz.equals(c.value())) { m = candidate; break; } } if (m != null) { final Class<?>[] parameterTypes = m.getParameterTypes(); if (parameterTypes.length == 1) { if (ReflectionUtils.isSubtype(exception.getClass(), parameterTypes[0])) { m.invoke(target, exception); invoked = true; } else { throw new IllegalArgumentException("Cleanup method with name " + cleanupClazz.getName() + " requires a parameter that is not a subtype of the exception class " + exception.getClass().getName()); } } else { m.invoke(target); invoked = true; } } } return invoked; }
java
public ProducerConnectionContext createProducerConnectionContext(Endpoint endpoint) throws JMSException { ProducerConnectionContext context = new ProducerConnectionContext(); createOrReuseConnection(context, true); createSession(context); createDestination(context, endpoint); createProducer(context); return context; }
java
protected void cacheConnection(Connection connection, boolean closeExistingConnection) { if (this.connection != null && closeExistingConnection) { try { // make sure it is closed to free up any resources it was using this.connection.close(); } catch (JMSException e) { msglog.errorCannotCloseConnectionMemoryMightLeak(e); } } this.connection = connection; }
java
protected void createConnection(ConnectionContext context) throws JMSException { if (context == null) { throw new IllegalStateException("The context is null"); } ConnectionFactory factory = getConnectionFactory(); Connection conn = factory.createConnection(); context.setConnection(conn); }
java
protected void createSession(ConnectionContext context) throws JMSException { if (context == null) { throw new IllegalStateException("The context is null"); } Connection conn = context.getConnection(); if (conn == null) { throw new IllegalStateException("The context had a null connection"); } Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE); context.setSession(session); }
java
protected void createDestination(ConnectionContext context, Endpoint endpoint) throws JMSException { if (endpoint == null) { throw new IllegalStateException("Endpoint is null"); } if (context == null) { throw new IllegalStateException("The context is null"); } Session session = context.getSession(); if (session == null) { throw new IllegalStateException("The context had a null session"); } Destination dest; if (endpoint.getType() == Endpoint.Type.QUEUE) { if (endpoint.isTemporary()) { dest = session.createTemporaryQueue(); } else { dest = session.createQueue(getDestinationName(endpoint)); } } else { if (endpoint.isTemporary()) { dest = session.createTemporaryTopic(); } else { dest = session.createTopic(getDestinationName(endpoint)); } } context.setDestination(dest); }
java
protected void createProducer(ProducerConnectionContext context) throws JMSException { if (context == null) { throw new IllegalStateException("The context is null"); } Session session = context.getSession(); if (session == null) { throw new IllegalStateException("The context had a null session"); } Destination dest = context.getDestination(); if (dest == null) { throw new IllegalStateException("The context had a null destination"); } MessageProducer producer = session.createProducer(dest); context.setMessageProducer(producer); }
java
protected void createConsumer(ConsumerConnectionContext context, String messageSelector) throws JMSException { if (context == null) { throw new IllegalStateException("The context is null"); } Session session = context.getSession(); if (session == null) { throw new IllegalStateException("The context had a null session"); } Destination dest = context.getDestination(); if (dest == null) { throw new IllegalStateException("The context had a null destination"); } MessageConsumer consumer = session.createConsumer(dest, messageSelector); context.setMessageConsumer(consumer); }
java
public static Bindings defaultBindings() { return noHashMapBindings() .set( ClassLoader.class, Thread.currentThread().getContextClassLoader() ) .set( ConfigParseOptions.class, ConfigParseOptions.defaults() ) .set( ConfigResolveOptions.class, ConfigResolveOptions.defaults() ) .set( Config.class, emptyConfig() ); }
java
public void Init( CalendarPeriod period, T value ) { for( int i = 0; i < period.getPeriods().size(); i++ ) { Period p = period.getPeriods().get( i ); periods.add( new PeriodAssociative<T>( p.getFrom(), p.getTo(), value ) ); } }
java
public Boolean Add( CalendarPeriodAssociative<T> period, AddFunction<T> addFunction ) { // combine les deux tableaux dans ordre croissant List<PeriodAssociative<T>> combined = _Combine( periods, period.getPeriods() ); // merge overlapping periods List<PeriodAssociative<T>> result = _Merge( combined, addFunction ); if( result == null ) return null; // we should stop the MakeUpCalendarAssociative process periods = result; // to say we can continue... return true; }
java
public CalendarPeriod GetCalendarPeriod() { CalendarPeriod res = new CalendarPeriod(); List<Period> periods = new ArrayList<Period>(); for( int i = 0; i < this.periods.size(); i++ ) { PeriodAssociative<T> p = this.periods.get( i ); periods.add( new Period( p.getFrom(), p.getTo() ) ); } // use merge to merge jointed periods... res.setPeriods( res._Merge( periods ) ); return res; }
java
private boolean _readDate() { int endIndex = pos + 10; if( endIndex <= len ) { _date = text.substring( pos, endIndex ); pos += 10; return true; } pos = len; return false; }
java
public void emphasizePoint( int index ) { if( dots == null || dots.length < (index - 1) ) return; // impossible ! // if no change, nothing to do if( emphasizedPoint == index ) return; // de-emphasize the current emphasized point if( emphasizedPoint >= 0 ) { dots[emphasizedPoint].attr( "r", dotNormalSize ); emphasizedPoint = -1; } if( index >= 0 ) { dots[index].attr( "r", dotBigSize ); emphasizedPoint = index; } }
java
public void moveLastChild( Row newParent ) { if( this == newParent ) return; // remove from its current position Row parentItem = m_parent; if( parentItem == null ) parentItem = this.treeTable.m_rootItem; parentItem.getChilds().remove( this ); // DOM.removeChild( m_body, m_tr ); if( newParent == null ) newParent = this.treeTable.m_rootItem; // insert at the end of the current parent // DOM add Row lastLeaf = newParent.getLastLeaf(); Element trToInsertAfter = lastLeaf.m_tr; if( trToInsertAfter != null ) { int after = DOM.getChildIndex( this.treeTable.m_body, trToInsertAfter ); int before = after + 1; DOM.insertChild( this.treeTable.m_body, m_tr, before ); } else { DOM.appendChild( this.treeTable.m_body, m_tr ); } parentItem.getChilds().add( this ); // take care of the left padding Element firstTd = DOM.getChild( m_tr, 0 ); firstTd.getStyle().setPaddingLeft( getLevel() * this.treeTable.treePadding, Unit.PX ); }
java
public void moveBefore( Row item ) { if( this == item ) return; Element lastTrToMove = getLastLeafTR(); Element firstChildRow = DOM.getNextSibling( m_tr ); // remove from its current position Row parentItem = m_parent; if( parentItem == null ) parentItem = this.treeTable.m_rootItem; parentItem.getChilds().remove( this ); // insert at the selected position if( item == null ) { // insert at the end of the current parent // DOM add Row lastLeaf = parentItem.getLastLeaf(); Element trToInsertAfter = lastLeaf.m_tr; if( trToInsertAfter != null ) { int after = DOM.getChildIndex( this.treeTable.m_body, trToInsertAfter ); int before = after + 1; DOM.insertChild( this.treeTable.m_body, m_tr, before ); } else { DOM.appendChild( this.treeTable.m_body, m_tr ); } parentItem.getChilds().add( this ); } else { Row newParentItem = item.m_parent; if( newParentItem == null ) newParentItem = this.treeTable.m_rootItem; int itemPos = item.m_parent.getChilds().indexOf( item ); newParentItem.getChilds().add( itemPos, this ); DOM.insertBefore( this.treeTable.m_body, m_tr, item.m_tr ); } // take care of the left padding Element firstTd = DOM.getChild( m_tr, 0 ); firstTd.getStyle().setPaddingLeft( getLevel() * this.treeTable.treePadding, Unit.PX ); // update child rows Element nextTR = DOM.getNextSibling( m_tr ); if( firstChildRow != null && lastTrToMove != null && hasChilds() ) { while( true ) { Element next = DOM.getNextSibling( firstChildRow ); DOM.insertBefore( this.treeTable.m_body, firstChildRow, nextTR ); if( firstChildRow == lastTrToMove ) break; firstChildRow = next; } } }
java
void removeHandler( Object handlerRegistration ) { // Through object's interface implementation if( handlerRegistration instanceof DirectHandlerInfo ) { DirectHandlerInfo info = (DirectHandlerInfo) handlerRegistration; info.source.removePropertyChangedHandler( info.registrationObject ); return; } if( ! ( handlerRegistration instanceof HandlerInfo ) ) return; HandlerInfo info = (HandlerInfo) handlerRegistration; HashMap<String, ArrayList<PropertyChangedHandler>> handlersMap = PlatformSpecificProvider.get().getObjectMetadata( info.source ); if( handlersMap == null ) return; ArrayList<PropertyChangedHandler> handlerList = handlersMap.get( info.propertyName ); if( handlerList == null ) return; handlerList.remove( info.handler ); if( handlerList.isEmpty() ) handlersMap.remove( info.propertyName ); if( handlersMap.isEmpty() ) PlatformSpecificProvider.get().setObjectMetadata( info.source, null ); stats.statsRemovedRegistration( info ); info.handler = null; info.propertyName = null; info.source = null; }
java
public static void filterRequest(ContainerRequestContext requestContext, Predicate<String> predicate) { //NOT a CORS request String requestOrigin = requestContext.getHeaderString(Headers.ORIGIN); if (requestOrigin == null) { return; } if (!predicate.test(requestOrigin)) { requestContext.abortWith(Response.status(Response.Status.BAD_REQUEST).build()); return; } //It is a CORS pre-flight request, there is no route for it, just return 200 if (requestContext.getMethod().equalsIgnoreCase(HttpMethod.OPTIONS)) { requestContext.abortWith(Response.status(Response.Status.OK).build()); } }
java
public static void filterResponse(ContainerRequestContext requestContext, ContainerResponseContext responseContext, String extraAccesControlAllowHeaders) { String requestOrigin = requestContext.getHeaderString(Headers.ORIGIN); if (requestOrigin == null) { return; } // CORS validation already checked on request filter, see AbstractCorsRequestFilter MultivaluedMap<String, Object> responseHeaders = responseContext.getHeaders(); responseHeaders.add(Headers.ACCESS_CONTROL_ALLOW_ORIGIN, requestOrigin); responseHeaders.add(Headers.ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); responseHeaders.add(Headers.ACCESS_CONTROL_ALLOW_METHODS, Headers.DEFAULT_CORS_ACCESS_CONTROL_ALLOW_METHODS); responseHeaders.add(Headers.ACCESS_CONTROL_MAX_AGE, 72 * 60 * 60); if (extraAccesControlAllowHeaders != null) { responseHeaders.add(Headers.ACCESS_CONTROL_ALLOW_HEADERS, Headers.DEFAULT_CORS_ACCESS_CONTROL_ALLOW_HEADERS + "," + extraAccesControlAllowHeaders.trim()); } else { responseHeaders.add(Headers.ACCESS_CONTROL_ALLOW_HEADERS, Headers.DEFAULT_CORS_ACCESS_CONTROL_ALLOW_HEADERS); } }
java
public static TableCellElement getCell( Element root, int column, int row ) { TableSectionElement tbody = getTBodyElement( root ); TableRowElement tr = tbody.getChild( row ).cast(); TableCellElement td = tr.getChild( column ).cast(); return td; }
java
public static Pair<Integer, Integer> getParentCellForElement( Element root, Element element ) { Element tbody = getTBodyElement( root ); // Is the element in our table ? and what's the path from the table to it ? ArrayList<Element> path = TemplateUtils.isDescendant( tbody, element ); if( path == null ) return null; // we know that path[0] is tbody and that path[1] is a tr template int row = DOM.getChildIndex( path.get( 0 ), path.get( 1 ) ); int col = DOM.getChildIndex( path.get( 1 ), path.get( 2 ) ); return new Pair<Integer, Integer>( col, row ); }
java
public static void setDragData( Object source, Object data ) { DragUtils.source = source; DragUtils.data = data; }
java
public static ConfigFactory webappConfigFactory(ServletContext servletContext) { checkNotNull(servletContext); return webappConfigFactory() .bind(ServletContextPath.class) .toInstance(ServletContextPath.fromServletContext(servletContext)); }
java
@Override public void setWidget( Widget w ) { // Validate if( w == widget ) return; // Detach new child. if( w != null ) w.removeFromParent(); // Remove old child. if( widget != null ) remove( widget ); // Logical attach. widget = w; if( w != null ) { // Physical attach. DOM.appendChild( containerElement, widget.getElement() ); adopt( w ); } }
java
private String getSentenceFromTokens(final String[] tokens) { final StringBuilder sb = new StringBuilder(); for (final String token : tokens) { sb.append(token).append(" "); } final String sentence = sb.toString(); return sentence; }
java
private String addHeadWordsToTreebank(final List<String> inputTrees) { final StringBuffer parsedDoc = new StringBuffer(); for (final String parseSent : inputTrees) { final Parse parsedSentence = Parse.parseParse(parseSent); this.headFinder.printHeads(parsedSentence); parsedSentence.show(parsedDoc); parsedDoc.append("\n"); } return parsedDoc.toString(); }
java
public void terminate() { log( "term" ); fActivated = false; converter = null; source.removePropertyChangedHandler( sourceHandler ); source = null; sourceHandler = null; destination.removePropertyChangedHandler( destinationHandler ); destination = null; destinationHandler = null; }
java
public static void tryToShowPrompt(Context context, OnCompleteListener onCompleteListener) { tryToShowPrompt(context, null, null, onCompleteListener); }
java
public static void resetIfAppVersionChanged(Context context) { SharedPreferences prefs = getSharedPreferences(context); int appVersionCode = Integer.MIN_VALUE; final int previousAppVersionCode = prefs.getInt(PREF_KEY_APP_VERSION_CODE, Integer.MIN_VALUE); try { appVersionCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode; } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, "Occurred PackageManager.NameNotFoundException", e); } if (previousAppVersionCode != appVersionCode) { SharedPreferences.Editor prefsEditor = prefs.edit(); prefsEditor.putLong(PREF_KEY_APP_LAUNCH_COUNT, 0); prefsEditor.putLong(PREF_KEY_APP_THIS_VERSION_CODE_LAUNCH_COUNT, 0); prefsEditor.putLong(PREF_KEY_APP_FIRST_LAUNCHED_DATE, 0); prefsEditor.putInt(PREF_KEY_APP_VERSION_CODE, Integer.MIN_VALUE); prefsEditor.putLong(PREF_KEY_RATE_CLICK_DATE, 0); prefsEditor.putLong(PREF_KEY_REMINDER_CLICK_DATE, 0); prefsEditor.putBoolean(PREF_KEY_DO_NOT_SHOW_AGAIN, false); prefsEditor.commit(); } }
java
public static Class<?> getObjectClassOfPrimitve(Class<?> primitive) { Class<?> objectClass = PRIMITIVE_TO_WRAPPER.get(primitive); if (objectClass != null) { return objectClass; } return primitive; }
java
public static int getTypeVariablePosition(GenericDeclaration genericDeclartion, TypeVariable<?> typeVariable) { int position = -1; TypeVariable<?>[] typeVariableDeclarationParameters = genericDeclartion .getTypeParameters(); // Try to find the position of the type variable in the class for (int i = 0; i < typeVariableDeclarationParameters.length; i++) { if (typeVariableDeclarationParameters[i].equals(typeVariable)) { position = i; break; } } return position; }
java
public static Field[] getMatchingFields(Class<?> clazz, final int modifiers) { final Set<Field> fields = new TreeSet<Field>( FIELD_NAME_AND_DECLARING_CLASS_COMPARATOR); traverseHierarchy(clazz, new TraverseTask<Field>() { @Override public Field run(Class<?> clazz) { Field[] fieldArray = clazz.getDeclaredFields(); for (int i = 0; i < fieldArray.length; i++) { if ((modifiers & fieldArray[i].getModifiers()) != 0) { fields.add(fieldArray[i]); } } return null; } }); return fields.toArray(new Field[fields.size()]); }
java
public static Field getField(Class<?> clazz, String fieldName) { final String internedName = fieldName.intern(); return traverseHierarchy(clazz, new TraverseTask<Field>() { @Override public Field run(Class<?> clazz) { Field[] fields = clazz.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if (fields[i].getName() == internedName) { return fields[i]; } } return null; } }); }
java
public static Method getMethod(Class<?> clazz, final String methodName, final Class<?>... parameterTypes) { final String internedName = methodName.intern(); return traverseHierarchy(clazz, new TraverseTask<Method>() { @Override public Method run(Class<?> clazz) { Method[] methods = clazz.getDeclaredMethods(); Method res = null; for (int i = 0; i < methods.length; i++) { Method m = methods[i]; if (m.getName() == internedName && arrayContentsEq(parameterTypes, m.getParameterTypes()) && (res == null || res.getReturnType().isAssignableFrom(m.getReturnType()))) { res = m; } } return res; } }); }
java
public static List<Method> getMethods(Class<?> clazz, final Class<? extends Annotation> annotation) { final List<Method> methods = new ArrayList<Method>(); traverseHierarchy(clazz, new TraverseTask<Method>() { @Override public Method run(Class<?> clazz) { Method[] methodArray = clazz.getDeclaredMethods(); for (int i = 0; i < methodArray.length; i++) { Method m = methodArray[i]; if (m.getAnnotation(annotation) != null) { methods.add(m); } } return null; } }); return methods; }
java
public static ArrayList<Element> verifyPath( Element root, ArrayList<Element> path ) { if( root == path.get( 0 ) ) return path; return null; }
java
public T getRecordForRow( Row row ) { Integer recordId = rowToRecordIds.get( row ); if( recordId == null ) return null; return getRecordForId( recordId ); }
java
public static Class<?> getSetterPropertyType( Clazz<?> clazz, String name ) { return propertyValues.getSetterPropertyType(clazz, name); }
java
private Map<String, Object> extractErrorDetailsFromResponse(ClientHttpResponse response) throws IOException { ObjectMapper mapper = new ObjectMapper(new JsonFactory()); try { return mapper.<Map<String, Object>> readValue(response.getBody(), new TypeReference<Map<String, Object>>() { }); } catch (JsonParseException e) { return null; } }
java
private void key(final byte key[]) { int i; final int koffp[] = {0}; final int lr[] = {0, 0}; final int plen = P.length, slen = S.length; for (i = 0; i < plen; i++) { P[i] = P[i] ^ streamtoword(key, koffp); } for (i = 0; i < plen; i += 2) { encipher(lr, 0); P[i] = lr[0]; P[i + 1] = lr[1]; } for (i = 0; i < slen; i += 2) { encipher(lr, 0); S[i] = lr[0]; S[i + 1] = lr[1]; } }
java
public final static int createLocalId() { Storage storage = Storage.getLocalStorageIfSupported(); if( storage == null ) return 0; int increment = 0; String incrementString = storage.getItem( LOCAL_CURRENT_ID_INCREMENT ); try { increment = Integer.parseInt( incrementString ); } catch( Exception e ) { } increment += 1; storage.setItem( LOCAL_CURRENT_ID_INCREMENT, increment + "" ); return -increment; }
java
public <T> void RegisterClazz( Clazz<T> clazz ) { _ensureMap(); if( clazzz.containsKey( clazz.getReflectedClass() ) ) return; clazzz.put( clazz.getReflectedClass(), clazz ); }
java
public void init( String baseUrl, XRPCBatchRequestSender callback ) { this.url = baseUrl + "&locale=" + LocaleInfo.getCurrentLocale().getLocaleName(); this.callback = callback; }
java
private void checkCallService( RequestCallInfo info ) { String service = info.request.service; String interfaceChecksum = info.request.interfaceChecksum; String key = getServiceKey( info ); if( usedServices.containsKey( key ) ) return; ServiceInfo serviceInfo = new ServiceInfo( service, interfaceChecksum ); serviceInfo.id = usedServices.size(); usedServices.put( key, serviceInfo ); }
java
public boolean send() { assert sentRequests == null; sentRequests = new ArrayList<RequestCallInfo>(); // add prepended requests, addPrependedRequests( sentRequests ); // add requests to send while( !requestsToSend.isEmpty() ) sentRequests.add( requestsToSend.remove( 0 ) ); // add appended requests addAppendedRequests( sentRequests ); // prepare payload JSONArray payload = createPayload(); RequestBuilder builderPost = buildMultipart( "payload", payload.toString() ); nbSentBytes += builderPost.getRequestData().length(); try { sentRequest = builderPost.send(); } catch( RequestException e ) { callback.error( RPCErrorCodes.ERROR_REQUEST_SEND, e, this ); return false; } callback.sent( this ); return true; }
java
private RequestBuilder buildMultipart( String name, String value ) { String boundary = "AJAX------" + Math.random() + "" + new Date().getTime(); RequestBuilder builderPost = new RequestBuilder( RequestBuilder.POST, url ); builderPost.setHeader( "Content-Type", "multipart/form-data; charset=utf-8; boundary=" + boundary ); builderPost.setCallback( requestCallback ); String CRLF = "\r\n"; String data = "--" + boundary + CRLF; data += "--" + boundary + CRLF; data += "Content-Disposition: form-data; "; data += "name=\"" + name + "\"" + CRLF + CRLF; data += value + CRLF; data += "--" + boundary + "--" + CRLF; builderPost.setRequestData( data ); return builderPost; }
java
public FormCreator field( Widget widget ) { return field( widget, totalWidth - currentlyUsedWidth - (fFirstItem ? 0 : spacing) ); }
java
public void copy(ConnectionContext source) { this.connection = source.connection; this.session = source.session; this.destination = source.destination; }
java
public static Set<Annotation> getAllAnnotations(Method m) { Set<Annotation> annotationSet = new LinkedHashSet<Annotation>(); Annotation[] annotations = m.getAnnotations(); List<Class<?>> annotationTypes = new ArrayList<Class<?>>(); // Iterate through all annotations of the current class for (Annotation a : annotations) { // Add the current annotation to the result and to the annotation types that needed to be examained for stereotype annotations annotationSet.add(a); annotationTypes.add(a.annotationType()); } if (stereotypeAnnotationClass != null) { while (!annotationTypes.isEmpty()) { Class<?> annotationType = annotationTypes.remove(annotationTypes.size() - 1); if (annotationType.isAnnotationPresent(stereotypeAnnotationClass)) { // If the stereotype annotation is present examine the 'inherited' annotations for (Annotation annotation : annotationType.getAnnotations()) { // add the 'inherited' annotations to be examined for further stereotype annotations annotationTypes.add(annotation.annotationType()); if (!annotation.annotationType().equals(stereotypeAnnotationClass)) { // add the stereotyped annotations to the set annotationSet.add(annotation); } } } } } return annotationSet; }
java
public static <T extends Annotation> T findAnnotation(Method m, Class<T> annotationClazz) { T annotation = m.getAnnotation(annotationClazz); if (annotation != null) { return annotation; } if (stereotypeAnnotationClass != null) { List<Class<?>> annotations = new ArrayList<>(); for (Annotation a : m.getAnnotations()) { annotations.add(a.annotationType()); } return findAnnotation(annotations, annotationClazz); } return null; }
java
public static <T extends Annotation> T findAnnotation(Class<?> clazz, Class<T> annotationClazz) { T annotation = clazz.getAnnotation(annotationClazz); if (annotation != null) { return annotation; } Set<Class<?>> superTypes = ReflectionUtils.getSuperTypes(clazz); for (Class<?> type : superTypes) { annotation = type.getAnnotation(annotationClazz); if (annotation != null) { return annotation; } } if (stereotypeAnnotationClass != null) { List<Class<?>> annotations = new ArrayList<>(); for (Class<?> type : superTypes) { for (Annotation a : type.getAnnotations()) { annotations.add(a.annotationType()); } } return findAnnotation(annotations, annotationClazz); } return null; }
java
public <T extends BasicMessage> void listen(ConsumerConnectionContext context, AbstractBasicMessageListener<T> listener) throws JMSException { if (context == null) { throw new NullPointerException("context must not be null"); } if (listener == null) { throw new NullPointerException("listener must not be null"); } MessageConsumer consumer = context.getMessageConsumer(); if (consumer == null) { throw new NullPointerException("context had a null consumer"); } listener.setConsumerConnectionContext(context); consumer.setMessageListener(listener); }
java
public MessageId send(ProducerConnectionContext context, BasicMessage basicMessage, Map<String, String> headers) throws JMSException { if (context == null) { throw new IllegalArgumentException("context must not be null"); } if (basicMessage == null) { throw new IllegalArgumentException("message must not be null"); } // create the JMS message to be sent Message msg = createMessage(context, basicMessage, headers); // if the message is correlated with another, put the correlation ID in the Message to be sent if (basicMessage.getCorrelationId() != null) { msg.setJMSCorrelationID(basicMessage.getCorrelationId().toString()); } if (basicMessage.getMessageId() != null) { log.debugf("Non-null message ID [%s] will be ignored and a new one generated", basicMessage.getMessageId()); basicMessage.setMessageId(null); } // now send the message to the broker MessageProducer producer = context.getMessageProducer(); if (producer == null) { throw new IllegalStateException("context had a null producer"); } producer.send(msg); // put message ID into the message in case the caller wants to correlate it with another record MessageId messageId = new MessageId(msg.getJMSMessageID()); basicMessage.setMessageId(messageId); return messageId; }
java
public <T extends BasicMessage> RPCConnectionContext sendAndListen(ProducerConnectionContext context, BasicMessage basicMessage, BasicMessageListener<T> responseListener, Map<String, String> headers) throws JMSException { if (context == null) { throw new IllegalArgumentException("context must not be null"); } if (basicMessage == null) { throw new IllegalArgumentException("message must not be null"); } if (responseListener == null) { throw new IllegalArgumentException("response listener must not be null"); } // create the JMS message to be sent Message msg = createMessage(context, basicMessage, headers); // if the message is correlated with another, put the correlation ID in the Message to be sent if (basicMessage.getCorrelationId() != null) { msg.setJMSCorrelationID(basicMessage.getCorrelationId().toString()); } if (basicMessage.getMessageId() != null) { log.debugf("Non-null message ID [%s] will be ignored and a new one generated", basicMessage.getMessageId()); basicMessage.setMessageId(null); } MessageProducer producer = context.getMessageProducer(); if (producer == null) { throw new NullPointerException("Cannot send request-response message - the producer is null"); } // prepare for the response prior to sending the request Session session = context.getSession(); if (session == null) { throw new NullPointerException("Cannot send request-response message - the session is null"); } TemporaryQueue responseQueue = session.createTemporaryQueue(); MessageConsumer responseConsumer = session.createConsumer(responseQueue); RPCConnectionContext rpcContext = new RPCConnectionContext(); rpcContext.copy(context); rpcContext.setDestination(responseQueue); rpcContext.setMessageConsumer(responseConsumer); rpcContext.setRequestMessage(msg); rpcContext.setResponseListener(responseListener); responseListener.setConsumerConnectionContext(rpcContext); responseConsumer.setMessageListener(responseListener); msg.setJMSReplyTo(responseQueue); // now send the message to the broker producer.send(msg); // put message ID into the message in case the caller wants to correlate it with another record MessageId messageId = new MessageId(msg.getJMSMessageID()); basicMessage.setMessageId(messageId); return rpcContext; }
java
public void sendBasicMessageAsync(Session session, BasicMessage msg) { String text = ApiDeserializer.toHawkularFormat(msg); sendTextAsync(session, text); }
java
public void sendBinaryAsync(Session session, InputStream inputStream, ExecutorService threadPool) { if (session == null) { return; } if (inputStream == null) { throw new IllegalArgumentException("inputStream must not be null"); } log.debugf("Attempting to send async binary data to client [%s]", session.getId()); if (session.isOpen()) { if (this.asyncTimeout != null) { // TODO: what to do with timeout? } CopyStreamRunnable runnable = new CopyStreamRunnable(session, inputStream); threadPool.execute(runnable); } return; }
java
public void sendBinarySync(Session session, InputStream inputStream) throws IOException { if (session == null) { return; } if (inputStream == null) { throw new IllegalArgumentException("inputStream must not be null"); } log.debugf("Attempting to send binary data to client [%s]", session.getId()); if (session.isOpen()) { long size = new CopyStreamRunnable(session, inputStream).copyInputToOutput(); log.debugf("Finished sending binary data to client [%s]: size=[%s]", session.getId(), size); } return; }
java
@OnOpen public void uiClientSessionOpen(Session session) { log.infoWsSessionOpened(session.getId(), endpoint); wsEndpoints.getUiClientSessions().addSession(session.getId(), session); WelcomeResponse welcomeResponse = new WelcomeResponse(); // FIXME we should not send the true sessionIds to clients to prevent spoofing. welcomeResponse.setSessionId(session.getId()); try { new WebSocketHelper().sendBasicMessageSync(session, welcomeResponse); } catch (IOException e) { log.warnf(e, "Could not send [%s] to UI client session [%s].", WelcomeResponse.class.getName(), session.getId()); } }
java
private void doStart() throws LifecycleException { tomcat.getServer().addLifecycleListener(new TomcatLifecycleListener()); logger.info("Deploying application to [" + getConfig().getDeployUrl() + "]"); tomcat.start(); // Let's set the port that was used to actually start the application if necessary if (getConfig().getPort() == EmbedVaadinConfig.DEFAULT_PORT) { getConfig().setPort(getTomcat().getConnector().getLocalPort()); } logger.info("Application has been deployed to [" + getConfig().getDeployUrl() + "]"); if (config.shouldOpenBrowser()) { BrowserUtils.openBrowser(getConfig().getOpenBrowserUrl()); } if (isWaiting()) { tomcat.getServer().await(); } }
java
private void doStop() throws LifecycleException { logger.info("Stopping tomcat."); long startTime = System.currentTimeMillis(); tomcat.stop(); long duration = System.currentTimeMillis() - startTime; logger.info("Tomcat shutdown finished in " + duration + " ms."); }
java
public LogTarget addDelegate(Log log) { LogProxyTarget logProxyTarget = new LogProxyTarget(log); this.addTarget(logProxyTarget); return logProxyTarget; }
java
public Object addingService(ServiceReference reference) { HttpService httpService = (HttpService) context.getService(reference); String alias = this.getAlias(); String name = this.getProperty(RESOURCE_NAME); if (name == null) name = alias; try { httpService.registerResources(alias, name, httpContext); } catch (NamespaceException e) { e.printStackTrace(); } return httpService; }
java
public final void setTypeName(final String typeName) { if (typeName == null) { type = LOOKING_AT; } else if (typeName.equalsIgnoreCase(TYPES[0])) { type = MATCHES; } else if (typeName.equalsIgnoreCase(TYPES[1])) { type = LOOKING_AT; } else if (typeName.equalsIgnoreCase(TYPES[2])) { type = FIND; } }
java
public static Reflect onObject(Object object) { if (object == null) { return new Reflect(null, null); } return new Reflect(object, object.getClass()); }
java
public static Reflect onClass(String clazz) throws Exception { return new Reflect(null, ReflectionUtils.getClassForName(clazz)); }
java
public boolean containsField(String name) { if (StringUtils.isNullOrBlank(name)) { return false; } return ClassDescriptorCache.getInstance() .getClassDescriptor(clazz) .getFields(accessAll) .stream() .anyMatch(f -> f.getName().equals(name)); }
java