code
stringlengths
73
34.1k
label
stringclasses
1 value
public String get(int idx) { if ( idx < 0 || idx >= parts.size() ) { throw new IndexOutOfBoundsException(); } return parts.get(idx); }
java
private PathEntry getPathEntry(UriEntry uri) { PathEntry pathEntry = new PathEntry( ContextRouter.MAP_PATH_TYPE, "default"); int length = uri.getLength(); // like /a or / if ( length < 2) return pathEntry; String requestUri = uri.getRequestUri(); ...
java
private void resizeTo( int length ) { if ( length <= 0 ) throw new IllegalArgumentException("length <= 0"); if ( length != buff.length ) { int len = ( length > buff.length ) ? buff.length : length; //System.out.println("resize:"+length); char[...
java
public IStringBuffer append( String str ) { if ( str == null ) throw new NullPointerException(); //check the necessary to resize the buffer. if ( count + str.length() > buff.length ) { resizeTo( (count + str.length()) * 2 + 1 ); } for ( int j ...
java
public IStringBuffer append( char[] chars, int start, int length ) { if ( chars == null ) throw new NullPointerException(); if ( start < 0 ) throw new IndexOutOfBoundsException(); if ( length <= 0 ) throw new IndexOutOfBoundsException(); if ( start...
java
public IStringBuffer append( char[] chars, int start ) { append(chars, start, chars.length - start); return this; }
java
public IStringBuffer append( char c ) { if ( count == buff.length ) { resizeTo( buff.length * 2 + 1 ); } buff[count++] = c; return this; }
java
public char charAt( int idx ) { if ( idx < 0 ) throw new IndexOutOfBoundsException("idx{"+idx+"} < 0"); if ( idx >= count ) throw new IndexOutOfBoundsException("idx{"+idx+"} >= buffer.length"); return buff[idx]; }
java
public IStringBuffer deleteCharAt( int idx ) { if ( idx < 0 ) throw new IndexOutOfBoundsException("idx < 0"); if ( idx >= count ) throw new IndexOutOfBoundsException("idx >= buffer.length"); //here we got a bug for j < count //change over it to count ...
java
public void set(int idx, char chr) { if ( idx < 0 ) throw new IndexOutOfBoundsException("idx < 0"); if ( idx >= count ) throw new IndexOutOfBoundsException("idx >= buffer.length"); buff[idx] = chr; }
java
protected IWord getNextTimeMergedWord(IWord word, int eIdx) throws IOException { int pIdx = TimeUtil.getDateTimeIndex(word.getEntity(eIdx)); if ( pIdx == TimeUtil.DATETIME_NONE ) { return null; } IWord[] wMask = TimeUtil.createDateTimePool(); TimeUtil.fillDateTim...
java
protected IWord getNextDatetimeWord(IWord word, int entityIdx) throws IOException { IWord dWord = super.next(); if ( dWord == null ) { return null; } String[] entity = dWord.getEntity(); if ( entity == null ) { eWordPool.add(dWord); return...
java
private IWord getNumericUnitComposedWord(String numeric, IWord unitWord) { IStringBuffer sb = new IStringBuffer(); sb.clear().append(numeric).append(unitWord.getValue()); IWord wd = new Word(sb.toString(), IWord.T_CJK_WORD); String[] entity = unitWord.getEntity(); int eIdx = ArrayUtil.star...
java
public List<Issue> getIssuesBySummary(String projectKey, String summaryField) throws RedmineException { if ((projectKey != null) && (projectKey.length() > 0)) { return transport.getObjectsList(Issue.class, new BasicNameValuePair("subject", summaryField), new B...
java
public List<SavedQuery> getSavedQueries(String projectKey) throws RedmineException { Set<NameValuePair> params = new HashSet<>(); if ((projectKey != null) && (projectKey.length() > 0)) { params.add(new BasicNameValuePair("project_id", projectKey)); } return transport.getObj...
java
public static <T> void addIfNotNull(JSONWriter writer, String field, T value, JsonObjectWriter<T> objWriter) throws JSONException { if (value == null) return; writer.key(field); writer.object(); objWriter.write(writer, value); writer.endObject(); }
java
public static <T> void addScalarArray(JSONWriter writer, String field, Collection<T> items, JsonObjectWriter<T> objWriter) throws JSONException { writer.key(field); writer.array(); for (T item : items) { objWriter.write(writer, item); } writer.endArray(); }
java
public URI addAPIKey(String uri) { try { final URIBuilder builder = new URIBuilder(uri); if (apiAccessKey != null) { builder.setParameter("key", apiAccessKey); } return builder.build(); } catch (URISyntaxException e) { throw new...
java
public static SSLSocketFactory createSocketFactory(Collection<KeyStore> extraStores) throws KeyStoreException, KeyManagementException { final Collection<X509TrustManager> managers = new ArrayList<>(); for (KeyStore ks : extraStores) { addX509Managers(managers, ks); } /* Add default manager. */ addX509Mana...
java
private static void addX509Managers(final Collection<X509TrustManager> managers, KeyStore ks) throws KeyStoreException, Error { try { final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); for (TrustManager tm : tmf.getTrustManagers()) { ...
java
public <T> T addObject(T object, NameValuePair... params) throws RedmineException { final EntityConfig<T> config = getConfig(object.getClass()); if (config.writer == null) { throw new RuntimeException("can't create object: writer is not implemented or is not registered in RedmineJSONBuilder for...
java
public <T> void deleteChildId(Class<?> parentClass, String parentId, T object, Integer value) throws RedmineException { URI uri = getURIConfigurator().getChildIdURI(parentClass, parentId, object.getClass(), value); HttpDelete httpDelete = new HttpDelete(uri); String response = send(httpDelete); ...
java
public <T extends Identifiable> void deleteObject(Class<T> classs, String id) throws RedmineException { final URI uri = getURIConfigurator().getObjectURI(classs, id); final HttpDelete http = new HttpDelete(uri); send(http); }
java
public <R> R download(String uri, ContentHandler<BasicHttpResponse, R> handler) throws RedmineException { final URI requestUri = configurator.addAPIKey(uri); final HttpGet request = new HttpGet(requestUri); if (onBehalfOfUser != null) { request.addHeader("X-Redmine-Switch-User", onBehalfOf...
java
public <T> T getChildEntry(Class<?> parentClass, String parentId, Class<T> classs, String childId, NameValuePair... params) throws RedmineException { final EntityConfig<T> config = getConfig(classs); final URI uri = getURIConfigurator().getChildIdURI(parentClass, parentId,...
java
public Project addTrackers(Collection<Tracker> trackers) { if (!storage.isPropertySet(TRACKERS)) //checks because trackers storage is not created for new projects storage.set(TRACKERS, new HashSet<>()); storage.get(TRACKERS).addAll(trackers); return this; }
java
public static RedmineManager createUnauthenticated(String uri, HttpClient httpClient) { return createWithUserAuth(uri, null, null, httpClient); }
java
public static RedmineManager createWithUserAuth(String uri, String login, String password) { return createWithUserAuth(uri, login, password, createDefaultHttpClient(uri)); }
java
public static RedmineManager createWithUserAuth(String uri, String login, String password, HttpClient httpClient) { final Transport transport = new Transport( new URIConfigurator(uri, null), httpClient); transport.setCredentials(login, ...
java
public void update() throws RedmineException { String urlSafeTitle = getUrlSafeString(getTitle()); transport.updateChildEntry(Project.class, getProjectKey(), this, urlSafeTitle); }
java
private InputStream decodeStream(String encoding, InputStream initialStream) throws IOException { if (encoding == null) return initialStream; if ("gzip".equals(encoding)) return new GZIPInputStream(initialStream); if ("deflate".equals(encoding)) return new InflaterInputStream(initialStream); throw n...
java
public static void updateCollections(PropertyStorage storage, Transport transport) { storage.getProperties().forEach(e -> { if (Collection.class.isAssignableFrom(e.getKey().getType())) { // found a collection in properties ((Collection) e.getValue()).forEach(i -> { ...
java
public static void writeProject(JSONWriter writer, Project project) throws IllegalArgumentException, JSONException { /* Validate project */ if (project.getName() == null) throw new IllegalArgumentException( "Project name must be set to create a new project"); if (project.getIdentifier() == null) thr...
java
public static <T> String toSimpleJSON(String tag, T object, JsonObjectWriter<T> writer) throws RedmineInternalError { final StringWriter swriter = new StringWriter(); final JSONWriter jsWriter = new JSONWriter(swriter); try { jsWriter.object(); jsWriter.key(tag); jsWriter.object(); writer.write(jsW...
java
public static Router getRouter(Class<? extends Router> routerType) { return routers.computeIfAbsent(routerType, Routers::create); }
java
public Mono<Void> send(GatewayMessage response) { return Mono.defer( () -> outbound .sendObject(Mono.just(response).map(codec::encode).map(TextWebSocketFrame::new)) .then() .doOnSuccessOrError((avoid, th) -> logSend(response, th))); }
java
public Mono<Void> onClose(Disposable disposable) { return Mono.create( sink -> inbound.withConnection( connection -> connection .onDispose(disposable) .onTerminate() .subscribe(sink::succe...
java
public boolean dispose(Long streamId) { boolean result = false; if (streamId != null) { Disposable disposable = subscriptions.remove(streamId); result = disposable != null; if (result) { LOGGER.debug("Dispose subscription by sid={}, session={}", streamId, id); disposable.dispos...
java
@Override public Mono<ServiceDiscovery> start() { return Mono.defer( () -> { Map<String, String> metadata = endpoint != null ? Collections.singletonMap( endpoint.id(), ClusterMetadataCodec.encodeMetadata(endpoint)) : Collect...
java
private static Class<?> parameterizedReturnType(Method method) { Type type = method.getGenericReturnType(); if (type instanceof ParameterizedType) { try { return Class.forName( (((ParameterizedType) type).getActualTypeArguments()[0]).getTypeName()); } catch (ClassNotFoundExceptio...
java
public void calculate(ServiceMessage message) { // client to service eval( message.header(SERVICE_RECV_TIME), message.header(CLIENT_SEND_TIME), (v1, v2) -> clientToServiceTimer.update(v1 - v2, TimeUnit.MILLISECONDS)); // service to client eval( message.header(CLIENT_RECV...
java
public static Builder from(ServiceMessage message) { return ServiceMessage.builder().data(message.data()).headers(message.headers()); }
java
public static ServiceMessage error(int errorType, int errorCode, String errorMessage) { return ServiceMessage.builder() .qualifier(Qualifier.asError(errorType)) .data(new ErrorData(errorCode, errorMessage)) .build(); }
java
void setHeaders(Map<String, String> headers) { this.headers = Collections.unmodifiableMap(new HashMap<>(headers)); }
java
public String header(String name) { Objects.requireNonNull(name); return headers.get(name); }
java
public boolean isError() { String qualifier = qualifier(); return qualifier != null && qualifier.contains(Qualifier.ERROR_NAMESPACE); }
java
public int errorType() { if (!isError()) { throw new IllegalStateException("Message is not an error"); } try { return Integer.parseInt(Qualifier.getQualifierAction(qualifier())); } catch (NumberFormatException e) { throw new IllegalStateException("Error type must be a number"); } ...
java
public static io.scalecube.transport.Address toAddress( io.scalecube.services.transport.api.Address address) { return io.scalecube.transport.Address.create(address.host(), address.port()); }
java
public static io.scalecube.transport.Address[] toAddresses(Address[] addresses) { return Arrays.stream(addresses) .map(ClusterAddresses::toAddress) .toArray(io.scalecube.transport.Address[]::new); }
java
protected final HttpServer prepareHttpServer( LoopResources loopResources, int port, GatewayMetrics metrics) { return HttpServer.create() .tcpConfiguration( tcpServer -> { if (loopResources != null) { tcpServer = tcpServer.runOn(loopResources); }...
java
private <T> T encodeAndTransform( ClientMessage message, BiFunction<ByteBuf, ByteBuf, T> transformer) throws MessageCodecException { ByteBuf dataBuffer = Unpooled.EMPTY_BUFFER; ByteBuf headersBuffer = Unpooled.EMPTY_BUFFER; if (message.hasData(ByteBuf.class)) { dataBuffer = message.data()...
java
public static Address from(String hostAndPort) { String[] split = hostAndPort.split(":"); if (split.length != 2) { throw new IllegalArgumentException(); } String host = split[0]; int port = Integer.parseInt(split[1]); return new Address(host, port); }
java
public static String asString(String namespace, String action) { return DELIMITER + namespace + DELIMITER + action; }
java
public static String getQualifierNamespace(String qualifierAsString) { int pos = qualifierAsString.indexOf(DELIMITER, 1); if (pos == -1) { throw new IllegalArgumentException("Wrong qualifier format: '" + qualifierAsString + "'"); } return qualifierAsString.substring(1, pos); }
java
public static String getQualifierAction(String qualifierAsString) { int pos = qualifierAsString.lastIndexOf(DELIMITER); if (pos == -1) { throw new IllegalArgumentException("Wrong qualifier format: '" + qualifierAsString + "'"); } return qualifierAsString.substring(pos + 1); }
java
public void add(long instrument, long orderId, Side side, long price, long size) { if (orders.containsKey(orderId)) { return; } OrderBook book = books.get(instrument); if (book == null) { return; } Order order = new Order(book, side, price, size); boolean bbo = book.add(side, ...
java
public void modify(long orderId, long size) { Order order = orders.get(orderId); if (order == null) { return; } OrderBook book = order.getOrderBook(); long newSize = Math.max(0, size); boolean bbo = book.update(order.getSide(), order.getPrice(), newSize - order.getRemainingQuant...
java
public long execute(long orderId, long quantity, long price) { Order order = orders.get(orderId); if (order == null) { return 0; } return execute(orderId, order, quantity, price); }
java
public long cancel(long orderId, long quantity) { Order order = orders.get(orderId); if (order == null) { return 0; } OrderBook book = order.getOrderBook(); long remainingQuantity = order.getRemainingQuantity(); long canceledQuantity = Math.min(quantity, remainingQuantity); boolean...
java
public void delete(long orderId) { Order order = orders.get(orderId); if (order == null) { return; } OrderBook book = order.getOrderBook(); boolean bbo = book.update(order.getSide(), order.getPrice(), -order.getRemainingQuantity()); orders.remove(orderId); listener.update(book, bbo...
java
public static Client rsocket(ClientSettings clientSettings) { RSocketClientCodec clientCodec = new RSocketClientCodec( HeadersCodec.getInstance(clientSettings.contentType()), DataCodec.getInstance(clientSettings.contentType())); RSocketClientTransport clientTransport = n...
java
public static Client websocket(ClientSettings clientSettings) { WebsocketClientCodec clientCodec = new WebsocketClientCodec(DataCodec.getInstance(clientSettings.contentType())); WebsocketClientTransport clientTransport = new WebsocketClientTransport(clientSettings, clientCodec, clientSettings.l...
java
public static Client http(ClientSettings clientSettings) { HttpClientCodec clientCodec = new HttpClientCodec(DataCodec.getInstance(clientSettings.contentType())); ClientTransport clientTransport = new HttpClientTransport(clientSettings, clientCodec, clientSettings.loopResources()); return ...
java
public static void main(String[] args) throws Exception { ConfigRegistry configRegistry = ConfigBootstrap.configRegistry(); Config config = configRegistry .objectProperty("io.scalecube.services.examples", Config.class) .value() .orElseThrow(() -> new IllegalStateExce...
java
public <T> Gauge<T> register( final String component, final String methodName, final Gauge<T> gauge) { registry.register( MetricRegistry.name(component, methodName), new Gauge<T>() { @Override public T getValue() { return gauge.getValue(); } })...
java
public static Timer timer(Metrics metrics, String component, String methodName) { if (metrics != null) { return metrics.getTimer(component, methodName); } else { return null; } }
java
public static Counter counter(Metrics metrics, String component, String methodName) { if (metrics != null) { return metrics.getCounter(component, methodName); } else { return null; } }
java
public Order add(long orderId, long size) { Order order = new Order(this, orderId, size); orders.add(order); return order; }
java
public long match(long orderId, Side side, long size, EmitterProcessor<MatchOrder> matchEmmiter) { long quantity = size; while (quantity > 0 && !orders.isEmpty()) { Order order = orders.get(0); long orderQuantity = order.size(); if (orderQuantity > quantity) { order.reduce(quantity); ...
java
public static DelegatedLoopResources newServerLoopResources(EventLoopGroup workerGroup) { EventLoopGroup bossGroup = Epoll.isAvailable() ? new EpollEventLoopGroup(BOSS_THREADS_NUM, BOSS_THREAD_FACTORY) : new NioEventLoopGroup(BOSS_THREADS_NUM, BOSS_THREAD_FACTORY); return new Del...
java
public boolean hasData(Class<?> dataClass) { if (dataClass == null) { return false; } return dataClass.isPrimitive() ? hasData() : dataClass.isInstance(data); }
java
public Collection<ServiceReference> serviceReferences() { return serviceRegistrations.stream() .flatMap(sr -> sr.methods().stream().map(sm -> new ServiceReference(sm, sr, this))) .collect(Collectors.toList()); }
java
public Mono<Void> oneWay(ServiceMessage request) { return Mono.defer(() -> requestOne(request, Void.class).then()); }
java
public Mono<ServiceMessage> requestOne(ServiceMessage request, Class<?> responseType) { return Mono.defer( () -> { String qualifier = request.qualifier(); if (methodRegistry.containsInvoker(qualifier)) { // local service. return methodRegistry .getInvoker(requ...
java
public Mono<ServiceMessage> requestOne( ServiceMessage request, Class<?> responseType, Address address) { return Mono.defer( () -> { requireNonNull(address, "requestOne address parameter is required and must not be null"); requireNonNull(transport, "transport is required and must n...
java
public Flux<ServiceMessage> requestMany(ServiceMessage request, Class<?> responseType) { return Flux.defer( () -> { String qualifier = request.qualifier(); if (methodRegistry.containsInvoker(qualifier)) { // local service. return methodRegistry .getInvoker(req...
java
public Flux<ServiceMessage> requestMany( ServiceMessage request, Class<?> responseType, Address address) { return Flux.defer( () -> { requireNonNull(address, "requestMany address parameter is required and must not be null"); requireNonNull(transport, "transport is required and must...
java
public Flux<ServiceMessage> requestBidirectional( Publisher<ServiceMessage> publisher, Class<?> responseType) { return Flux.from(publisher) .switchOnFirst( (first, messages) -> { if (first.hasValue()) { ServiceMessage request = first.get(); Str...
java
public Flux<ServiceMessage> requestBidirectional( Publisher<ServiceMessage> publisher, Class<?> responseType, Address address) { return Flux.defer( () -> { requireNonNull( address, "requestBidirectional address parameter is required and must not be null"); requireNonN...
java
@SuppressWarnings("unchecked") public <T> T api(Class<T> serviceInterface) { final ServiceCall serviceCall = this; final Map<Method, MethodInfo> genericReturnTypes = Reflect.methodsInfo(serviceInterface); // noinspection unchecked return (T) Proxy.newProxyInstance( getClass().get...
java
private Optional<Object> toStringOrEqualsOrHashCode( String method, Class<?> serviceInterface, Object... args) { switch (method) { case "toString": return Optional.of(serviceInterface.toString()); case "equals": return Optional.of(serviceInterface.equals(args[0])); case "has...
java
public static Microservices inject(Microservices microservices, Collection<Object> services) { services.forEach( service -> Arrays.stream(service.getClass().getDeclaredFields()) .forEach(field -> injectField(microservices, field, service))); services.forEach(service -> proces...
java
public static Type parameterizedType(Object object) { if (object != null) { Type type = object.getClass().getGenericSuperclass(); if (type instanceof ParameterizedType) { return ((ParameterizedType) type).getActualTypeArguments()[0]; } } return Object.class; }
java
public static Type parameterizedRequestType(Method method) { if (method != null && method.getGenericParameterTypes().length > 0) { Type type = method.getGenericParameterTypes()[0]; if (type instanceof ParameterizedType) { return ((ParameterizedType) type).getActualTypeArguments()[0]; } ...
java
public static Collection<Class<?>> serviceInterfaces(Object serviceObject) { Class<?>[] interfaces = serviceObject.getClass().getInterfaces(); return Arrays.stream(interfaces) .filter(interfaceClass -> interfaceClass.isAnnotationPresent(Service.class)) .collect(Collectors.toList()); }
java
public static void validateMethodOrThrow(Method method) { Class<?> returnType = method.getReturnType(); if (returnType.equals(Void.TYPE)) { return; } else if (!Publisher.class.isAssignableFrom(returnType)) { throw new UnsupportedOperationException("Service method return type can be Publisher onl...
java
public static void main(String[] args) throws InterruptedException { Microservices ms1 = Microservices.builder() .discovery(ScalecubeServiceDiscovery::new) .transport(ServiceTransports::rsocketServiceTransport) .defaultErrorMapper(new ServiceAProviderErrorMapper()) // def...
java
public Mono<ServiceMessage> invokeOne( ServiceMessage message, BiFunction<ServiceMessage, Class<?>, ServiceMessage> dataDecoder) { return Mono.defer(() -> Mono.from(invoke(toRequest(message, dataDecoder)))) .map(this::toResponse) .onErrorResume(throwable -> Mono.just(errorMapper.toMessage(thro...
java
public Flux<ServiceMessage> invokeMany( ServiceMessage message, BiFunction<ServiceMessage, Class<?>, ServiceMessage> dataDecoder) { return Flux.defer(() -> Flux.from(invoke(toRequest(message, dataDecoder)))) .map(this::toResponse) .onErrorResume(throwable -> Flux.just(errorMapper.toMessage(thr...
java
public Flux<ServiceMessage> invokeBidirectional( Publisher<ServiceMessage> publisher, BiFunction<ServiceMessage, Class<?>, ServiceMessage> dataDecoder) { return Flux.from(publisher) .map(message -> toRequest(message, dataDecoder)) .transform(this::invoke) .map(this::toResponse) ...
java
public ServiceMessage decode(ByteBuf dataBuffer, ByteBuf headersBuffer) throws MessageCodecException { ServiceMessage.Builder builder = ServiceMessage.builder(); if (dataBuffer.isReadable()) { builder.data(dataBuffer); } if (headersBuffer.isReadable()) { try (ByteBufInputStream stream...
java
public static ServiceMessage decodeData(ServiceMessage message, Class<?> dataType) throws MessageCodecException { if (dataType == null || !message.hasData(ByteBuf.class) || ((ByteBuf) message.data()).readableBytes() == 0) { return message; } Object data; Class<?> targetType ...
java
public void enter(long orderId, Side side, long price, long size) { if (orders.containsKey(orderId)) { return; } if (side == Side.BUY) { buy(orderId, price, size); } else { sell(orderId, price, size); } }
java
public void cancel(long orderId, long size) { Order order = orders.get(orderId); if (order == null) { return; } long remainingQuantity = order.size(); if (size >= remainingQuantity) { return; } if (size > 0) { order.resize(size); } else { delete(order); o...
java
public static <T> Optional<T> findFirst(Class<T> clazz) { ServiceLoader<T> load = ServiceLoader.load(clazz); return StreamSupport.stream(load.spliterator(), false).findFirst(); }
java
public static <T> Optional<T> findFirst(Class<T> clazz, Predicate<? super T> predicate) { ServiceLoader<T> load = ServiceLoader.load(clazz); Stream<T> stream = StreamSupport.stream(load.spliterator(), false); return stream.filter(predicate).findFirst(); }
java
public static <T> Stream<T> findAll(Class<T> clazz) { ServiceLoader<T> load = ServiceLoader.load(clazz); return StreamSupport.stream(load.spliterator(), false); }
java
@RequiresTransaction public void put( String key, Document document ) { database.put(key, document); }
java
public <V> V runInTransaction( Callable<V> operation, int retryCountOnLockTimeout, String... keysToLock ) { // Start a transaction ... Transactions txns = repoEnv.getTransactions(); int retryCount = retryCountOnLockTimeout; try { Transactions.Transaction txn = txns.begin(); ...
java
public void setStrategy( double median, double standardDeviation, int sigma ) { this.bucketingStrategy = new StandardDeviationBucketingStrategy(median, standardDeviation, sigma); this.bucketWidth = null; }
java